SemaDecl.cpp revision c34ee5ef2b267a683c432ba0c342f7c3a14889d6
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 "clang/AST/APValue.h" 16#include "clang/AST/ASTConsumer.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/DeclObjC.h" 19#include "clang/AST/ExprCXX.h" 20#include "clang/Parse/DeclSpec.h" 21#include "clang/Basic/DiagnosticSema.h" 22#include "clang/Basic/TargetInfo.h" 23#include "clang/Basic/SourceManager.h" 24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's) 25#include "clang/Lex/Preprocessor.h" 26#include "clang/Lex/HeaderSearch.h" 27#include "llvm/ADT/SmallSet.h" 28#include "llvm/ADT/STLExtras.h" 29#include <algorithm> 30#include <functional> 31 32using namespace clang; 33 34Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, Scope *S, 35 const CXXScopeSpec *SS) { 36 DeclContext *DC = 0; 37 38 if (SS) { 39 if (SS->isInvalid()) 40 return 0; 41 DC = static_cast<DeclContext*>(SS->getScopeRep()); 42 } 43 LookupResult Result = DC ? 44 LookupDeclInContext(&II, Decl::IDNS_Ordinary, DC) : 45 LookupDeclInScope(&II, Decl::IDNS_Ordinary, S); 46 47 Decl *IIDecl = 0; 48 switch (Result.getKind()) { 49 case LookupResult::NotFound: 50 case LookupResult::FoundOverloaded: 51 case LookupResult::AmbiguousBaseSubobjectTypes: 52 case LookupResult::AmbiguousBaseSubobjects: 53 // FIXME: In the event of an ambiguous lookup, we could visit all of 54 // the entities found to determine whether they are all types. This 55 // might provide better diagnostics. 56 return 0; 57 58 case LookupResult::Found: 59 IIDecl = Result.getAsDecl(); 60 break; 61 } 62 63 if (isa<TypedefDecl>(IIDecl) || 64 isa<ObjCInterfaceDecl>(IIDecl) || 65 isa<TagDecl>(IIDecl) || 66 isa<TemplateTypeParmDecl>(IIDecl)) 67 return IIDecl; 68 return 0; 69} 70 71DeclContext *Sema::getContainingDC(DeclContext *DC) { 72 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 73 // A C++ out-of-line method will return to the file declaration context. 74 if (MD->isOutOfLineDefinition()) 75 return MD->getLexicalDeclContext(); 76 77 // A C++ inline method is parsed *after* the topmost class it was declared in 78 // is fully parsed (it's "complete"). 79 // The parsing of a C++ inline method happens at the declaration context of 80 // the topmost (non-nested) class it is lexically declared in. 81 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record."); 82 DC = MD->getParent(); 83 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 84 DC = RD; 85 86 // Return the declaration context of the topmost class the inline method is 87 // declared in. 88 return DC; 89 } 90 91 if (isa<ObjCMethodDecl>(DC)) 92 return Context.getTranslationUnitDecl(); 93 94 if (Decl *D = dyn_cast<Decl>(DC)) 95 return D->getLexicalDeclContext(); 96 97 return DC->getLexicalParent(); 98} 99 100void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 101 assert(getContainingDC(DC) == CurContext && 102 "The next DeclContext should be lexically contained in the current one."); 103 CurContext = DC; 104 S->setEntity(DC); 105} 106 107void Sema::PopDeclContext() { 108 assert(CurContext && "DeclContext imbalance!"); 109 110 CurContext = getContainingDC(CurContext); 111} 112 113/// Add this decl to the scope shadowed decl chains. 114void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) { 115 // Move up the scope chain until we find the nearest enclosing 116 // non-transparent context. The declaration will be introduced into this 117 // scope. 118 while (S->getEntity() && 119 ((DeclContext *)S->getEntity())->isTransparentContext()) 120 S = S->getParent(); 121 122 S->AddDecl(D); 123 124 // Add scoped declarations into their context, so that they can be 125 // found later. Declarations without a context won't be inserted 126 // into any context. 127 CurContext->addDecl(D); 128 129 // C++ [basic.scope]p4: 130 // -- exactly one declaration shall declare a class name or 131 // enumeration name that is not a typedef name and the other 132 // declarations shall all refer to the same object or 133 // enumerator, or all refer to functions and function templates; 134 // in this case the class name or enumeration name is hidden. 135 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 136 // We are pushing the name of a tag (enum or class). 137 if (CurContext->getLookupContext() 138 == TD->getDeclContext()->getLookupContext()) { 139 // We're pushing the tag into the current context, which might 140 // require some reshuffling in the identifier resolver. 141 IdentifierResolver::iterator 142 I = IdResolver.begin(TD->getDeclName(), CurContext, 143 false/*LookInParentCtx*/), 144 IEnd = IdResolver.end(); 145 if (I != IEnd && isDeclInScope(*I, CurContext, S)) { 146 NamedDecl *PrevDecl = *I; 147 for (; I != IEnd && isDeclInScope(*I, CurContext, S); 148 PrevDecl = *I, ++I) { 149 if (TD->declarationReplaces(*I)) { 150 // This is a redeclaration. Remove it from the chain and 151 // break out, so that we'll add in the shadowed 152 // declaration. 153 S->RemoveDecl(*I); 154 if (PrevDecl == *I) { 155 IdResolver.RemoveDecl(*I); 156 IdResolver.AddDecl(TD); 157 return; 158 } else { 159 IdResolver.RemoveDecl(*I); 160 break; 161 } 162 } 163 } 164 165 // There is already a declaration with the same name in the same 166 // scope, which is not a tag declaration. It must be found 167 // before we find the new declaration, so insert the new 168 // declaration at the end of the chain. 169 IdResolver.AddShadowedDecl(TD, PrevDecl); 170 171 return; 172 } 173 } 174 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) { 175 // We are pushing the name of a function, which might be an 176 // overloaded name. 177 FunctionDecl *FD = cast<FunctionDecl>(D); 178 DeclContext *DC = FD->getDeclContext()->getLookupContext(); 179 IdentifierResolver::iterator Redecl 180 = std::find_if(IdResolver.begin(FD->getDeclName(), DC, 181 false/*LookInParentCtx*/), 182 IdResolver.end(), 183 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces), 184 FD)); 185 if (Redecl != IdResolver.end()) { 186 // There is already a declaration of a function on our 187 // IdResolver chain. Replace it with this declaration. 188 S->RemoveDecl(*Redecl); 189 IdResolver.RemoveDecl(*Redecl); 190 } 191 } 192 193 IdResolver.AddDecl(D); 194} 195 196void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 197 if (S->decl_empty()) return; 198 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 199 "Scope shouldn't contain decls!"); 200 201 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 202 I != E; ++I) { 203 Decl *TmpD = static_cast<Decl*>(*I); 204 assert(TmpD && "This decl didn't get pushed??"); 205 206 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 207 NamedDecl *D = cast<NamedDecl>(TmpD); 208 209 if (!D->getDeclName()) continue; 210 211 // Remove this name from our lexical scope. 212 IdResolver.RemoveDecl(D); 213 } 214} 215 216/// getObjCInterfaceDecl - Look up a for a class declaration in the scope. 217/// return 0 if one not found. 218ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) { 219 // The third "scope" argument is 0 since we aren't enabling lazy built-in 220 // creation from this context. 221 Decl *IDecl = LookupDeclInScope(Id, Decl::IDNS_Ordinary, 0); 222 223 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 224} 225 226/// getNonFieldDeclScope - Retrieves the innermost scope, starting 227/// from S, where a non-field would be declared. This routine copes 228/// with the difference between C and C++ scoping rules in structs and 229/// unions. For example, the following code is well-formed in C but 230/// ill-formed in C++: 231/// @code 232/// struct S6 { 233/// enum { BAR } e; 234/// }; 235/// 236/// void test_S6() { 237/// struct S6 a; 238/// a.e = BAR; 239/// } 240/// @endcode 241/// For the declaration of BAR, this routine will return a different 242/// scope. The scope S will be the scope of the unnamed enumeration 243/// within S6. In C++, this routine will return the scope associated 244/// with S6, because the enumeration's scope is a transparent 245/// context but structures can contain non-field names. In C, this 246/// routine will return the translation unit scope, since the 247/// enumeration's scope is a transparent context and structures cannot 248/// contain non-field names. 249Scope *Sema::getNonFieldDeclScope(Scope *S) { 250 while (((S->getFlags() & Scope::DeclScope) == 0) || 251 (S->getEntity() && 252 ((DeclContext *)S->getEntity())->isTransparentContext()) || 253 (S->isClassScope() && !getLangOptions().CPlusPlus)) 254 S = S->getParent(); 255 return S; 256} 257 258/// LookupDeclInScope - Look up the inner-most declaration in the specified 259/// namespace. NamespaceNameOnly - during lookup only namespace names 260/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1 261/// 'When looking up a namespace-name in a using-directive or 262/// namespace-alias-definition, only namespace names are considered.' 263/// 264/// Note: The use of this routine is deprecated. Please use 265/// LookupName, LookupQualifiedName, or LookupParsedName instead. 266Sema::LookupResult 267Sema::LookupDeclInScope(DeclarationName Name, unsigned NSI, Scope *S, 268 bool LookInParent) { 269 LookupCriteria::NameKind Kind; 270 if (NSI == Decl::IDNS_Ordinary) { 271 Kind = LookupCriteria::Ordinary; 272 } else if (NSI == Decl::IDNS_Tag) 273 Kind = LookupCriteria::Tag; 274 else { 275 assert(NSI == Decl::IDNS_Member &&"Unable to grok LookupDecl NSI argument"); 276 Kind = LookupCriteria::Member; 277 } 278 // Unqualified lookup 279 return LookupName(S, Name, 280 LookupCriteria(Kind, !LookInParent, 281 getLangOptions().CPlusPlus)); 282} 283 284Sema::LookupResult 285Sema::LookupDeclInContext(DeclarationName Name, unsigned NSI, 286 const DeclContext *LookupCtx, 287 bool LookInParent) { 288 assert(LookupCtx && "LookupDeclInContext(): Missing DeclContext"); 289 LookupCriteria::NameKind Kind; 290 if (NSI == Decl::IDNS_Ordinary) { 291 Kind = LookupCriteria::Ordinary; 292 } else if (NSI == Decl::IDNS_Tag) 293 Kind = LookupCriteria::Tag; 294 else { 295 assert(NSI == Decl::IDNS_Member &&"Unable to grok LookupDecl NSI argument"); 296 Kind = LookupCriteria::Member; 297 } 298 return LookupQualifiedName(const_cast<DeclContext *>(LookupCtx), Name, 299 LookupCriteria(Kind, !LookInParent, 300 getLangOptions().CPlusPlus)); 301} 302 303void Sema::InitBuiltinVaListType() { 304 if (!Context.getBuiltinVaListType().isNull()) 305 return; 306 307 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list"); 308 Decl *VaDecl = LookupDeclInScope(VaIdent, Decl::IDNS_Ordinary, TUScope); 309 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl); 310 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef)); 311} 312 313/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope. 314/// lazily create a decl for it. 315NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 316 Scope *S) { 317 Builtin::ID BID = (Builtin::ID)bid; 318 319 if (Context.BuiltinInfo.hasVAListUse(BID)) 320 InitBuiltinVaListType(); 321 322 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context); 323 FunctionDecl *New = FunctionDecl::Create(Context, 324 Context.getTranslationUnitDecl(), 325 SourceLocation(), II, R, 326 FunctionDecl::Extern, false); 327 328 // Create Decl objects for each parameter, adding them to the 329 // FunctionDecl. 330 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) { 331 llvm::SmallVector<ParmVarDecl*, 16> Params; 332 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) 333 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0, 334 FT->getArgType(i), VarDecl::None, 0)); 335 New->setParams(Context, &Params[0], Params.size()); 336 } 337 338 339 340 // TUScope is the translation-unit scope to insert this function into. 341 // FIXME: This is hideous. We need to teach PushOnScopeChains to 342 // relate Scopes to DeclContexts, and probably eliminate CurContext 343 // entirely, but we're not there yet. 344 DeclContext *SavedContext = CurContext; 345 CurContext = Context.getTranslationUnitDecl(); 346 PushOnScopeChains(New, TUScope); 347 CurContext = SavedContext; 348 return New; 349} 350 351/// GetStdNamespace - This method gets the C++ "std" namespace. This is where 352/// everything from the standard library is defined. 353NamespaceDecl *Sema::GetStdNamespace() { 354 if (!StdNamespace) { 355 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std"); 356 DeclContext *Global = Context.getTranslationUnitDecl(); 357 Decl *Std = LookupDeclInContext(StdIdent, Decl::IDNS_Ordinary, Global); 358 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std); 359 } 360 return StdNamespace; 361} 362 363/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name 364/// and scope as a previous declaration 'Old'. Figure out how to resolve this 365/// situation, merging decls or emitting diagnostics as appropriate. 366/// 367TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) { 368 bool objc_types = false; 369 // Allow multiple definitions for ObjC built-in typedefs. 370 // FIXME: Verify the underlying types are equivalent! 371 if (getLangOptions().ObjC1) { 372 const IdentifierInfo *TypeID = New->getIdentifier(); 373 switch (TypeID->getLength()) { 374 default: break; 375 case 2: 376 if (!TypeID->isStr("id")) 377 break; 378 Context.setObjCIdType(New); 379 objc_types = true; 380 break; 381 case 5: 382 if (!TypeID->isStr("Class")) 383 break; 384 Context.setObjCClassType(New); 385 objc_types = true; 386 return New; 387 case 3: 388 if (!TypeID->isStr("SEL")) 389 break; 390 Context.setObjCSelType(New); 391 objc_types = true; 392 return New; 393 case 8: 394 if (!TypeID->isStr("Protocol")) 395 break; 396 Context.setObjCProtoType(New->getUnderlyingType()); 397 objc_types = true; 398 return New; 399 } 400 // Fall through - the typedef name was not a builtin type. 401 } 402 // Verify the old decl was also a type. 403 TypeDecl *Old = dyn_cast<TypeDecl>(OldD); 404 if (!Old) { 405 Diag(New->getLocation(), diag::err_redefinition_different_kind) 406 << New->getDeclName(); 407 if (!objc_types) 408 Diag(OldD->getLocation(), diag::note_previous_definition); 409 return New; 410 } 411 412 // Determine the "old" type we'll use for checking and diagnostics. 413 QualType OldType; 414 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old)) 415 OldType = OldTypedef->getUnderlyingType(); 416 else 417 OldType = Context.getTypeDeclType(Old); 418 419 // If the typedef types are not identical, reject them in all languages and 420 // with any extensions enabled. 421 422 if (OldType != New->getUnderlyingType() && 423 Context.getCanonicalType(OldType) != 424 Context.getCanonicalType(New->getUnderlyingType())) { 425 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 426 << New->getUnderlyingType() << OldType; 427 if (!objc_types) 428 Diag(Old->getLocation(), diag::note_previous_definition); 429 return New; 430 } 431 if (objc_types) return New; 432 if (getLangOptions().Microsoft) return New; 433 434 // C++ [dcl.typedef]p2: 435 // In a given non-class scope, a typedef specifier can be used to 436 // redefine the name of any type declared in that scope to refer 437 // to the type to which it already refers. 438 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext)) 439 return New; 440 441 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1). 442 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if 443 // *either* declaration is in a system header. The code below implements 444 // this adhoc compatibility rule. FIXME: The following code will not 445 // work properly when compiling ".i" files (containing preprocessed output). 446 if (PP.getDiagnostics().getSuppressSystemWarnings()) { 447 SourceManager &SrcMgr = Context.getSourceManager(); 448 if (SrcMgr.isInSystemHeader(Old->getLocation())) 449 return New; 450 if (SrcMgr.isInSystemHeader(New->getLocation())) 451 return New; 452 } 453 454 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 455 Diag(Old->getLocation(), diag::note_previous_definition); 456 return New; 457} 458 459/// DeclhasAttr - returns true if decl Declaration already has the target 460/// attribute. 461static bool DeclHasAttr(const Decl *decl, const Attr *target) { 462 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext()) 463 if (attr->getKind() == target->getKind()) 464 return true; 465 466 return false; 467} 468 469/// MergeAttributes - append attributes from the Old decl to the New one. 470static void MergeAttributes(Decl *New, Decl *Old) { 471 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp; 472 473 while (attr) { 474 tmp = attr; 475 attr = attr->getNext(); 476 477 if (!DeclHasAttr(New, tmp)) { 478 tmp->setInherited(true); 479 New->addAttr(tmp); 480 } else { 481 tmp->setNext(0); 482 delete(tmp); 483 } 484 } 485 486 Old->invalidateAttrs(); 487} 488 489/// MergeFunctionDecl - We just parsed a function 'New' from 490/// declarator D which has the same name and scope as a previous 491/// declaration 'Old'. Figure out how to resolve this situation, 492/// merging decls or emitting diagnostics as appropriate. 493/// Redeclaration will be set true if this New is a redeclaration OldD. 494/// 495/// In C++, New and Old must be declarations that are not 496/// overloaded. Use IsOverload to determine whether New and Old are 497/// overloaded, and to select the Old declaration that New should be 498/// merged with. 499FunctionDecl * 500Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) { 501 assert(!isa<OverloadedFunctionDecl>(OldD) && 502 "Cannot merge with an overloaded function declaration"); 503 504 Redeclaration = false; 505 // Verify the old decl was also a function. 506 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD); 507 if (!Old) { 508 Diag(New->getLocation(), diag::err_redefinition_different_kind) 509 << New->getDeclName(); 510 Diag(OldD->getLocation(), diag::note_previous_definition); 511 return New; 512 } 513 514 // Determine whether the previous declaration was a definition, 515 // implicit declaration, or a declaration. 516 diag::kind PrevDiag; 517 if (Old->isThisDeclarationADefinition()) 518 PrevDiag = diag::note_previous_definition; 519 else if (Old->isImplicit()) 520 PrevDiag = diag::note_previous_implicit_declaration; 521 else 522 PrevDiag = diag::note_previous_declaration; 523 524 QualType OldQType = Context.getCanonicalType(Old->getType()); 525 QualType NewQType = Context.getCanonicalType(New->getType()); 526 527 if (getLangOptions().CPlusPlus) { 528 // (C++98 13.1p2): 529 // Certain function declarations cannot be overloaded: 530 // -- Function declarations that differ only in the return type 531 // cannot be overloaded. 532 QualType OldReturnType 533 = cast<FunctionType>(OldQType.getTypePtr())->getResultType(); 534 QualType NewReturnType 535 = cast<FunctionType>(NewQType.getTypePtr())->getResultType(); 536 if (OldReturnType != NewReturnType) { 537 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 538 Diag(Old->getLocation(), PrevDiag); 539 Redeclaration = true; 540 return New; 541 } 542 543 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 544 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 545 if (OldMethod && NewMethod) { 546 // -- Member function declarations with the same name and the 547 // same parameter types cannot be overloaded if any of them 548 // is a static member function declaration. 549 if (OldMethod->isStatic() || NewMethod->isStatic()) { 550 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 551 Diag(Old->getLocation(), PrevDiag); 552 return New; 553 } 554 555 // C++ [class.mem]p1: 556 // [...] A member shall not be declared twice in the 557 // member-specification, except that a nested class or member 558 // class template can be declared and then later defined. 559 if (OldMethod->getLexicalDeclContext() == 560 NewMethod->getLexicalDeclContext()) { 561 unsigned NewDiag; 562 if (isa<CXXConstructorDecl>(OldMethod)) 563 NewDiag = diag::err_constructor_redeclared; 564 else if (isa<CXXDestructorDecl>(NewMethod)) 565 NewDiag = diag::err_destructor_redeclared; 566 else if (isa<CXXConversionDecl>(NewMethod)) 567 NewDiag = diag::err_conv_function_redeclared; 568 else 569 NewDiag = diag::err_member_redeclared; 570 571 Diag(New->getLocation(), NewDiag); 572 Diag(Old->getLocation(), PrevDiag); 573 } 574 } 575 576 // (C++98 8.3.5p3): 577 // All declarations for a function shall agree exactly in both the 578 // return type and the parameter-type-list. 579 if (OldQType == NewQType) { 580 // We have a redeclaration. 581 MergeAttributes(New, Old); 582 Redeclaration = true; 583 return MergeCXXFunctionDecl(New, Old); 584 } 585 586 // Fall through for conflicting redeclarations and redefinitions. 587 } 588 589 // C: Function types need to be compatible, not identical. This handles 590 // duplicate function decls like "void f(int); void f(enum X);" properly. 591 if (!getLangOptions().CPlusPlus && 592 Context.typesAreCompatible(OldQType, NewQType)) { 593 MergeAttributes(New, Old); 594 Redeclaration = true; 595 return New; 596 } 597 598 // A function that has already been declared has been redeclared or defined 599 // with a different type- show appropriate diagnostic 600 601 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 602 // TODO: This is totally simplistic. It should handle merging functions 603 // together etc, merging extern int X; int X; ... 604 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 605 Diag(Old->getLocation(), PrevDiag); 606 return New; 607} 608 609/// Predicate for C "tentative" external object definitions (C99 6.9.2). 610static bool isTentativeDefinition(VarDecl *VD) { 611 if (VD->isFileVarDecl()) 612 return (!VD->getInit() && 613 (VD->getStorageClass() == VarDecl::None || 614 VD->getStorageClass() == VarDecl::Static)); 615 return false; 616} 617 618/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors 619/// when dealing with C "tentative" external object definitions (C99 6.9.2). 620void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) { 621 bool VDIsTentative = isTentativeDefinition(VD); 622 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType(); 623 624 // FIXME: I don't think this will actually see all of the 625 // redefinitions. Can't we check this property on-the-fly? 626 for (IdentifierResolver::iterator 627 I = IdResolver.begin(VD->getIdentifier(), 628 VD->getDeclContext(), false/*LookInParentCtx*/), 629 E = IdResolver.end(); I != E; ++I) { 630 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) { 631 VarDecl *OldDecl = dyn_cast<VarDecl>(*I); 632 633 // Handle the following case: 634 // int a[10]; 635 // int a[]; - the code below makes sure we set the correct type. 636 // int a[11]; - this is an error, size isn't 10. 637 if (OldDecl && VDIsTentative && VDIsIncompleteArray && 638 OldDecl->getType()->isConstantArrayType()) 639 VD->setType(OldDecl->getType()); 640 641 // Check for "tentative" definitions. We can't accomplish this in 642 // MergeVarDecl since the initializer hasn't been attached. 643 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative) 644 continue; 645 646 // Handle __private_extern__ just like extern. 647 if (OldDecl->getStorageClass() != VarDecl::Extern && 648 OldDecl->getStorageClass() != VarDecl::PrivateExtern && 649 VD->getStorageClass() != VarDecl::Extern && 650 VD->getStorageClass() != VarDecl::PrivateExtern) { 651 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName(); 652 Diag(OldDecl->getLocation(), diag::note_previous_definition); 653 } 654 } 655 } 656} 657 658/// MergeVarDecl - We just parsed a variable 'New' which has the same name 659/// and scope as a previous declaration 'Old'. Figure out how to resolve this 660/// situation, merging decls or emitting diagnostics as appropriate. 661/// 662/// Tentative definition rules (C99 6.9.2p2) are checked by 663/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 664/// definitions here, since the initializer hasn't been attached. 665/// 666VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) { 667 // Verify the old decl was also a variable. 668 VarDecl *Old = dyn_cast<VarDecl>(OldD); 669 if (!Old) { 670 Diag(New->getLocation(), diag::err_redefinition_different_kind) 671 << New->getDeclName(); 672 Diag(OldD->getLocation(), diag::note_previous_definition); 673 return New; 674 } 675 676 MergeAttributes(New, Old); 677 678 // Merge the types 679 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType()); 680 if (MergedT.isNull()) { 681 Diag(New->getLocation(), diag::err_redefinition_different_type) 682 << New->getDeclName(); 683 Diag(Old->getLocation(), diag::note_previous_definition); 684 return New; 685 } 686 New->setType(MergedT); 687 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 688 if (New->getStorageClass() == VarDecl::Static && 689 (Old->getStorageClass() == VarDecl::None || 690 Old->getStorageClass() == VarDecl::Extern)) { 691 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 692 Diag(Old->getLocation(), diag::note_previous_definition); 693 return New; 694 } 695 // C99 6.2.2p4: Check if we have a non-static decl followed by a static. 696 if (New->getStorageClass() != VarDecl::Static && 697 Old->getStorageClass() == VarDecl::Static) { 698 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 699 Diag(Old->getLocation(), diag::note_previous_definition); 700 return New; 701 } 702 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 703 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) { 704 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 705 Diag(Old->getLocation(), diag::note_previous_definition); 706 } 707 return New; 708} 709 710/// CheckParmsForFunctionDef - Check that the parameters of the given 711/// function are appropriate for the definition of a function. This 712/// takes care of any checks that cannot be performed on the 713/// declaration itself, e.g., that the types of each of the function 714/// parameters are complete. 715bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) { 716 bool HasInvalidParm = false; 717 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 718 ParmVarDecl *Param = FD->getParamDecl(p); 719 720 // C99 6.7.5.3p4: the parameters in a parameter type list in a 721 // function declarator that is part of a function definition of 722 // that function shall not have incomplete type. 723 if (!Param->isInvalidDecl() && 724 DiagnoseIncompleteType(Param->getLocation(), Param->getType(), 725 diag::err_typecheck_decl_incomplete_type)) { 726 Param->setInvalidDecl(); 727 HasInvalidParm = true; 728 } 729 730 // C99 6.9.1p5: If the declarator includes a parameter type list, the 731 // declaration of each parameter shall include an identifier. 732 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus) 733 Diag(Param->getLocation(), diag::err_parameter_name_omitted); 734 } 735 736 return HasInvalidParm; 737} 738 739/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 740/// no declarator (e.g. "struct foo;") is parsed. 741Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) { 742 TagDecl *Tag 743 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep())); 744 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 745 if (!Record->getDeclName() && Record->isDefinition() && 746 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 747 return BuildAnonymousStructOrUnion(S, DS, Record); 748 749 // Microsoft allows unnamed struct/union fields. Don't complain 750 // about them. 751 // FIXME: Should we support Microsoft's extensions in this area? 752 if (Record->getDeclName() && getLangOptions().Microsoft) 753 return Tag; 754 } 755 756 if (!DS.isMissingDeclaratorOk()) { 757 // Warn about typedefs of enums without names, since this is an 758 // extension in both Microsoft an GNU. 759 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 760 Tag && isa<EnumDecl>(Tag)) { 761 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name) 762 << DS.getSourceRange(); 763 return Tag; 764 } 765 766 // FIXME: This diagnostic is emitted even when various previous 767 // errors occurred (see e.g. test/Sema/decl-invalid.c). However, 768 // DeclSpec has no means of communicating this information, and the 769 // responsible parser functions are quite far apart. 770 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators) 771 << DS.getSourceRange(); 772 return 0; 773 } 774 775 return Tag; 776} 777 778/// InjectAnonymousStructOrUnionMembers - Inject the members of the 779/// anonymous struct or union AnonRecord into the owning context Owner 780/// and scope S. This routine will be invoked just after we realize 781/// that an unnamed union or struct is actually an anonymous union or 782/// struct, e.g., 783/// 784/// @code 785/// union { 786/// int i; 787/// float f; 788/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 789/// // f into the surrounding scope.x 790/// @endcode 791/// 792/// This routine is recursive, injecting the names of nested anonymous 793/// structs/unions into the owning context and scope as well. 794bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner, 795 RecordDecl *AnonRecord) { 796 bool Invalid = false; 797 for (RecordDecl::field_iterator F = AnonRecord->field_begin(), 798 FEnd = AnonRecord->field_end(); 799 F != FEnd; ++F) { 800 if ((*F)->getDeclName()) { 801 Decl *PrevDecl = LookupDeclInContext((*F)->getDeclName(), 802 Decl::IDNS_Ordinary, Owner, false); 803 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 804 // C++ [class.union]p2: 805 // The names of the members of an anonymous union shall be 806 // distinct from the names of any other entity in the 807 // scope in which the anonymous union is declared. 808 unsigned diagKind 809 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl 810 : diag::err_anonymous_struct_member_redecl; 811 Diag((*F)->getLocation(), diagKind) 812 << (*F)->getDeclName(); 813 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 814 Invalid = true; 815 } else { 816 // C++ [class.union]p2: 817 // For the purpose of name lookup, after the anonymous union 818 // definition, the members of the anonymous union are 819 // considered to have been defined in the scope in which the 820 // anonymous union is declared. 821 Owner->makeDeclVisibleInContext(*F); 822 S->AddDecl(*F); 823 IdResolver.AddDecl(*F); 824 } 825 } else if (const RecordType *InnerRecordType 826 = (*F)->getType()->getAsRecordType()) { 827 RecordDecl *InnerRecord = InnerRecordType->getDecl(); 828 if (InnerRecord->isAnonymousStructOrUnion()) 829 Invalid = Invalid || 830 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord); 831 } 832 } 833 834 return Invalid; 835} 836 837/// ActOnAnonymousStructOrUnion - Handle the declaration of an 838/// anonymous structure or union. Anonymous unions are a C++ feature 839/// (C++ [class.union]) and a GNU C extension; anonymous structures 840/// are a GNU C and GNU C++ extension. 841Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 842 RecordDecl *Record) { 843 DeclContext *Owner = Record->getDeclContext(); 844 845 // Diagnose whether this anonymous struct/union is an extension. 846 if (Record->isUnion() && !getLangOptions().CPlusPlus) 847 Diag(Record->getLocation(), diag::ext_anonymous_union); 848 else if (!Record->isUnion()) 849 Diag(Record->getLocation(), diag::ext_anonymous_struct); 850 851 // C and C++ require different kinds of checks for anonymous 852 // structs/unions. 853 bool Invalid = false; 854 if (getLangOptions().CPlusPlus) { 855 const char* PrevSpec = 0; 856 // C++ [class.union]p3: 857 // Anonymous unions declared in a named namespace or in the 858 // global namespace shall be declared static. 859 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 860 (isa<TranslationUnitDecl>(Owner) || 861 (isa<NamespaceDecl>(Owner) && 862 cast<NamespaceDecl>(Owner)->getDeclName()))) { 863 Diag(Record->getLocation(), diag::err_anonymous_union_not_static); 864 Invalid = true; 865 866 // Recover by adding 'static'. 867 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec); 868 } 869 // C++ [class.union]p3: 870 // A storage class is not allowed in a declaration of an 871 // anonymous union in a class scope. 872 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 873 isa<RecordDecl>(Owner)) { 874 Diag(DS.getStorageClassSpecLoc(), 875 diag::err_anonymous_union_with_storage_spec); 876 Invalid = true; 877 878 // Recover by removing the storage specifier. 879 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(), 880 PrevSpec); 881 } 882 883 // C++ [class.union]p2: 884 // The member-specification of an anonymous union shall only 885 // define non-static data members. [Note: nested types and 886 // functions cannot be declared within an anonymous union. ] 887 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 888 MemEnd = Record->decls_end(); 889 Mem != MemEnd; ++Mem) { 890 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 891 // C++ [class.union]p3: 892 // An anonymous union shall not have private or protected 893 // members (clause 11). 894 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) { 895 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 896 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 897 Invalid = true; 898 } 899 } else if ((*Mem)->isImplicit()) { 900 // Any implicit members are fine. 901 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 902 if (!MemRecord->isAnonymousStructOrUnion() && 903 MemRecord->getDeclName()) { 904 // This is a nested type declaration. 905 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 906 << (int)Record->isUnion(); 907 Invalid = true; 908 } 909 } else { 910 // We have something that isn't a non-static data 911 // member. Complain about it. 912 unsigned DK = diag::err_anonymous_record_bad_member; 913 if (isa<TypeDecl>(*Mem)) 914 DK = diag::err_anonymous_record_with_type; 915 else if (isa<FunctionDecl>(*Mem)) 916 DK = diag::err_anonymous_record_with_function; 917 else if (isa<VarDecl>(*Mem)) 918 DK = diag::err_anonymous_record_with_static; 919 Diag((*Mem)->getLocation(), DK) 920 << (int)Record->isUnion(); 921 Invalid = true; 922 } 923 } 924 } else { 925 // FIXME: Check GNU C semantics 926 if (Record->isUnion() && !Owner->isRecord()) { 927 Diag(Record->getLocation(), diag::err_anonymous_union_not_member) 928 << (int)getLangOptions().CPlusPlus; 929 Invalid = true; 930 } 931 } 932 933 if (!Record->isUnion() && !Owner->isRecord()) { 934 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 935 << (int)getLangOptions().CPlusPlus; 936 Invalid = true; 937 } 938 939 // Create a declaration for this anonymous struct/union. 940 NamedDecl *Anon = 0; 941 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 942 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(), 943 /*IdentifierInfo=*/0, 944 Context.getTypeDeclType(Record), 945 /*BitWidth=*/0, /*Mutable=*/false); 946 Anon->setAccess(AS_public); 947 if (getLangOptions().CPlusPlus) 948 FieldCollector->Add(cast<FieldDecl>(Anon)); 949 } else { 950 VarDecl::StorageClass SC; 951 switch (DS.getStorageClassSpec()) { 952 default: assert(0 && "Unknown storage class!"); 953 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 954 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 955 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 956 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 957 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 958 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 959 case DeclSpec::SCS_mutable: 960 // mutable can only appear on non-static class members, so it's always 961 // an error here 962 Diag(Record->getLocation(), diag::err_mutable_nonmember); 963 Invalid = true; 964 SC = VarDecl::None; 965 break; 966 } 967 968 Anon = VarDecl::Create(Context, Owner, Record->getLocation(), 969 /*IdentifierInfo=*/0, 970 Context.getTypeDeclType(Record), 971 SC, DS.getSourceRange().getBegin()); 972 } 973 Anon->setImplicit(); 974 975 // Add the anonymous struct/union object to the current 976 // context. We'll be referencing this object when we refer to one of 977 // its members. 978 Owner->addDecl(Anon); 979 980 // Inject the members of the anonymous struct/union into the owning 981 // context and into the identifier resolver chain for name lookup 982 // purposes. 983 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record)) 984 Invalid = true; 985 986 // Mark this as an anonymous struct/union type. Note that we do not 987 // do this until after we have already checked and injected the 988 // members of this anonymous struct/union type, because otherwise 989 // the members could be injected twice: once by DeclContext when it 990 // builds its lookup table, and once by 991 // InjectAnonymousStructOrUnionMembers. 992 Record->setAnonymousStructOrUnion(true); 993 994 if (Invalid) 995 Anon->setInvalidDecl(); 996 997 return Anon; 998} 999 1000bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType, 1001 bool DirectInit) { 1002 // Get the type before calling CheckSingleAssignmentConstraints(), since 1003 // it can promote the expression. 1004 QualType InitType = Init->getType(); 1005 1006 if (getLangOptions().CPlusPlus) { 1007 // FIXME: I dislike this error message. A lot. 1008 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit)) 1009 return Diag(Init->getSourceRange().getBegin(), 1010 diag::err_typecheck_convert_incompatible) 1011 << DeclType << Init->getType() << "initializing" 1012 << Init->getSourceRange(); 1013 1014 return false; 1015 } 1016 1017 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init); 1018 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType, 1019 InitType, Init, "initializing"); 1020} 1021 1022bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) { 1023 const ArrayType *AT = Context.getAsArrayType(DeclT); 1024 1025 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 1026 // C99 6.7.8p14. We have an array of character type with unknown size 1027 // being initialized to a string literal. 1028 llvm::APSInt ConstVal(32); 1029 ConstVal = strLiteral->getByteLength() + 1; 1030 // Return a new array type (C99 6.7.8p22). 1031 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal, 1032 ArrayType::Normal, 0); 1033 } else { 1034 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); 1035 // C99 6.7.8p14. We have an array of character type with known size. 1036 // FIXME: Avoid truncation for 64-bit length strings. 1037 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue()) 1038 Diag(strLiteral->getSourceRange().getBegin(), 1039 diag::warn_initializer_string_for_char_array_too_long) 1040 << strLiteral->getSourceRange(); 1041 } 1042 // Set type from "char *" to "constant array of char". 1043 strLiteral->setType(DeclT); 1044 // For now, we always return false (meaning success). 1045 return false; 1046} 1047 1048StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) { 1049 const ArrayType *AT = Context.getAsArrayType(DeclType); 1050 if (AT && AT->getElementType()->isCharType()) { 1051 return dyn_cast<StringLiteral>(Init->IgnoreParens()); 1052 } 1053 return 0; 1054} 1055 1056bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType, 1057 SourceLocation InitLoc, 1058 DeclarationName InitEntity, 1059 bool DirectInit) { 1060 if (DeclType->isDependentType() || Init->isTypeDependent()) 1061 return false; 1062 1063 // C++ [dcl.init.ref]p1: 1064 // A variable declared to be a T&, that is "reference to type T" 1065 // (8.3.2), shall be initialized by an object, or function, of 1066 // type T or by an object that can be converted into a T. 1067 if (DeclType->isReferenceType()) 1068 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit); 1069 1070 // C99 6.7.8p3: The type of the entity to be initialized shall be an array 1071 // of unknown size ("[]") or an object type that is not a variable array type. 1072 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType)) 1073 return Diag(InitLoc, diag::err_variable_object_no_init) 1074 << VAT->getSizeExpr()->getSourceRange(); 1075 1076 InitListExpr *InitList = dyn_cast<InitListExpr>(Init); 1077 if (!InitList) { 1078 // FIXME: Handle wide strings 1079 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType)) 1080 return CheckStringLiteralInit(strLiteral, DeclType); 1081 1082 // C++ [dcl.init]p14: 1083 // -- If the destination type is a (possibly cv-qualified) class 1084 // type: 1085 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) { 1086 QualType DeclTypeC = Context.getCanonicalType(DeclType); 1087 QualType InitTypeC = Context.getCanonicalType(Init->getType()); 1088 1089 // -- If the initialization is direct-initialization, or if it is 1090 // copy-initialization where the cv-unqualified version of the 1091 // source type is the same class as, or a derived class of, the 1092 // class of the destination, constructors are considered. 1093 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) || 1094 IsDerivedFrom(InitTypeC, DeclTypeC)) { 1095 CXXConstructorDecl *Constructor 1096 = PerformInitializationByConstructor(DeclType, &Init, 1, 1097 InitLoc, Init->getSourceRange(), 1098 InitEntity, 1099 DirectInit? IK_Direct : IK_Copy); 1100 return Constructor == 0; 1101 } 1102 1103 // -- Otherwise (i.e., for the remaining copy-initialization 1104 // cases), user-defined conversion sequences that can 1105 // convert from the source type to the destination type or 1106 // (when a conversion function is used) to a derived class 1107 // thereof are enumerated as described in 13.3.1.4, and the 1108 // best one is chosen through overload resolution 1109 // (13.3). If the conversion cannot be done or is 1110 // ambiguous, the initialization is ill-formed. The 1111 // function selected is called with the initializer 1112 // expression as its argument; if the function is a 1113 // constructor, the call initializes a temporary of the 1114 // destination type. 1115 // FIXME: We're pretending to do copy elision here; return to 1116 // this when we have ASTs for such things. 1117 if (!PerformImplicitConversion(Init, DeclType, "initializing")) 1118 return false; 1119 1120 if (InitEntity) 1121 return Diag(InitLoc, diag::err_cannot_initialize_decl) 1122 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid) 1123 << Init->getType() << Init->getSourceRange(); 1124 else 1125 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname) 1126 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid) 1127 << Init->getType() << Init->getSourceRange(); 1128 } 1129 1130 // C99 6.7.8p16. 1131 if (DeclType->isArrayType()) 1132 return Diag(Init->getLocStart(), diag::err_array_init_list_required) 1133 << Init->getSourceRange(); 1134 1135 return CheckSingleInitializer(Init, DeclType, DirectInit); 1136 } else if (getLangOptions().CPlusPlus) { 1137 // C++ [dcl.init]p14: 1138 // [...] If the class is an aggregate (8.5.1), and the initializer 1139 // is a brace-enclosed list, see 8.5.1. 1140 // 1141 // Note: 8.5.1 is handled below; here, we diagnose the case where 1142 // we have an initializer list and a destination type that is not 1143 // an aggregate. 1144 // FIXME: In C++0x, this is yet another form of initialization. 1145 if (const RecordType *ClassRec = DeclType->getAsRecordType()) { 1146 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl()); 1147 if (!ClassDecl->isAggregate()) 1148 return Diag(InitLoc, diag::err_init_non_aggr_init_list) 1149 << DeclType << Init->getSourceRange(); 1150 } 1151 } 1152 1153 bool hadError = CheckInitList(InitList, DeclType); 1154 Init = InitList; 1155 return hadError; 1156} 1157 1158/// GetNameForDeclarator - Determine the full declaration name for the 1159/// given Declarator. 1160DeclarationName Sema::GetNameForDeclarator(Declarator &D) { 1161 switch (D.getKind()) { 1162 case Declarator::DK_Abstract: 1163 assert(D.getIdentifier() == 0 && "abstract declarators have no name"); 1164 return DeclarationName(); 1165 1166 case Declarator::DK_Normal: 1167 assert (D.getIdentifier() != 0 && "normal declarators have an identifier"); 1168 return DeclarationName(D.getIdentifier()); 1169 1170 case Declarator::DK_Constructor: { 1171 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType()); 1172 Ty = Context.getCanonicalType(Ty); 1173 return Context.DeclarationNames.getCXXConstructorName(Ty); 1174 } 1175 1176 case Declarator::DK_Destructor: { 1177 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType()); 1178 Ty = Context.getCanonicalType(Ty); 1179 return Context.DeclarationNames.getCXXDestructorName(Ty); 1180 } 1181 1182 case Declarator::DK_Conversion: { 1183 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType()); 1184 Ty = Context.getCanonicalType(Ty); 1185 return Context.DeclarationNames.getCXXConversionFunctionName(Ty); 1186 } 1187 1188 case Declarator::DK_Operator: 1189 assert(D.getIdentifier() == 0 && "operator names have no identifier"); 1190 return Context.DeclarationNames.getCXXOperatorName( 1191 D.getOverloadedOperator()); 1192 } 1193 1194 assert(false && "Unknown name kind"); 1195 return DeclarationName(); 1196} 1197 1198/// isNearlyMatchingMemberFunction - Determine whether the C++ member 1199/// functions Declaration and Definition are "nearly" matching. This 1200/// heuristic is used to improve diagnostics in the case where an 1201/// out-of-line member function definition doesn't match any 1202/// declaration within the class. 1203static bool isNearlyMatchingMemberFunction(ASTContext &Context, 1204 FunctionDecl *Declaration, 1205 FunctionDecl *Definition) { 1206 if (Declaration->param_size() != Definition->param_size()) 1207 return false; 1208 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 1209 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 1210 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 1211 1212 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType()); 1213 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType()); 1214 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType()) 1215 return false; 1216 } 1217 1218 return true; 1219} 1220 1221Sema::DeclTy * 1222Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl, 1223 bool IsFunctionDefinition) { 1224 NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl); 1225 DeclarationName Name = GetNameForDeclarator(D); 1226 1227 // All of these full declarators require an identifier. If it doesn't have 1228 // one, the ParsedFreeStandingDeclSpec action should be used. 1229 if (!Name) { 1230 if (!D.getInvalidType()) // Reject this if we think it is valid. 1231 Diag(D.getDeclSpec().getSourceRange().getBegin(), 1232 diag::err_declarator_need_ident) 1233 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 1234 return 0; 1235 } 1236 1237 // The scope passed in may not be a decl scope. Zip up the scope tree until 1238 // we find one that is. 1239 while ((S->getFlags() & Scope::DeclScope) == 0 || 1240 (S->getFlags() & Scope::TemplateParamScope) != 0) 1241 S = S->getParent(); 1242 1243 DeclContext *DC; 1244 Decl *PrevDecl; 1245 NamedDecl *New; 1246 bool InvalidDecl = false; 1247 1248 // See if this is a redefinition of a variable in the same scope. 1249 if (!D.getCXXScopeSpec().isSet()) { 1250 DC = CurContext; 1251 PrevDecl = LookupDeclInScope(Name, Decl::IDNS_Ordinary, S); 1252 } else { // Something like "int foo::x;" 1253 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep()); 1254 PrevDecl = DC ? LookupDeclInContext(Name, Decl::IDNS_Ordinary, DC) 1255 : LookupDeclInScope(Name, Decl::IDNS_Ordinary, S); 1256 1257 // C++ 7.3.1.2p2: 1258 // Members (including explicit specializations of templates) of a named 1259 // namespace can also be defined outside that namespace by explicit 1260 // qualification of the name being defined, provided that the entity being 1261 // defined was already declared in the namespace and the definition appears 1262 // after the point of declaration in a namespace that encloses the 1263 // declarations namespace. 1264 // 1265 // Note that we only check the context at this point. We don't yet 1266 // have enough information to make sure that PrevDecl is actually 1267 // the declaration we want to match. For example, given: 1268 // 1269 // class X { 1270 // void f(); 1271 // void f(float); 1272 // }; 1273 // 1274 // void X::f(int) { } // ill-formed 1275 // 1276 // In this case, PrevDecl will point to the overload set 1277 // containing the two f's declared in X, but neither of them 1278 // matches. 1279 if (!CurContext->Encloses(DC)) { 1280 // The qualifying scope doesn't enclose the original declaration. 1281 // Emit diagnostic based on current scope. 1282 SourceLocation L = D.getIdentifierLoc(); 1283 SourceRange R = D.getCXXScopeSpec().getRange(); 1284 if (isa<FunctionDecl>(CurContext)) { 1285 Diag(L, diag::err_invalid_declarator_in_function) << Name << R; 1286 } else { 1287 Diag(L, diag::err_invalid_declarator_scope) 1288 << Name << cast<NamedDecl>(DC)->getDeclName() << R; 1289 } 1290 InvalidDecl = true; 1291 } 1292 } 1293 1294 if (PrevDecl && PrevDecl->isTemplateParameter()) { 1295 // Maybe we will complain about the shadowed template parameter. 1296 InvalidDecl = InvalidDecl 1297 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 1298 // Just pretend that we didn't see the previous declaration. 1299 PrevDecl = 0; 1300 } 1301 1302 // In C++, the previous declaration we find might be a tag type 1303 // (class or enum). In this case, the new declaration will hide the 1304 // tag type. Note that this does does not apply if we're declaring a 1305 // typedef (C++ [dcl.typedef]p4). 1306 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag && 1307 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 1308 PrevDecl = 0; 1309 1310 QualType R = GetTypeForDeclarator(D, S); 1311 assert(!R.isNull() && "GetTypeForDeclarator() returned null type"); 1312 1313 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 1314 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl, 1315 InvalidDecl); 1316 } else if (R.getTypePtr()->isFunctionType()) { 1317 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl, 1318 IsFunctionDefinition, InvalidDecl); 1319 } else { 1320 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl, 1321 InvalidDecl); 1322 } 1323 1324 if (New == 0) 1325 return 0; 1326 1327 // Set the lexical context. If the declarator has a C++ scope specifier, the 1328 // lexical context will be different from the semantic context. 1329 New->setLexicalDeclContext(CurContext); 1330 1331 // If this has an identifier, add it to the scope stack. 1332 if (Name) 1333 PushOnScopeChains(New, S); 1334 // If any semantic error occurred, mark the decl as invalid. 1335 if (D.getInvalidType() || InvalidDecl) 1336 New->setInvalidDecl(); 1337 1338 return New; 1339} 1340 1341NamedDecl* 1342Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1343 QualType R, Decl* LastDeclarator, 1344 Decl* PrevDecl, bool& InvalidDecl) { 1345 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 1346 if (D.getCXXScopeSpec().isSet()) { 1347 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 1348 << D.getCXXScopeSpec().getRange(); 1349 InvalidDecl = true; 1350 // Pretend we didn't see the scope specifier. 1351 DC = 0; 1352 } 1353 1354 // Check that there are no default arguments (C++ only). 1355 if (getLangOptions().CPlusPlus) 1356 CheckExtraCXXDefaultArguments(D); 1357 1358 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator); 1359 if (!NewTD) return 0; 1360 1361 // Handle attributes prior to checking for duplicates in MergeVarDecl 1362 ProcessDeclAttributes(NewTD, D); 1363 // Merge the decl with the existing one if appropriate. If the decl is 1364 // in an outer scope, it isn't the same thing. 1365 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) { 1366 NewTD = MergeTypeDefDecl(NewTD, PrevDecl); 1367 if (NewTD == 0) return 0; 1368 } 1369 1370 if (S->getFnParent() == 0) { 1371 // C99 6.7.7p2: If a typedef name specifies a variably modified type 1372 // then it shall have block scope. 1373 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) { 1374 if (NewTD->getUnderlyingType()->isVariableArrayType()) 1375 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope); 1376 else 1377 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope); 1378 1379 InvalidDecl = true; 1380 } 1381 } 1382 return NewTD; 1383} 1384 1385NamedDecl* 1386Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1387 QualType R, Decl* LastDeclarator, 1388 Decl* PrevDecl, bool& InvalidDecl) { 1389 DeclarationName Name = GetNameForDeclarator(D); 1390 1391 // Check that there are no default arguments (C++ only). 1392 if (getLangOptions().CPlusPlus) 1393 CheckExtraCXXDefaultArguments(D); 1394 1395 if (R.getTypePtr()->isObjCInterfaceType()) { 1396 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object) 1397 << D.getIdentifier(); 1398 InvalidDecl = true; 1399 } 1400 1401 VarDecl *NewVD; 1402 VarDecl::StorageClass SC; 1403 switch (D.getDeclSpec().getStorageClassSpec()) { 1404 default: assert(0 && "Unknown storage class!"); 1405 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 1406 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 1407 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 1408 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 1409 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 1410 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 1411 case DeclSpec::SCS_mutable: 1412 // mutable can only appear on non-static class members, so it's always 1413 // an error here 1414 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 1415 InvalidDecl = true; 1416 SC = VarDecl::None; 1417 break; 1418 } 1419 1420 IdentifierInfo *II = Name.getAsIdentifierInfo(); 1421 if (!II) { 1422 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 1423 << Name.getAsString(); 1424 return 0; 1425 } 1426 1427 if (DC->isRecord()) { 1428 // This is a static data member for a C++ class. 1429 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC), 1430 D.getIdentifierLoc(), II, 1431 R); 1432 } else { 1433 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified(); 1434 if (S->getFnParent() == 0) { 1435 // C99 6.9p2: The storage-class specifiers auto and register shall not 1436 // appear in the declaration specifiers in an external declaration. 1437 if (SC == VarDecl::Auto || SC == VarDecl::Register) { 1438 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 1439 InvalidDecl = true; 1440 } 1441 } 1442 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(), 1443 II, R, SC, 1444 // FIXME: Move to DeclGroup... 1445 D.getDeclSpec().getSourceRange().getBegin()); 1446 NewVD->setThreadSpecified(ThreadSpecified); 1447 } 1448 NewVD->setNextDeclarator(LastDeclarator); 1449 1450 // Handle attributes prior to checking for duplicates in MergeVarDecl 1451 ProcessDeclAttributes(NewVD, D); 1452 1453 // Handle GNU asm-label extension (encoded as an attribute). 1454 if (Expr *E = (Expr*) D.getAsmLabel()) { 1455 // The parser guarantees this is a string. 1456 StringLiteral *SE = cast<StringLiteral>(E); 1457 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(), 1458 SE->getByteLength()))); 1459 } 1460 1461 // Emit an error if an address space was applied to decl with local storage. 1462 // This includes arrays of objects with address space qualifiers, but not 1463 // automatic variables that point to other address spaces. 1464 // ISO/IEC TR 18037 S5.1.2 1465 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) { 1466 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl); 1467 InvalidDecl = true; 1468 } 1469 // Merge the decl with the existing one if appropriate. If the decl is 1470 // in an outer scope, it isn't the same thing. 1471 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) { 1472 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) { 1473 // The user tried to define a non-static data member 1474 // out-of-line (C++ [dcl.meaning]p1). 1475 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 1476 << D.getCXXScopeSpec().getRange(); 1477 NewVD->Destroy(Context); 1478 return 0; 1479 } 1480 1481 NewVD = MergeVarDecl(NewVD, PrevDecl); 1482 if (NewVD == 0) return 0; 1483 1484 if (D.getCXXScopeSpec().isSet()) { 1485 // No previous declaration in the qualifying scope. 1486 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member) 1487 << Name << D.getCXXScopeSpec().getRange(); 1488 InvalidDecl = true; 1489 } 1490 } 1491 return NewVD; 1492} 1493 1494NamedDecl* 1495Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1496 QualType R, Decl *LastDeclarator, 1497 Decl* PrevDecl, bool IsFunctionDefinition, 1498 bool& InvalidDecl) { 1499 assert(R.getTypePtr()->isFunctionType()); 1500 1501 DeclarationName Name = GetNameForDeclarator(D); 1502 FunctionDecl::StorageClass SC = FunctionDecl::None; 1503 switch (D.getDeclSpec().getStorageClassSpec()) { 1504 default: assert(0 && "Unknown storage class!"); 1505 case DeclSpec::SCS_auto: 1506 case DeclSpec::SCS_register: 1507 case DeclSpec::SCS_mutable: 1508 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func); 1509 InvalidDecl = true; 1510 break; 1511 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break; 1512 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break; 1513 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break; 1514 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break; 1515 } 1516 1517 bool isInline = D.getDeclSpec().isInlineSpecified(); 1518 // bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 1519 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 1520 1521 FunctionDecl *NewFD; 1522 if (D.getKind() == Declarator::DK_Constructor) { 1523 // This is a C++ constructor declaration. 1524 assert(DC->isRecord() && 1525 "Constructors can only be declared in a member context"); 1526 1527 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC); 1528 1529 // Create the new declaration 1530 NewFD = CXXConstructorDecl::Create(Context, 1531 cast<CXXRecordDecl>(DC), 1532 D.getIdentifierLoc(), Name, R, 1533 isExplicit, isInline, 1534 /*isImplicitlyDeclared=*/false); 1535 1536 if (InvalidDecl) 1537 NewFD->setInvalidDecl(); 1538 } else if (D.getKind() == Declarator::DK_Destructor) { 1539 // This is a C++ destructor declaration. 1540 if (DC->isRecord()) { 1541 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC); 1542 1543 NewFD = CXXDestructorDecl::Create(Context, 1544 cast<CXXRecordDecl>(DC), 1545 D.getIdentifierLoc(), Name, R, 1546 isInline, 1547 /*isImplicitlyDeclared=*/false); 1548 1549 if (InvalidDecl) 1550 NewFD->setInvalidDecl(); 1551 } else { 1552 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 1553 1554 // Create a FunctionDecl to satisfy the function definition parsing 1555 // code path. 1556 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(), 1557 Name, R, SC, isInline, 1558 // FIXME: Move to DeclGroup... 1559 D.getDeclSpec().getSourceRange().getBegin()); 1560 InvalidDecl = true; 1561 NewFD->setInvalidDecl(); 1562 } 1563 } else if (D.getKind() == Declarator::DK_Conversion) { 1564 if (!DC->isRecord()) { 1565 Diag(D.getIdentifierLoc(), 1566 diag::err_conv_function_not_member); 1567 return 0; 1568 } else { 1569 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC); 1570 1571 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC), 1572 D.getIdentifierLoc(), Name, R, 1573 isInline, isExplicit); 1574 1575 if (InvalidDecl) 1576 NewFD->setInvalidDecl(); 1577 } 1578 } else if (DC->isRecord()) { 1579 // This is a C++ method declaration. 1580 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC), 1581 D.getIdentifierLoc(), Name, R, 1582 (SC == FunctionDecl::Static), isInline); 1583 } else { 1584 NewFD = FunctionDecl::Create(Context, DC, 1585 D.getIdentifierLoc(), 1586 Name, R, SC, isInline, 1587 // FIXME: Move to DeclGroup... 1588 D.getDeclSpec().getSourceRange().getBegin()); 1589 } 1590 NewFD->setNextDeclarator(LastDeclarator); 1591 1592 // Set the lexical context. If the declarator has a C++ 1593 // scope specifier, the lexical context will be different 1594 // from the semantic context. 1595 NewFD->setLexicalDeclContext(CurContext); 1596 1597 // Handle GNU asm-label extension (encoded as an attribute). 1598 if (Expr *E = (Expr*) D.getAsmLabel()) { 1599 // The parser guarantees this is a string. 1600 StringLiteral *SE = cast<StringLiteral>(E); 1601 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(), 1602 SE->getByteLength()))); 1603 } 1604 1605 // Copy the parameter declarations from the declarator D to 1606 // the function declaration NewFD, if they are available. 1607 if (D.getNumTypeObjects() > 0) { 1608 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1609 1610 // Create Decl objects for each parameter, adding them to the 1611 // FunctionDecl. 1612 llvm::SmallVector<ParmVarDecl*, 16> Params; 1613 1614 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 1615 // function that takes no arguments, not a function that takes a 1616 // single void argument. 1617 // We let through "const void" here because Sema::GetTypeForDeclarator 1618 // already checks for that case. 1619 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 1620 FTI.ArgInfo[0].Param && 1621 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 1622 // empty arg list, don't push any params. 1623 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param; 1624 1625 // In C++, the empty parameter-type-list must be spelled "void"; a 1626 // typedef of void is not permitted. 1627 if (getLangOptions().CPlusPlus && 1628 Param->getType().getUnqualifiedType() != Context.VoidTy) { 1629 Diag(Param->getLocation(), diag::ext_param_typedef_of_void); 1630 } 1631 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 1632 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 1633 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param); 1634 } 1635 1636 NewFD->setParams(Context, &Params[0], Params.size()); 1637 } else if (R->getAsTypedefType()) { 1638 // When we're declaring a function with a typedef, as in the 1639 // following example, we'll need to synthesize (unnamed) 1640 // parameters for use in the declaration. 1641 // 1642 // @code 1643 // typedef void fn(int); 1644 // fn f; 1645 // @endcode 1646 const FunctionTypeProto *FT = R->getAsFunctionTypeProto(); 1647 if (!FT) { 1648 // This is a typedef of a function with no prototype, so we 1649 // don't need to do anything. 1650 } else if ((FT->getNumArgs() == 0) || 1651 (FT->getNumArgs() == 1 && !FT->isVariadic() && 1652 FT->getArgType(0)->isVoidType())) { 1653 // This is a zero-argument function. We don't need to do anything. 1654 } else { 1655 // Synthesize a parameter for each argument type. 1656 llvm::SmallVector<ParmVarDecl*, 16> Params; 1657 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin(); 1658 ArgType != FT->arg_type_end(); ++ArgType) { 1659 Params.push_back(ParmVarDecl::Create(Context, DC, 1660 SourceLocation(), 0, 1661 *ArgType, VarDecl::None, 1662 0)); 1663 } 1664 1665 NewFD->setParams(Context, &Params[0], Params.size()); 1666 } 1667 } 1668 1669 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) 1670 InvalidDecl = InvalidDecl || CheckConstructor(Constructor); 1671 else if (isa<CXXDestructorDecl>(NewFD)) { 1672 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent()); 1673 Record->setUserDeclaredDestructor(true); 1674 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no 1675 // user-defined destructor. 1676 Record->setPOD(false); 1677 } else if (CXXConversionDecl *Conversion = 1678 dyn_cast<CXXConversionDecl>(NewFD)) 1679 ActOnConversionDeclarator(Conversion); 1680 1681 // Extra checking for C++ overloaded operators (C++ [over.oper]). 1682 if (NewFD->isOverloadedOperator() && 1683 CheckOverloadedOperatorDeclaration(NewFD)) 1684 NewFD->setInvalidDecl(); 1685 1686 // Merge the decl with the existing one if appropriate. Since C functions 1687 // are in a flat namespace, make sure we consider decls in outer scopes. 1688 if (PrevDecl && 1689 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) { 1690 bool Redeclaration = false; 1691 1692 // If C++, determine whether NewFD is an overload of PrevDecl or 1693 // a declaration that requires merging. If it's an overload, 1694 // there's no more work to do here; we'll just add the new 1695 // function to the scope. 1696 OverloadedFunctionDecl::function_iterator MatchedDecl; 1697 if (!getLangOptions().CPlusPlus || 1698 !IsOverload(NewFD, PrevDecl, MatchedDecl)) { 1699 Decl *OldDecl = PrevDecl; 1700 1701 // If PrevDecl was an overloaded function, extract the 1702 // FunctionDecl that matched. 1703 if (isa<OverloadedFunctionDecl>(PrevDecl)) 1704 OldDecl = *MatchedDecl; 1705 1706 // NewFD and PrevDecl represent declarations that need to be 1707 // merged. 1708 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration); 1709 1710 if (NewFD == 0) return 0; 1711 if (Redeclaration) { 1712 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 1713 1714 // An out-of-line member function declaration must also be a 1715 // definition (C++ [dcl.meaning]p1). 1716 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && 1717 !InvalidDecl) { 1718 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration) 1719 << D.getCXXScopeSpec().getRange(); 1720 NewFD->setInvalidDecl(); 1721 } 1722 } 1723 } 1724 1725 if (!Redeclaration && D.getCXXScopeSpec().isSet()) { 1726 // The user tried to provide an out-of-line definition for a 1727 // member function, but there was no such member function 1728 // declared (C++ [class.mfct]p2). For example: 1729 // 1730 // class X { 1731 // void f() const; 1732 // }; 1733 // 1734 // void X::f() { } // ill-formed 1735 // 1736 // Complain about this problem, and attempt to suggest close 1737 // matches (e.g., those that differ only in cv-qualifiers and 1738 // whether the parameter types are references). 1739 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match) 1740 << cast<CXXRecordDecl>(DC)->getDeclName() 1741 << D.getCXXScopeSpec().getRange(); 1742 InvalidDecl = true; 1743 1744 PrevDecl = LookupDeclInContext(Name, Decl::IDNS_Ordinary, DC); 1745 if (!PrevDecl) { 1746 // Nothing to suggest. 1747 } else if (OverloadedFunctionDecl *Ovl 1748 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) { 1749 for (OverloadedFunctionDecl::function_iterator 1750 Func = Ovl->function_begin(), 1751 FuncEnd = Ovl->function_end(); 1752 Func != FuncEnd; ++Func) { 1753 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD)) 1754 Diag((*Func)->getLocation(), diag::note_member_def_close_match); 1755 1756 } 1757 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) { 1758 // Suggest this no matter how mismatched it is; it's the only 1759 // thing we have. 1760 unsigned diag; 1761 if (isNearlyMatchingMemberFunction(Context, Method, NewFD)) 1762 diag = diag::note_member_def_close_match; 1763 else if (Method->getBody()) 1764 diag = diag::note_previous_definition; 1765 else 1766 diag = diag::note_previous_declaration; 1767 Diag(Method->getLocation(), diag); 1768 } 1769 1770 PrevDecl = 0; 1771 } 1772 } 1773 // Handle attributes. We need to have merged decls when handling attributes 1774 // (for example to check for conflicts, etc). 1775 ProcessDeclAttributes(NewFD, D); 1776 1777 if (getLangOptions().CPlusPlus) { 1778 // In C++, check default arguments now that we have merged decls. 1779 CheckCXXDefaultArguments(NewFD); 1780 1781 // An out-of-line member function declaration must also be a 1782 // definition (C++ [dcl.meaning]p1). 1783 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) { 1784 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration) 1785 << D.getCXXScopeSpec().getRange(); 1786 InvalidDecl = true; 1787 } 1788 } 1789 return NewFD; 1790} 1791 1792void Sema::InitializerElementNotConstant(const Expr *Init) { 1793 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 1794 << Init->getSourceRange(); 1795} 1796 1797bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) { 1798 switch (Init->getStmtClass()) { 1799 default: 1800 InitializerElementNotConstant(Init); 1801 return true; 1802 case Expr::ParenExprClass: { 1803 const ParenExpr* PE = cast<ParenExpr>(Init); 1804 return CheckAddressConstantExpressionLValue(PE->getSubExpr()); 1805 } 1806 case Expr::CompoundLiteralExprClass: 1807 return cast<CompoundLiteralExpr>(Init)->isFileScope(); 1808 case Expr::DeclRefExprClass: 1809 case Expr::QualifiedDeclRefExprClass: { 1810 const Decl *D = cast<DeclRefExpr>(Init)->getDecl(); 1811 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1812 if (VD->hasGlobalStorage()) 1813 return false; 1814 InitializerElementNotConstant(Init); 1815 return true; 1816 } 1817 if (isa<FunctionDecl>(D)) 1818 return false; 1819 InitializerElementNotConstant(Init); 1820 return true; 1821 } 1822 case Expr::MemberExprClass: { 1823 const MemberExpr *M = cast<MemberExpr>(Init); 1824 if (M->isArrow()) 1825 return CheckAddressConstantExpression(M->getBase()); 1826 return CheckAddressConstantExpressionLValue(M->getBase()); 1827 } 1828 case Expr::ArraySubscriptExprClass: { 1829 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)? 1830 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init); 1831 return CheckAddressConstantExpression(ASE->getBase()) || 1832 CheckArithmeticConstantExpression(ASE->getIdx()); 1833 } 1834 case Expr::StringLiteralClass: 1835 case Expr::PredefinedExprClass: 1836 return false; 1837 case Expr::UnaryOperatorClass: { 1838 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1839 1840 // C99 6.6p9 1841 if (Exp->getOpcode() == UnaryOperator::Deref) 1842 return CheckAddressConstantExpression(Exp->getSubExpr()); 1843 1844 InitializerElementNotConstant(Init); 1845 return true; 1846 } 1847 } 1848} 1849 1850bool Sema::CheckAddressConstantExpression(const Expr* Init) { 1851 switch (Init->getStmtClass()) { 1852 default: 1853 InitializerElementNotConstant(Init); 1854 return true; 1855 case Expr::ParenExprClass: 1856 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr()); 1857 case Expr::StringLiteralClass: 1858 case Expr::ObjCStringLiteralClass: 1859 return false; 1860 case Expr::CallExprClass: 1861 case Expr::CXXOperatorCallExprClass: 1862 // __builtin___CFStringMakeConstantString is a valid constant l-value. 1863 if (cast<CallExpr>(Init)->isBuiltinCall() == 1864 Builtin::BI__builtin___CFStringMakeConstantString) 1865 return false; 1866 1867 InitializerElementNotConstant(Init); 1868 return true; 1869 1870 case Expr::UnaryOperatorClass: { 1871 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1872 1873 // C99 6.6p9 1874 if (Exp->getOpcode() == UnaryOperator::AddrOf) 1875 return CheckAddressConstantExpressionLValue(Exp->getSubExpr()); 1876 1877 if (Exp->getOpcode() == UnaryOperator::Extension) 1878 return CheckAddressConstantExpression(Exp->getSubExpr()); 1879 1880 InitializerElementNotConstant(Init); 1881 return true; 1882 } 1883 case Expr::BinaryOperatorClass: { 1884 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"? 1885 const BinaryOperator *Exp = cast<BinaryOperator>(Init); 1886 1887 Expr *PExp = Exp->getLHS(); 1888 Expr *IExp = Exp->getRHS(); 1889 if (IExp->getType()->isPointerType()) 1890 std::swap(PExp, IExp); 1891 1892 // FIXME: Should we pedwarn if IExp isn't an integer constant expression? 1893 return CheckAddressConstantExpression(PExp) || 1894 CheckArithmeticConstantExpression(IExp); 1895 } 1896 case Expr::ImplicitCastExprClass: 1897 case Expr::CStyleCastExprClass: { 1898 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr(); 1899 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) { 1900 // Check for implicit promotion 1901 if (SubExpr->getType()->isFunctionType() || 1902 SubExpr->getType()->isArrayType()) 1903 return CheckAddressConstantExpressionLValue(SubExpr); 1904 } 1905 1906 // Check for pointer->pointer cast 1907 if (SubExpr->getType()->isPointerType()) 1908 return CheckAddressConstantExpression(SubExpr); 1909 1910 if (SubExpr->getType()->isIntegralType()) { 1911 // Check for the special-case of a pointer->int->pointer cast; 1912 // this isn't standard, but some code requires it. See 1913 // PR2720 for an example. 1914 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) { 1915 if (SubCast->getSubExpr()->getType()->isPointerType()) { 1916 unsigned IntWidth = Context.getIntWidth(SubCast->getType()); 1917 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy); 1918 if (IntWidth >= PointerWidth) { 1919 return CheckAddressConstantExpression(SubCast->getSubExpr()); 1920 } 1921 } 1922 } 1923 } 1924 if (SubExpr->getType()->isArithmeticType()) { 1925 return CheckArithmeticConstantExpression(SubExpr); 1926 } 1927 1928 InitializerElementNotConstant(Init); 1929 return true; 1930 } 1931 case Expr::ConditionalOperatorClass: { 1932 // FIXME: Should we pedwarn here? 1933 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init); 1934 if (!Exp->getCond()->getType()->isArithmeticType()) { 1935 InitializerElementNotConstant(Init); 1936 return true; 1937 } 1938 if (CheckArithmeticConstantExpression(Exp->getCond())) 1939 return true; 1940 if (Exp->getLHS() && 1941 CheckAddressConstantExpression(Exp->getLHS())) 1942 return true; 1943 return CheckAddressConstantExpression(Exp->getRHS()); 1944 } 1945 case Expr::AddrLabelExprClass: 1946 return false; 1947 } 1948} 1949 1950static const Expr* FindExpressionBaseAddress(const Expr* E); 1951 1952static const Expr* FindExpressionBaseAddressLValue(const Expr* E) { 1953 switch (E->getStmtClass()) { 1954 default: 1955 return E; 1956 case Expr::ParenExprClass: { 1957 const ParenExpr* PE = cast<ParenExpr>(E); 1958 return FindExpressionBaseAddressLValue(PE->getSubExpr()); 1959 } 1960 case Expr::MemberExprClass: { 1961 const MemberExpr *M = cast<MemberExpr>(E); 1962 if (M->isArrow()) 1963 return FindExpressionBaseAddress(M->getBase()); 1964 return FindExpressionBaseAddressLValue(M->getBase()); 1965 } 1966 case Expr::ArraySubscriptExprClass: { 1967 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E); 1968 return FindExpressionBaseAddress(ASE->getBase()); 1969 } 1970 case Expr::UnaryOperatorClass: { 1971 const UnaryOperator *Exp = cast<UnaryOperator>(E); 1972 1973 if (Exp->getOpcode() == UnaryOperator::Deref) 1974 return FindExpressionBaseAddress(Exp->getSubExpr()); 1975 1976 return E; 1977 } 1978 } 1979} 1980 1981static const Expr* FindExpressionBaseAddress(const Expr* E) { 1982 switch (E->getStmtClass()) { 1983 default: 1984 return E; 1985 case Expr::ParenExprClass: { 1986 const ParenExpr* PE = cast<ParenExpr>(E); 1987 return FindExpressionBaseAddress(PE->getSubExpr()); 1988 } 1989 case Expr::UnaryOperatorClass: { 1990 const UnaryOperator *Exp = cast<UnaryOperator>(E); 1991 1992 // C99 6.6p9 1993 if (Exp->getOpcode() == UnaryOperator::AddrOf) 1994 return FindExpressionBaseAddressLValue(Exp->getSubExpr()); 1995 1996 if (Exp->getOpcode() == UnaryOperator::Extension) 1997 return FindExpressionBaseAddress(Exp->getSubExpr()); 1998 1999 return E; 2000 } 2001 case Expr::BinaryOperatorClass: { 2002 const BinaryOperator *Exp = cast<BinaryOperator>(E); 2003 2004 Expr *PExp = Exp->getLHS(); 2005 Expr *IExp = Exp->getRHS(); 2006 if (IExp->getType()->isPointerType()) 2007 std::swap(PExp, IExp); 2008 2009 return FindExpressionBaseAddress(PExp); 2010 } 2011 case Expr::ImplicitCastExprClass: { 2012 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr(); 2013 2014 // Check for implicit promotion 2015 if (SubExpr->getType()->isFunctionType() || 2016 SubExpr->getType()->isArrayType()) 2017 return FindExpressionBaseAddressLValue(SubExpr); 2018 2019 // Check for pointer->pointer cast 2020 if (SubExpr->getType()->isPointerType()) 2021 return FindExpressionBaseAddress(SubExpr); 2022 2023 // We assume that we have an arithmetic expression here; 2024 // if we don't, we'll figure it out later 2025 return 0; 2026 } 2027 case Expr::CStyleCastExprClass: { 2028 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 2029 2030 // Check for pointer->pointer cast 2031 if (SubExpr->getType()->isPointerType()) 2032 return FindExpressionBaseAddress(SubExpr); 2033 2034 // We assume that we have an arithmetic expression here; 2035 // if we don't, we'll figure it out later 2036 return 0; 2037 } 2038 } 2039} 2040 2041bool Sema::CheckArithmeticConstantExpression(const Expr* Init) { 2042 switch (Init->getStmtClass()) { 2043 default: 2044 InitializerElementNotConstant(Init); 2045 return true; 2046 case Expr::ParenExprClass: { 2047 const ParenExpr* PE = cast<ParenExpr>(Init); 2048 return CheckArithmeticConstantExpression(PE->getSubExpr()); 2049 } 2050 case Expr::FloatingLiteralClass: 2051 case Expr::IntegerLiteralClass: 2052 case Expr::CharacterLiteralClass: 2053 case Expr::ImaginaryLiteralClass: 2054 case Expr::TypesCompatibleExprClass: 2055 case Expr::CXXBoolLiteralExprClass: 2056 return false; 2057 case Expr::CallExprClass: 2058 case Expr::CXXOperatorCallExprClass: { 2059 const CallExpr *CE = cast<CallExpr>(Init); 2060 2061 // Allow any constant foldable calls to builtins. 2062 if (CE->isBuiltinCall() && CE->isEvaluatable(Context)) 2063 return false; 2064 2065 InitializerElementNotConstant(Init); 2066 return true; 2067 } 2068 case Expr::DeclRefExprClass: 2069 case Expr::QualifiedDeclRefExprClass: { 2070 const Decl *D = cast<DeclRefExpr>(Init)->getDecl(); 2071 if (isa<EnumConstantDecl>(D)) 2072 return false; 2073 InitializerElementNotConstant(Init); 2074 return true; 2075 } 2076 case Expr::CompoundLiteralExprClass: 2077 // Allow "(vector type){2,4}"; normal C constraints don't allow this, 2078 // but vectors are allowed to be magic. 2079 if (Init->getType()->isVectorType()) 2080 return false; 2081 InitializerElementNotConstant(Init); 2082 return true; 2083 case Expr::UnaryOperatorClass: { 2084 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 2085 2086 switch (Exp->getOpcode()) { 2087 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 2088 // See C99 6.6p3. 2089 default: 2090 InitializerElementNotConstant(Init); 2091 return true; 2092 case UnaryOperator::OffsetOf: 2093 if (Exp->getSubExpr()->getType()->isConstantSizeType()) 2094 return false; 2095 InitializerElementNotConstant(Init); 2096 return true; 2097 case UnaryOperator::Extension: 2098 case UnaryOperator::LNot: 2099 case UnaryOperator::Plus: 2100 case UnaryOperator::Minus: 2101 case UnaryOperator::Not: 2102 return CheckArithmeticConstantExpression(Exp->getSubExpr()); 2103 } 2104 } 2105 case Expr::SizeOfAlignOfExprClass: { 2106 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init); 2107 // Special check for void types, which are allowed as an extension 2108 if (Exp->getTypeOfArgument()->isVoidType()) 2109 return false; 2110 // alignof always evaluates to a constant. 2111 // FIXME: is sizeof(int[3.0]) a constant expression? 2112 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) { 2113 InitializerElementNotConstant(Init); 2114 return true; 2115 } 2116 return false; 2117 } 2118 case Expr::BinaryOperatorClass: { 2119 const BinaryOperator *Exp = cast<BinaryOperator>(Init); 2120 2121 if (Exp->getLHS()->getType()->isArithmeticType() && 2122 Exp->getRHS()->getType()->isArithmeticType()) { 2123 return CheckArithmeticConstantExpression(Exp->getLHS()) || 2124 CheckArithmeticConstantExpression(Exp->getRHS()); 2125 } 2126 2127 if (Exp->getLHS()->getType()->isPointerType() && 2128 Exp->getRHS()->getType()->isPointerType()) { 2129 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS()); 2130 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS()); 2131 2132 // Only allow a null (constant integer) base; we could 2133 // allow some additional cases if necessary, but this 2134 // is sufficient to cover offsetof-like constructs. 2135 if (!LHSBase && !RHSBase) { 2136 return CheckAddressConstantExpression(Exp->getLHS()) || 2137 CheckAddressConstantExpression(Exp->getRHS()); 2138 } 2139 } 2140 2141 InitializerElementNotConstant(Init); 2142 return true; 2143 } 2144 case Expr::ImplicitCastExprClass: 2145 case Expr::CStyleCastExprClass: { 2146 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr(); 2147 if (SubExpr->getType()->isArithmeticType()) 2148 return CheckArithmeticConstantExpression(SubExpr); 2149 2150 if (SubExpr->getType()->isPointerType()) { 2151 const Expr* Base = FindExpressionBaseAddress(SubExpr); 2152 // If the pointer has a null base, this is an offsetof-like construct 2153 if (!Base) 2154 return CheckAddressConstantExpression(SubExpr); 2155 } 2156 2157 InitializerElementNotConstant(Init); 2158 return true; 2159 } 2160 case Expr::ConditionalOperatorClass: { 2161 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init); 2162 2163 // If GNU extensions are disabled, we require all operands to be arithmetic 2164 // constant expressions. 2165 if (getLangOptions().NoExtensions) { 2166 return CheckArithmeticConstantExpression(Exp->getCond()) || 2167 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) || 2168 CheckArithmeticConstantExpression(Exp->getRHS()); 2169 } 2170 2171 // Otherwise, we have to emulate some of the behavior of fold here. 2172 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant 2173 // because it can constant fold things away. To retain compatibility with 2174 // GCC code, we see if we can fold the condition to a constant (which we 2175 // should always be able to do in theory). If so, we only require the 2176 // specified arm of the conditional to be a constant. This is a horrible 2177 // hack, but is require by real world code that uses __builtin_constant_p. 2178 Expr::EvalResult EvalResult; 2179 if (!Exp->getCond()->Evaluate(EvalResult, Context) || 2180 EvalResult.HasSideEffects) { 2181 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression 2182 // won't be able to either. Use it to emit the diagnostic though. 2183 bool Res = CheckArithmeticConstantExpression(Exp->getCond()); 2184 assert(Res && "Evaluate couldn't evaluate this constant?"); 2185 return Res; 2186 } 2187 2188 // Verify that the side following the condition is also a constant. 2189 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS(); 2190 if (EvalResult.Val.getInt() == 0) 2191 std::swap(TrueSide, FalseSide); 2192 2193 if (TrueSide && CheckArithmeticConstantExpression(TrueSide)) 2194 return true; 2195 2196 // Okay, the evaluated side evaluates to a constant, so we accept this. 2197 // Check to see if the other side is obviously not a constant. If so, 2198 // emit a warning that this is a GNU extension. 2199 if (FalseSide && !FalseSide->isEvaluatable(Context)) 2200 Diag(Init->getExprLoc(), 2201 diag::ext_typecheck_expression_not_constant_but_accepted) 2202 << FalseSide->getSourceRange(); 2203 return false; 2204 } 2205 } 2206} 2207 2208bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 2209 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) 2210 Init = DIE->getInit(); 2211 2212 Init = Init->IgnoreParens(); 2213 2214 if (Init->isEvaluatable(Context)) 2215 return false; 2216 2217 // Look through CXXDefaultArgExprs; they have no meaning in this context. 2218 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init)) 2219 return CheckForConstantInitializer(DAE->getExpr(), DclT); 2220 2221 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init)) 2222 return CheckForConstantInitializer(e->getInitializer(), DclT); 2223 2224 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) { 2225 unsigned numInits = Exp->getNumInits(); 2226 for (unsigned i = 0; i < numInits; i++) { 2227 // FIXME: Need to get the type of the declaration for C++, 2228 // because it could be a reference? 2229 2230 // Implicitly-generated value initializations are okay. 2231 if (isa<CXXZeroInitValueExpr>(Exp->getInit(i)) && 2232 cast<CXXZeroInitValueExpr>(Exp->getInit(i))->isImplicit()) 2233 continue; 2234 2235 if (CheckForConstantInitializer(Exp->getInit(i), 2236 Exp->getInit(i)->getType())) 2237 return true; 2238 } 2239 return false; 2240 } 2241 2242 // FIXME: We can probably remove some of this code below, now that 2243 // Expr::Evaluate is doing the heavy lifting for scalars. 2244 2245 if (Init->isNullPointerConstant(Context)) 2246 return false; 2247 if (Init->getType()->isArithmeticType()) { 2248 QualType InitTy = Context.getCanonicalType(Init->getType()) 2249 .getUnqualifiedType(); 2250 if (InitTy == Context.BoolTy) { 2251 // Special handling for pointers implicitly cast to bool; 2252 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level. 2253 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) { 2254 Expr* SubE = ICE->getSubExpr(); 2255 if (SubE->getType()->isPointerType() || 2256 SubE->getType()->isArrayType() || 2257 SubE->getType()->isFunctionType()) { 2258 return CheckAddressConstantExpression(Init); 2259 } 2260 } 2261 } else if (InitTy->isIntegralType()) { 2262 Expr* SubE = 0; 2263 if (CastExpr* CE = dyn_cast<CastExpr>(Init)) 2264 SubE = CE->getSubExpr(); 2265 // Special check for pointer cast to int; we allow as an extension 2266 // an address constant cast to an integer if the integer 2267 // is of an appropriate width (this sort of code is apparently used 2268 // in some places). 2269 // FIXME: Add pedwarn? 2270 // FIXME: Don't allow bitfields here! Need the FieldDecl for that. 2271 if (SubE && (SubE->getType()->isPointerType() || 2272 SubE->getType()->isArrayType() || 2273 SubE->getType()->isFunctionType())) { 2274 unsigned IntWidth = Context.getTypeSize(Init->getType()); 2275 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy); 2276 if (IntWidth >= PointerWidth) 2277 return CheckAddressConstantExpression(Init); 2278 } 2279 } 2280 2281 return CheckArithmeticConstantExpression(Init); 2282 } 2283 2284 if (Init->getType()->isPointerType()) 2285 return CheckAddressConstantExpression(Init); 2286 2287 // An array type at the top level that isn't an init-list must 2288 // be a string literal 2289 if (Init->getType()->isArrayType()) 2290 return false; 2291 2292 if (Init->getType()->isFunctionType()) 2293 return false; 2294 2295 // Allow block exprs at top level. 2296 if (Init->getType()->isBlockPointerType()) 2297 return false; 2298 2299 // GCC cast to union extension 2300 // note: the validity of the cast expr is checked by CheckCastTypes() 2301 if (CastExpr *C = dyn_cast<CastExpr>(Init)) { 2302 QualType T = C->getType(); 2303 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T); 2304 } 2305 2306 InitializerElementNotConstant(Init); 2307 return true; 2308} 2309 2310void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) { 2311 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false); 2312} 2313 2314/// AddInitializerToDecl - Adds the initializer Init to the 2315/// declaration dcl. If DirectInit is true, this is C++ direct 2316/// initialization rather than copy initialization. 2317void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) { 2318 Decl *RealDecl = static_cast<Decl *>(dcl); 2319 Expr *Init = static_cast<Expr *>(init.release()); 2320 assert(Init && "missing initializer"); 2321 2322 // If there is no declaration, there was an error parsing it. Just ignore 2323 // the initializer. 2324 if (RealDecl == 0) { 2325 delete Init; 2326 return; 2327 } 2328 2329 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 2330 if (!VDecl) { 2331 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 2332 RealDecl->setInvalidDecl(); 2333 return; 2334 } 2335 // Get the decls type and save a reference for later, since 2336 // CheckInitializerTypes may change it. 2337 QualType DclT = VDecl->getType(), SavT = DclT; 2338 if (VDecl->isBlockVarDecl()) { 2339 VarDecl::StorageClass SC = VDecl->getStorageClass(); 2340 if (SC == VarDecl::Extern) { // C99 6.7.8p5 2341 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 2342 VDecl->setInvalidDecl(); 2343 } else if (!VDecl->isInvalidDecl()) { 2344 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(), 2345 VDecl->getDeclName(), DirectInit)) 2346 VDecl->setInvalidDecl(); 2347 2348 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 2349 if (!getLangOptions().CPlusPlus) { 2350 if (SC == VarDecl::Static) // C99 6.7.8p4. 2351 CheckForConstantInitializer(Init, DclT); 2352 } 2353 } 2354 } else if (VDecl->isFileVarDecl()) { 2355 if (VDecl->getStorageClass() == VarDecl::Extern) 2356 Diag(VDecl->getLocation(), diag::warn_extern_init); 2357 if (!VDecl->isInvalidDecl()) 2358 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(), 2359 VDecl->getDeclName(), DirectInit)) 2360 VDecl->setInvalidDecl(); 2361 2362 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 2363 if (!getLangOptions().CPlusPlus) { 2364 // C99 6.7.8p4. All file scoped initializers need to be constant. 2365 CheckForConstantInitializer(Init, DclT); 2366 } 2367 } 2368 // If the type changed, it means we had an incomplete type that was 2369 // completed by the initializer. For example: 2370 // int ary[] = { 1, 3, 5 }; 2371 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 2372 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 2373 VDecl->setType(DclT); 2374 Init->setType(DclT); 2375 } 2376 2377 // Attach the initializer to the decl. 2378 VDecl->setInit(Init); 2379 return; 2380} 2381 2382void Sema::ActOnUninitializedDecl(DeclTy *dcl) { 2383 Decl *RealDecl = static_cast<Decl *>(dcl); 2384 2385 // If there is no declaration, there was an error parsing it. Just ignore it. 2386 if (RealDecl == 0) 2387 return; 2388 2389 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 2390 QualType Type = Var->getType(); 2391 // C++ [dcl.init.ref]p3: 2392 // The initializer can be omitted for a reference only in a 2393 // parameter declaration (8.3.5), in the declaration of a 2394 // function return type, in the declaration of a class member 2395 // within its class declaration (9.2), and where the extern 2396 // specifier is explicitly used. 2397 if (Type->isReferenceType() && 2398 Var->getStorageClass() != VarDecl::Extern && 2399 Var->getStorageClass() != VarDecl::PrivateExtern) { 2400 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 2401 << Var->getDeclName() 2402 << SourceRange(Var->getLocation(), Var->getLocation()); 2403 Var->setInvalidDecl(); 2404 return; 2405 } 2406 2407 // C++ [dcl.init]p9: 2408 // 2409 // If no initializer is specified for an object, and the object 2410 // is of (possibly cv-qualified) non-POD class type (or array 2411 // thereof), the object shall be default-initialized; if the 2412 // object is of const-qualified type, the underlying class type 2413 // shall have a user-declared default constructor. 2414 if (getLangOptions().CPlusPlus) { 2415 QualType InitType = Type; 2416 if (const ArrayType *Array = Context.getAsArrayType(Type)) 2417 InitType = Array->getElementType(); 2418 if (Var->getStorageClass() != VarDecl::Extern && 2419 Var->getStorageClass() != VarDecl::PrivateExtern && 2420 InitType->isRecordType()) { 2421 const CXXConstructorDecl *Constructor 2422 = PerformInitializationByConstructor(InitType, 0, 0, 2423 Var->getLocation(), 2424 SourceRange(Var->getLocation(), 2425 Var->getLocation()), 2426 Var->getDeclName(), 2427 IK_Default); 2428 if (!Constructor) 2429 Var->setInvalidDecl(); 2430 } 2431 } 2432 2433#if 0 2434 // FIXME: Temporarily disabled because we are not properly parsing 2435 // linkage specifications on declarations, e.g., 2436 // 2437 // extern "C" const CGPoint CGPointerZero; 2438 // 2439 // C++ [dcl.init]p9: 2440 // 2441 // If no initializer is specified for an object, and the 2442 // object is of (possibly cv-qualified) non-POD class type (or 2443 // array thereof), the object shall be default-initialized; if 2444 // the object is of const-qualified type, the underlying class 2445 // type shall have a user-declared default 2446 // constructor. Otherwise, if no initializer is specified for 2447 // an object, the object and its subobjects, if any, have an 2448 // indeterminate initial value; if the object or any of its 2449 // subobjects are of const-qualified type, the program is 2450 // ill-formed. 2451 // 2452 // This isn't technically an error in C, so we don't diagnose it. 2453 // 2454 // FIXME: Actually perform the POD/user-defined default 2455 // constructor check. 2456 if (getLangOptions().CPlusPlus && 2457 Context.getCanonicalType(Type).isConstQualified() && 2458 Var->getStorageClass() != VarDecl::Extern) 2459 Diag(Var->getLocation(), diag::err_const_var_requires_init) 2460 << Var->getName() 2461 << SourceRange(Var->getLocation(), Var->getLocation()); 2462#endif 2463 } 2464} 2465 2466/// The declarators are chained together backwards, reverse the list. 2467Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) { 2468 // Often we have single declarators, handle them quickly. 2469 Decl *GroupDecl = static_cast<Decl*>(group); 2470 if (GroupDecl == 0) 2471 return 0; 2472 2473 Decl *Group = dyn_cast<Decl>(GroupDecl); 2474 Decl *NewGroup = 0; 2475 if (Group->getNextDeclarator() == 0) 2476 NewGroup = Group; 2477 else { // reverse the list. 2478 while (Group) { 2479 Decl *Next = Group->getNextDeclarator(); 2480 Group->setNextDeclarator(NewGroup); 2481 NewGroup = Group; 2482 Group = Next; 2483 } 2484 } 2485 // Perform semantic analysis that depends on having fully processed both 2486 // the declarator and initializer. 2487 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) { 2488 VarDecl *IDecl = dyn_cast<VarDecl>(ID); 2489 if (!IDecl) 2490 continue; 2491 QualType T = IDecl->getType(); 2492 2493 if (T->isVariableArrayType()) { 2494 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 2495 2496 // FIXME: This won't give the correct result for 2497 // int a[10][n]; 2498 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 2499 if (IDecl->isFileVarDecl()) { 2500 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) << 2501 SizeRange; 2502 2503 IDecl->setInvalidDecl(); 2504 } else { 2505 // C99 6.7.5.2p2: If an identifier is declared to be an object with 2506 // static storage duration, it shall not have a variable length array. 2507 if (IDecl->getStorageClass() == VarDecl::Static) { 2508 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage) 2509 << SizeRange; 2510 IDecl->setInvalidDecl(); 2511 } else if (IDecl->getStorageClass() == VarDecl::Extern) { 2512 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage) 2513 << SizeRange; 2514 IDecl->setInvalidDecl(); 2515 } 2516 } 2517 } else if (T->isVariablyModifiedType()) { 2518 if (IDecl->isFileVarDecl()) { 2519 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope); 2520 IDecl->setInvalidDecl(); 2521 } else { 2522 if (IDecl->getStorageClass() == VarDecl::Extern) { 2523 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage); 2524 IDecl->setInvalidDecl(); 2525 } 2526 } 2527 } 2528 2529 // Block scope. C99 6.7p7: If an identifier for an object is declared with 2530 // no linkage (C99 6.2.2p6), the type for the object shall be complete... 2531 if (IDecl->isBlockVarDecl() && 2532 IDecl->getStorageClass() != VarDecl::Extern) { 2533 if (!IDecl->isInvalidDecl() && 2534 DiagnoseIncompleteType(IDecl->getLocation(), T, 2535 diag::err_typecheck_decl_incomplete_type)) 2536 IDecl->setInvalidDecl(); 2537 } 2538 // File scope. C99 6.9.2p2: A declaration of an identifier for and 2539 // object that has file scope without an initializer, and without a 2540 // storage-class specifier or with the storage-class specifier "static", 2541 // constitutes a tentative definition. Note: A tentative definition with 2542 // external linkage is valid (C99 6.2.2p5). 2543 if (isTentativeDefinition(IDecl)) { 2544 if (T->isIncompleteArrayType()) { 2545 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete 2546 // array to be completed. Don't issue a diagnostic. 2547 } else if (!IDecl->isInvalidDecl() && 2548 DiagnoseIncompleteType(IDecl->getLocation(), T, 2549 diag::err_typecheck_decl_incomplete_type)) 2550 // C99 6.9.2p3: If the declaration of an identifier for an object is 2551 // a tentative definition and has internal linkage (C99 6.2.2p3), the 2552 // declared type shall not be an incomplete type. 2553 IDecl->setInvalidDecl(); 2554 } 2555 if (IDecl->isFileVarDecl()) 2556 CheckForFileScopedRedefinitions(S, IDecl); 2557 } 2558 return NewGroup; 2559} 2560 2561/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 2562/// to introduce parameters into function prototype scope. 2563Sema::DeclTy * 2564Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 2565 const DeclSpec &DS = D.getDeclSpec(); 2566 2567 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 2568 VarDecl::StorageClass StorageClass = VarDecl::None; 2569 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 2570 StorageClass = VarDecl::Register; 2571 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 2572 Diag(DS.getStorageClassSpecLoc(), 2573 diag::err_invalid_storage_class_in_func_decl); 2574 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2575 } 2576 if (DS.isThreadSpecified()) { 2577 Diag(DS.getThreadSpecLoc(), 2578 diag::err_invalid_storage_class_in_func_decl); 2579 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2580 } 2581 2582 // Check that there are no default arguments inside the type of this 2583 // parameter (C++ only). 2584 if (getLangOptions().CPlusPlus) 2585 CheckExtraCXXDefaultArguments(D); 2586 2587 // In this context, we *do not* check D.getInvalidType(). If the declarator 2588 // type was invalid, GetTypeForDeclarator() still returns a "valid" type, 2589 // though it will not reflect the user specified type. 2590 QualType parmDeclType = GetTypeForDeclarator(D, S); 2591 2592 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type"); 2593 2594 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 2595 // Can this happen for params? We already checked that they don't conflict 2596 // among each other. Here they can only shadow globals, which is ok. 2597 IdentifierInfo *II = D.getIdentifier(); 2598 if (II) { 2599 if (Decl *PrevDecl = LookupDeclInScope(II, Decl::IDNS_Ordinary, S)) { 2600 if (PrevDecl->isTemplateParameter()) { 2601 // Maybe we will complain about the shadowed template parameter. 2602 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 2603 // Just pretend that we didn't see the previous declaration. 2604 PrevDecl = 0; 2605 } else if (S->isDeclScope(PrevDecl)) { 2606 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 2607 2608 // Recover by removing the name 2609 II = 0; 2610 D.SetIdentifier(0, D.getIdentifierLoc()); 2611 } 2612 } 2613 } 2614 2615 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]). 2616 // Doing the promotion here has a win and a loss. The win is the type for 2617 // both Decl's and DeclRefExpr's will match (a convenient invariant for the 2618 // code generator). The loss is the orginal type isn't preserved. For example: 2619 // 2620 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *" 2621 // int blockvardecl[5]; 2622 // sizeof(parmvardecl); // size == 4 2623 // sizeof(blockvardecl); // size == 20 2624 // } 2625 // 2626 // For expressions, all implicit conversions are captured using the 2627 // ImplicitCastExpr AST node (we have no such mechanism for Decl's). 2628 // 2629 // FIXME: If a source translation tool needs to see the original type, then 2630 // we need to consider storing both types (in ParmVarDecl)... 2631 // 2632 if (parmDeclType->isArrayType()) { 2633 // int x[restrict 4] -> int *restrict 2634 parmDeclType = Context.getArrayDecayedType(parmDeclType); 2635 } else if (parmDeclType->isFunctionType()) 2636 parmDeclType = Context.getPointerType(parmDeclType); 2637 2638 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, 2639 D.getIdentifierLoc(), II, 2640 parmDeclType, StorageClass, 2641 0); 2642 2643 if (D.getInvalidType()) 2644 New->setInvalidDecl(); 2645 2646 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 2647 if (D.getCXXScopeSpec().isSet()) { 2648 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 2649 << D.getCXXScopeSpec().getRange(); 2650 New->setInvalidDecl(); 2651 } 2652 2653 // Add the parameter declaration into this scope. 2654 S->AddDecl(New); 2655 if (II) 2656 IdResolver.AddDecl(New); 2657 2658 ProcessDeclAttributes(New, D); 2659 return New; 2660 2661} 2662 2663void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) { 2664 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 2665 "Not a function declarator!"); 2666 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2667 2668 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 2669 // for a K&R function. 2670 if (!FTI.hasPrototype) { 2671 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 2672 if (FTI.ArgInfo[i].Param == 0) { 2673 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 2674 << FTI.ArgInfo[i].Ident; 2675 // Implicitly declare the argument as type 'int' for lack of a better 2676 // type. 2677 DeclSpec DS; 2678 const char* PrevSpec; // unused 2679 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 2680 PrevSpec); 2681 Declarator ParamD(DS, Declarator::KNRTypeListContext); 2682 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 2683 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 2684 } 2685 } 2686 } 2687} 2688 2689Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 2690 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 2691 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 2692 "Not a function declarator!"); 2693 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 2694 2695 if (FTI.hasPrototype) { 2696 // FIXME: Diagnose arguments without names in C. 2697 } 2698 2699 Scope *ParentScope = FnBodyScope->getParent(); 2700 2701 return ActOnStartOfFunctionDef(FnBodyScope, 2702 ActOnDeclarator(ParentScope, D, 0, 2703 /*IsFunctionDefinition=*/true)); 2704} 2705 2706Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) { 2707 Decl *decl = static_cast<Decl*>(D); 2708 FunctionDecl *FD = cast<FunctionDecl>(decl); 2709 2710 // See if this is a redefinition. 2711 const FunctionDecl *Definition; 2712 if (FD->getBody(Definition)) { 2713 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 2714 Diag(Definition->getLocation(), diag::note_previous_definition); 2715 } 2716 2717 PushDeclContext(FnBodyScope, FD); 2718 2719 // Check the validity of our function parameters 2720 CheckParmsForFunctionDef(FD); 2721 2722 // Introduce our parameters into the function scope 2723 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 2724 ParmVarDecl *Param = FD->getParamDecl(p); 2725 Param->setOwningFunction(FD); 2726 2727 // If this has an identifier, add it to the scope stack. 2728 if (Param->getIdentifier()) 2729 PushOnScopeChains(Param, FnBodyScope); 2730 } 2731 2732 // Checking attributes of current function definition 2733 // dllimport attribute. 2734 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) { 2735 // dllimport attribute cannot be applied to definition. 2736 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) { 2737 Diag(FD->getLocation(), 2738 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 2739 << "dllimport"; 2740 FD->setInvalidDecl(); 2741 return FD; 2742 } else { 2743 // If a symbol previously declared dllimport is later defined, the 2744 // attribute is ignored in subsequent references, and a warning is 2745 // emitted. 2746 Diag(FD->getLocation(), 2747 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 2748 << FD->getNameAsCString() << "dllimport"; 2749 } 2750 } 2751 return FD; 2752} 2753 2754Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) { 2755 Decl *dcl = static_cast<Decl *>(D); 2756 Stmt *Body = static_cast<Stmt*>(BodyArg.release()); 2757 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) { 2758 FD->setBody(Body); 2759 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 2760 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 2761 MD->setBody((Stmt*)Body); 2762 } else 2763 return 0; 2764 PopDeclContext(); 2765 // Verify and clean out per-function state. 2766 2767 // Check goto/label use. 2768 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 2769 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) { 2770 // Verify that we have no forward references left. If so, there was a goto 2771 // or address of a label taken, but no definition of it. Label fwd 2772 // definitions are indicated with a null substmt. 2773 if (I->second->getSubStmt() == 0) { 2774 LabelStmt *L = I->second; 2775 // Emit error. 2776 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName(); 2777 2778 // At this point, we have gotos that use the bogus label. Stitch it into 2779 // the function body so that they aren't leaked and that the AST is well 2780 // formed. 2781 if (Body) { 2782 L->setSubStmt(new NullStmt(L->getIdentLoc())); 2783 cast<CompoundStmt>(Body)->push_back(L); 2784 } else { 2785 // The whole function wasn't parsed correctly, just delete this. 2786 delete L; 2787 } 2788 } 2789 } 2790 LabelMap.clear(); 2791 2792 return D; 2793} 2794 2795/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 2796/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 2797NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 2798 IdentifierInfo &II, Scope *S) { 2799 // Extension in C99. Legal in C90, but warn about it. 2800 if (getLangOptions().C99) 2801 Diag(Loc, diag::ext_implicit_function_decl) << &II; 2802 else 2803 Diag(Loc, diag::warn_implicit_function_decl) << &II; 2804 2805 // FIXME: handle stuff like: 2806 // void foo() { extern float X(); } 2807 // void bar() { X(); } <-- implicit decl for X in another scope. 2808 2809 // Set a Declarator for the implicit definition: int foo(); 2810 const char *Dummy; 2811 DeclSpec DS; 2812 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy); 2813 Error = Error; // Silence warning. 2814 assert(!Error && "Error setting up implicit decl!"); 2815 Declarator D(DS, Declarator::BlockContext); 2816 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc, D)); 2817 D.SetIdentifier(&II, Loc); 2818 2819 // Insert this function into translation-unit scope. 2820 2821 DeclContext *PrevDC = CurContext; 2822 CurContext = Context.getTranslationUnitDecl(); 2823 2824 FunctionDecl *FD = 2825 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0))); 2826 FD->setImplicit(); 2827 2828 CurContext = PrevDC; 2829 2830 return FD; 2831} 2832 2833 2834TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 2835 Decl *LastDeclarator) { 2836 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 2837 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 2838 2839 // Scope manipulation handled by caller. 2840 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 2841 D.getIdentifierLoc(), 2842 D.getIdentifier(), 2843 T); 2844 NewTD->setNextDeclarator(LastDeclarator); 2845 if (D.getInvalidType()) 2846 NewTD->setInvalidDecl(); 2847 return NewTD; 2848} 2849 2850/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 2851/// former case, Name will be non-null. In the later case, Name will be null. 2852/// TagSpec indicates what kind of tag this is. TK indicates whether this is a 2853/// reference/declaration/definition of a tag. 2854Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK, 2855 SourceLocation KWLoc, const CXXScopeSpec &SS, 2856 IdentifierInfo *Name, SourceLocation NameLoc, 2857 AttributeList *Attr, 2858 MultiTemplateParamsArg TemplateParameterLists) { 2859 // If this is not a definition, it must have a name. 2860 assert((Name != 0 || TK == TK_Definition) && 2861 "Nameless record must be a definition!"); 2862 2863 TagDecl::TagKind Kind; 2864 switch (TagSpec) { 2865 default: assert(0 && "Unknown tag type!"); 2866 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 2867 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 2868 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 2869 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break; 2870 } 2871 2872 DeclContext *SearchDC = CurContext; 2873 DeclContext *DC = CurContext; 2874 DeclContext *LexicalContext = CurContext; 2875 Decl *PrevDecl = 0; 2876 2877 bool Invalid = false; 2878 2879 if (Name && SS.isNotEmpty()) { 2880 // We have a nested-name tag ('struct foo::bar'). 2881 2882 // Check for invalid 'foo::'. 2883 if (SS.isInvalid()) { 2884 Name = 0; 2885 goto CreateNewDecl; 2886 } 2887 2888 DC = static_cast<DeclContext*>(SS.getScopeRep()); 2889 // Look-up name inside 'foo::'. 2890 PrevDecl = dyn_cast_or_null<TagDecl>( 2891 LookupDeclInContext(Name, Decl::IDNS_Tag, DC).getAsDecl()); 2892 2893 // A tag 'foo::bar' must already exist. 2894 if (PrevDecl == 0) { 2895 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange(); 2896 Name = 0; 2897 goto CreateNewDecl; 2898 } 2899 } else if (Name) { 2900 // If this is a named struct, check to see if there was a previous forward 2901 // declaration or definition. 2902 PrevDecl = dyn_cast_or_null<NamedDecl>(LookupDeclInScope(Name, 2903 Decl::IDNS_Tag,S) 2904 .getAsDecl()); 2905 2906 if (!getLangOptions().CPlusPlus && TK != TK_Reference) { 2907 // FIXME: This makes sure that we ignore the contexts associated 2908 // with C structs, unions, and enums when looking for a matching 2909 // tag declaration or definition. See the similar lookup tweak 2910 // in Sema::LookupDecl; is there a better way to deal with this? 2911 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 2912 SearchDC = SearchDC->getParent(); 2913 } 2914 } 2915 2916 if (PrevDecl && PrevDecl->isTemplateParameter()) { 2917 // Maybe we will complain about the shadowed template parameter. 2918 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl); 2919 // Just pretend that we didn't see the previous declaration. 2920 PrevDecl = 0; 2921 } 2922 2923 if (PrevDecl) { 2924 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 2925 // If this is a use of a previous tag, or if the tag is already declared 2926 // in the same scope (so that the definition/declaration completes or 2927 // rementions the tag), reuse the decl. 2928 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) { 2929 // Make sure that this wasn't declared as an enum and now used as a 2930 // struct or something similar. 2931 if (PrevTagDecl->getTagKind() != Kind) { 2932 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 2933 Diag(PrevDecl->getLocation(), diag::note_previous_use); 2934 // Recover by making this an anonymous redefinition. 2935 Name = 0; 2936 PrevDecl = 0; 2937 Invalid = true; 2938 } else { 2939 // If this is a use, just return the declaration we found. 2940 2941 // FIXME: In the future, return a variant or some other clue 2942 // for the consumer of this Decl to know it doesn't own it. 2943 // For our current ASTs this shouldn't be a problem, but will 2944 // need to be changed with DeclGroups. 2945 if (TK == TK_Reference) 2946 return PrevDecl; 2947 2948 // Diagnose attempts to redefine a tag. 2949 if (TK == TK_Definition) { 2950 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) { 2951 Diag(NameLoc, diag::err_redefinition) << Name; 2952 Diag(Def->getLocation(), diag::note_previous_definition); 2953 // If this is a redefinition, recover by making this 2954 // struct be anonymous, which will make any later 2955 // references get the previous definition. 2956 Name = 0; 2957 PrevDecl = 0; 2958 Invalid = true; 2959 } else { 2960 // If the type is currently being defined, complain 2961 // about a nested redefinition. 2962 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 2963 if (Tag->isBeingDefined()) { 2964 Diag(NameLoc, diag::err_nested_redefinition) << Name; 2965 Diag(PrevTagDecl->getLocation(), 2966 diag::note_previous_definition); 2967 Name = 0; 2968 PrevDecl = 0; 2969 Invalid = true; 2970 } 2971 } 2972 2973 // Okay, this is definition of a previously declared or referenced 2974 // tag PrevDecl. We're going to create a new Decl for it. 2975 } 2976 } 2977 // If we get here we have (another) forward declaration or we 2978 // have a definition. Just create a new decl. 2979 } else { 2980 // If we get here, this is a definition of a new tag type in a nested 2981 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 2982 // new decl/type. We set PrevDecl to NULL so that the entities 2983 // have distinct types. 2984 PrevDecl = 0; 2985 } 2986 // If we get here, we're going to create a new Decl. If PrevDecl 2987 // is non-NULL, it's a definition of the tag declared by 2988 // PrevDecl. If it's NULL, we have a new definition. 2989 } else { 2990 // PrevDecl is a namespace, template, or anything else 2991 // that lives in the IDNS_Tag identifier namespace. 2992 if (isDeclInScope(PrevDecl, SearchDC, S)) { 2993 // The tag name clashes with a namespace name, issue an error and 2994 // recover by making this tag be anonymous. 2995 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 2996 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2997 Name = 0; 2998 PrevDecl = 0; 2999 Invalid = true; 3000 } else { 3001 // The existing declaration isn't relevant to us; we're in a 3002 // new scope, so clear out the previous declaration. 3003 PrevDecl = 0; 3004 } 3005 } 3006 } else if (TK == TK_Reference && SS.isEmpty() && Name && 3007 (Kind != TagDecl::TK_enum)) { 3008 // C++ [basic.scope.pdecl]p5: 3009 // -- for an elaborated-type-specifier of the form 3010 // 3011 // class-key identifier 3012 // 3013 // if the elaborated-type-specifier is used in the 3014 // decl-specifier-seq or parameter-declaration-clause of a 3015 // function defined in namespace scope, the identifier is 3016 // declared as a class-name in the namespace that contains 3017 // the declaration; otherwise, except as a friend 3018 // declaration, the identifier is declared in the smallest 3019 // non-class, non-function-prototype scope that contains the 3020 // declaration. 3021 // 3022 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 3023 // C structs and unions. 3024 3025 // Find the context where we'll be declaring the tag. 3026 // FIXME: We would like to maintain the current DeclContext as the 3027 // lexical context, 3028 while (DC->isRecord()) 3029 DC = DC->getParent(); 3030 LexicalContext = DC; 3031 3032 // Find the scope where we'll be declaring the tag. 3033 while (S->isClassScope() || 3034 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) || 3035 ((S->getFlags() & Scope::DeclScope) == 0) || 3036 (S->getEntity() && 3037 ((DeclContext *)S->getEntity())->isTransparentContext())) 3038 S = S->getParent(); 3039 } 3040 3041CreateNewDecl: 3042 3043 // If there is an identifier, use the location of the identifier as the 3044 // location of the decl, otherwise use the location of the struct/union 3045 // keyword. 3046 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 3047 3048 // Otherwise, create a new declaration. If there is a previous 3049 // declaration of the same entity, the two will be linked via 3050 // PrevDecl. 3051 TagDecl *New; 3052 3053 if (Kind == TagDecl::TK_enum) { 3054 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 3055 // enum X { A, B, C } D; D should chain to X. 3056 New = EnumDecl::Create(Context, DC, Loc, Name, 3057 cast_or_null<EnumDecl>(PrevDecl)); 3058 // If this is an undefined enum, warn. 3059 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum); 3060 } else { 3061 // struct/union/class 3062 3063 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 3064 // struct X { int A; } D; D should chain to X. 3065 if (getLangOptions().CPlusPlus) 3066 // FIXME: Look for a way to use RecordDecl for simple structs. 3067 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name, 3068 cast_or_null<CXXRecordDecl>(PrevDecl)); 3069 else 3070 New = RecordDecl::Create(Context, Kind, DC, Loc, Name, 3071 cast_or_null<RecordDecl>(PrevDecl)); 3072 } 3073 3074 if (Kind != TagDecl::TK_enum) { 3075 // Handle #pragma pack: if the #pragma pack stack has non-default 3076 // alignment, make up a packed attribute for this decl. These 3077 // attributes are checked when the ASTContext lays out the 3078 // structure. 3079 // 3080 // It is important for implementing the correct semantics that this 3081 // happen here (in act on tag decl). The #pragma pack stack is 3082 // maintained as a result of parser callbacks which can occur at 3083 // many points during the parsing of a struct declaration (because 3084 // the #pragma tokens are effectively skipped over during the 3085 // parsing of the struct). 3086 if (unsigned Alignment = PackContext.getAlignment()) 3087 New->addAttr(new PackedAttr(Alignment * 8)); 3088 } 3089 3090 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) { 3091 // C++ [dcl.typedef]p3: 3092 // [...] Similarly, in a given scope, a class or enumeration 3093 // shall not be declared with the same name as a typedef-name 3094 // that is declared in that scope and refers to a type other 3095 // than the class or enumeration itself. 3096 LookupResult Lookup = LookupName(S, Name, 3097 LookupCriteria(LookupCriteria::Ordinary, 3098 true, true)); 3099 TypedefDecl *PrevTypedef = 0; 3100 if (Lookup.getKind() == LookupResult::Found) 3101 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl()); 3102 3103 if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) && 3104 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) != 3105 Context.getCanonicalType(Context.getTypeDeclType(New))) { 3106 Diag(Loc, diag::err_tag_definition_of_typedef) 3107 << Context.getTypeDeclType(New) 3108 << PrevTypedef->getUnderlyingType(); 3109 Diag(PrevTypedef->getLocation(), diag::note_previous_definition); 3110 Invalid = true; 3111 } 3112 } 3113 3114 if (Invalid) 3115 New->setInvalidDecl(); 3116 3117 if (Attr) 3118 ProcessDeclAttributeList(New, Attr); 3119 3120 // If we're declaring or defining a tag in function prototype scope 3121 // in C, note that this type can only be used within the function. 3122 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus) 3123 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 3124 3125 // Set the lexical context. If the tag has a C++ scope specifier, the 3126 // lexical context will be different from the semantic context. 3127 New->setLexicalDeclContext(LexicalContext); 3128 3129 if (TK == TK_Definition) 3130 New->startDefinition(); 3131 3132 // If this has an identifier, add it to the scope stack. 3133 if (Name) { 3134 S = getNonFieldDeclScope(S); 3135 3136 // Add it to the decl chain. 3137 if (LexicalContext != CurContext) { 3138 // FIXME: PushOnScopeChains should not rely on CurContext! 3139 DeclContext *OldContext = CurContext; 3140 CurContext = LexicalContext; 3141 PushOnScopeChains(New, S); 3142 CurContext = OldContext; 3143 } else 3144 PushOnScopeChains(New, S); 3145 } else { 3146 LexicalContext->addDecl(New); 3147 } 3148 3149 return New; 3150} 3151 3152void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) { 3153 TagDecl *Tag = cast<TagDecl>((Decl *)TagD); 3154 3155 // Enter the tag context. 3156 PushDeclContext(S, Tag); 3157 3158 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) { 3159 FieldCollector->StartClass(); 3160 3161 if (Record->getIdentifier()) { 3162 // C++ [class]p2: 3163 // [...] The class-name is also inserted into the scope of the 3164 // class itself; this is known as the injected-class-name. For 3165 // purposes of access checking, the injected-class-name is treated 3166 // as if it were a public member name. 3167 RecordDecl *InjectedClassName 3168 = CXXRecordDecl::Create(Context, Record->getTagKind(), 3169 CurContext, Record->getLocation(), 3170 Record->getIdentifier(), Record); 3171 InjectedClassName->setImplicit(); 3172 PushOnScopeChains(InjectedClassName, S); 3173 } 3174 } 3175} 3176 3177void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) { 3178 TagDecl *Tag = cast<TagDecl>((Decl *)TagD); 3179 3180 if (isa<CXXRecordDecl>(Tag)) 3181 FieldCollector->FinishClass(); 3182 3183 // Exit this scope of this tag's definition. 3184 PopDeclContext(); 3185 3186 // Notify the consumer that we've defined a tag. 3187 Consumer.HandleTagDeclDefinition(Tag); 3188} 3189 3190/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array 3191/// types into constant array types in certain situations which would otherwise 3192/// be errors (for GCC compatibility). 3193static QualType TryToFixInvalidVariablyModifiedType(QualType T, 3194 ASTContext &Context) { 3195 // This method tries to turn a variable array into a constant 3196 // array even when the size isn't an ICE. This is necessary 3197 // for compatibility with code that depends on gcc's buggy 3198 // constant expression folding, like struct {char x[(int)(char*)2];} 3199 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 3200 if (!VLATy) return QualType(); 3201 3202 Expr::EvalResult EvalResult; 3203 if (!VLATy->getSizeExpr() || 3204 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context)) 3205 return QualType(); 3206 3207 assert(EvalResult.Val.isInt() && "Size expressions must be integers!"); 3208 llvm::APSInt &Res = EvalResult.Val.getInt(); 3209 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) 3210 return Context.getConstantArrayType(VLATy->getElementType(), 3211 Res, ArrayType::Normal, 0); 3212 return QualType(); 3213} 3214 3215bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 3216 QualType FieldTy, const Expr *BitWidth) { 3217 // FIXME: 6.7.2.1p4 - verify the field type. 3218 3219 llvm::APSInt Value; 3220 if (VerifyIntegerConstantExpression(BitWidth, &Value)) 3221 return true; 3222 3223 // Zero-width bitfield is ok for anonymous field. 3224 if (Value == 0 && FieldName) 3225 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 3226 3227 if (Value.isNegative()) 3228 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName; 3229 3230 uint64_t TypeSize = Context.getTypeSize(FieldTy); 3231 // FIXME: We won't need the 0 size once we check that the field type is valid. 3232 if (TypeSize && Value.getZExtValue() > TypeSize) 3233 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 3234 << FieldName << (unsigned)TypeSize; 3235 3236 return false; 3237} 3238 3239/// ActOnField - Each field of a struct/union/class is passed into this in order 3240/// to create a FieldDecl object for it. 3241Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD, 3242 SourceLocation DeclStart, 3243 Declarator &D, ExprTy *BitfieldWidth) { 3244 IdentifierInfo *II = D.getIdentifier(); 3245 Expr *BitWidth = (Expr*)BitfieldWidth; 3246 SourceLocation Loc = DeclStart; 3247 RecordDecl *Record = (RecordDecl *)TagD; 3248 if (II) Loc = D.getIdentifierLoc(); 3249 3250 // FIXME: Unnamed fields can be handled in various different ways, for 3251 // example, unnamed unions inject all members into the struct namespace! 3252 3253 QualType T = GetTypeForDeclarator(D, S); 3254 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 3255 bool InvalidDecl = false; 3256 3257 // C99 6.7.2.1p8: A member of a structure or union may have any type other 3258 // than a variably modified type. 3259 if (T->isVariablyModifiedType()) { 3260 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context); 3261 if (!FixedTy.isNull()) { 3262 Diag(Loc, diag::warn_illegal_constant_array_size); 3263 T = FixedTy; 3264 } else { 3265 Diag(Loc, diag::err_typecheck_field_variable_size); 3266 T = Context.IntTy; 3267 InvalidDecl = true; 3268 } 3269 } 3270 3271 if (BitWidth) { 3272 if (VerifyBitField(Loc, II, T, BitWidth)) 3273 InvalidDecl = true; 3274 } else { 3275 // Not a bitfield. 3276 3277 // validate II. 3278 3279 } 3280 3281 // FIXME: Chain fielddecls together. 3282 FieldDecl *NewFD; 3283 3284 NewFD = FieldDecl::Create(Context, Record, 3285 Loc, II, T, BitWidth, 3286 D.getDeclSpec().getStorageClassSpec() == 3287 DeclSpec::SCS_mutable); 3288 3289 if (II) { 3290 Decl *PrevDecl 3291 = LookupDeclInScope(II, Decl::IDNS_Member, S, false); 3292 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S) 3293 && !isa<TagDecl>(PrevDecl)) { 3294 Diag(Loc, diag::err_duplicate_member) << II; 3295 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3296 NewFD->setInvalidDecl(); 3297 Record->setInvalidDecl(); 3298 } 3299 } 3300 3301 if (getLangOptions().CPlusPlus) { 3302 CheckExtraCXXDefaultArguments(D); 3303 if (!T->isPODType()) 3304 cast<CXXRecordDecl>(Record)->setPOD(false); 3305 } 3306 3307 ProcessDeclAttributes(NewFD, D); 3308 3309 if (D.getInvalidType() || InvalidDecl) 3310 NewFD->setInvalidDecl(); 3311 3312 if (II) { 3313 PushOnScopeChains(NewFD, S); 3314 } else 3315 Record->addDecl(NewFD); 3316 3317 return NewFD; 3318} 3319 3320/// TranslateIvarVisibility - Translate visibility from a token ID to an 3321/// AST enum value. 3322static ObjCIvarDecl::AccessControl 3323TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 3324 switch (ivarVisibility) { 3325 default: assert(0 && "Unknown visitibility kind"); 3326 case tok::objc_private: return ObjCIvarDecl::Private; 3327 case tok::objc_public: return ObjCIvarDecl::Public; 3328 case tok::objc_protected: return ObjCIvarDecl::Protected; 3329 case tok::objc_package: return ObjCIvarDecl::Package; 3330 } 3331} 3332 3333/// ActOnIvar - Each ivar field of an objective-c class is passed into this 3334/// in order to create an IvarDecl object for it. 3335Sema::DeclTy *Sema::ActOnIvar(Scope *S, 3336 SourceLocation DeclStart, 3337 Declarator &D, ExprTy *BitfieldWidth, 3338 tok::ObjCKeywordKind Visibility) { 3339 3340 IdentifierInfo *II = D.getIdentifier(); 3341 Expr *BitWidth = (Expr*)BitfieldWidth; 3342 SourceLocation Loc = DeclStart; 3343 if (II) Loc = D.getIdentifierLoc(); 3344 3345 // FIXME: Unnamed fields can be handled in various different ways, for 3346 // example, unnamed unions inject all members into the struct namespace! 3347 3348 QualType T = GetTypeForDeclarator(D, S); 3349 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 3350 bool InvalidDecl = false; 3351 3352 if (BitWidth) { 3353 // TODO: Validate. 3354 //printf("WARNING: BITFIELDS IGNORED!\n"); 3355 3356 // 6.7.2.1p3 3357 // 6.7.2.1p4 3358 3359 } else { 3360 // Not a bitfield. 3361 3362 // validate II. 3363 3364 } 3365 3366 // C99 6.7.2.1p8: A member of a structure or union may have any type other 3367 // than a variably modified type. 3368 if (T->isVariablyModifiedType()) { 3369 Diag(Loc, diag::err_typecheck_ivar_variable_size); 3370 InvalidDecl = true; 3371 } 3372 3373 // Get the visibility (access control) for this ivar. 3374 ObjCIvarDecl::AccessControl ac = 3375 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 3376 : ObjCIvarDecl::None; 3377 3378 // Construct the decl. 3379 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac, 3380 (Expr *)BitfieldWidth); 3381 3382 if (II) { 3383 Decl *PrevDecl = LookupDeclInScope(II, Decl::IDNS_Member, S, false); 3384 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S) 3385 && !isa<TagDecl>(PrevDecl)) { 3386 Diag(Loc, diag::err_duplicate_member) << II; 3387 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3388 NewID->setInvalidDecl(); 3389 } 3390 } 3391 3392 // Process attributes attached to the ivar. 3393 ProcessDeclAttributes(NewID, D); 3394 3395 if (D.getInvalidType() || InvalidDecl) 3396 NewID->setInvalidDecl(); 3397 3398 if (II) { 3399 // FIXME: When interfaces are DeclContexts, we'll need to add 3400 // these to the interface. 3401 S->AddDecl(NewID); 3402 IdResolver.AddDecl(NewID); 3403 } 3404 3405 return NewID; 3406} 3407 3408void Sema::ActOnFields(Scope* S, 3409 SourceLocation RecLoc, DeclTy *RecDecl, 3410 DeclTy **Fields, unsigned NumFields, 3411 SourceLocation LBrac, SourceLocation RBrac, 3412 AttributeList *Attr) { 3413 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl); 3414 assert(EnclosingDecl && "missing record or interface decl"); 3415 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 3416 3417 // Verify that all the fields are okay. 3418 unsigned NumNamedMembers = 0; 3419 llvm::SmallVector<FieldDecl*, 32> RecFields; 3420 3421 for (unsigned i = 0; i != NumFields; ++i) { 3422 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i])); 3423 assert(FD && "missing field decl"); 3424 3425 // Get the type for the field. 3426 Type *FDTy = FD->getType().getTypePtr(); 3427 3428 if (!FD->isAnonymousStructOrUnion()) { 3429 // Remember all fields written by the user. 3430 RecFields.push_back(FD); 3431 } 3432 3433 // C99 6.7.2.1p2 - A field may not be a function type. 3434 if (FDTy->isFunctionType()) { 3435 Diag(FD->getLocation(), diag::err_field_declared_as_function) 3436 << FD->getDeclName(); 3437 FD->setInvalidDecl(); 3438 EnclosingDecl->setInvalidDecl(); 3439 continue; 3440 } 3441 // C99 6.7.2.1p2 - A field may not be an incomplete type except... 3442 if (FDTy->isIncompleteType()) { 3443 if (!Record) { // Incomplete ivar type is always an error. 3444 DiagnoseIncompleteType(FD->getLocation(), FD->getType(), 3445 diag::err_field_incomplete); 3446 FD->setInvalidDecl(); 3447 EnclosingDecl->setInvalidDecl(); 3448 continue; 3449 } 3450 if (i != NumFields-1 || // ... that the last member ... 3451 !Record->isStruct() || // ... of a structure ... 3452 !FDTy->isArrayType()) { //... may have incomplete array type. 3453 DiagnoseIncompleteType(FD->getLocation(), FD->getType(), 3454 diag::err_field_incomplete); 3455 FD->setInvalidDecl(); 3456 EnclosingDecl->setInvalidDecl(); 3457 continue; 3458 } 3459 if (NumNamedMembers < 1) { //... must have more than named member ... 3460 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 3461 << FD->getDeclName(); 3462 FD->setInvalidDecl(); 3463 EnclosingDecl->setInvalidDecl(); 3464 continue; 3465 } 3466 // Okay, we have a legal flexible array member at the end of the struct. 3467 if (Record) 3468 Record->setHasFlexibleArrayMember(true); 3469 } 3470 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the 3471 /// field of another structure or the element of an array. 3472 if (const RecordType *FDTTy = FDTy->getAsRecordType()) { 3473 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 3474 // If this is a member of a union, then entire union becomes "flexible". 3475 if (Record && Record->isUnion()) { 3476 Record->setHasFlexibleArrayMember(true); 3477 } else { 3478 // If this is a struct/class and this is not the last element, reject 3479 // it. Note that GCC supports variable sized arrays in the middle of 3480 // structures. 3481 if (i != NumFields-1) { 3482 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct) 3483 << FD->getDeclName(); 3484 FD->setInvalidDecl(); 3485 EnclosingDecl->setInvalidDecl(); 3486 continue; 3487 } 3488 // We support flexible arrays at the end of structs in other structs 3489 // as an extension. 3490 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 3491 << FD->getDeclName(); 3492 if (Record) 3493 Record->setHasFlexibleArrayMember(true); 3494 } 3495 } 3496 } 3497 /// A field cannot be an Objective-c object 3498 if (FDTy->isObjCInterfaceType()) { 3499 Diag(FD->getLocation(), diag::err_statically_allocated_object) 3500 << FD->getDeclName(); 3501 FD->setInvalidDecl(); 3502 EnclosingDecl->setInvalidDecl(); 3503 continue; 3504 } 3505 // Keep track of the number of named members. 3506 if (FD->getIdentifier()) 3507 ++NumNamedMembers; 3508 } 3509 3510 // Okay, we successfully defined 'Record'. 3511 if (Record) { 3512 Record->completeDefinition(Context); 3513 } else { 3514 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]); 3515 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 3516 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac); 3517 // Must enforce the rule that ivars in the base classes may not be 3518 // duplicates. 3519 if (ID->getSuperClass()) { 3520 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(), 3521 IVE = ID->ivar_end(); IVI != IVE; ++IVI) { 3522 ObjCIvarDecl* Ivar = (*IVI); 3523 IdentifierInfo *II = Ivar->getIdentifier(); 3524 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II); 3525 if (prevIvar) { 3526 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II; 3527 Diag(prevIvar->getLocation(), diag::note_previous_declaration); 3528 } 3529 } 3530 } 3531 } 3532 else if (ObjCImplementationDecl *IMPDecl = 3533 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 3534 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 3535 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size()); 3536 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 3537 } 3538 } 3539 3540 if (Attr) 3541 ProcessDeclAttributeList(Record, Attr); 3542} 3543 3544Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl, 3545 DeclTy *lastEnumConst, 3546 SourceLocation IdLoc, IdentifierInfo *Id, 3547 SourceLocation EqualLoc, ExprTy *val) { 3548 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl)); 3549 EnumConstantDecl *LastEnumConst = 3550 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst)); 3551 Expr *Val = static_cast<Expr*>(val); 3552 3553 // The scope passed in may not be a decl scope. Zip up the scope tree until 3554 // we find one that is. 3555 S = getNonFieldDeclScope(S); 3556 3557 // Verify that there isn't already something declared with this name in this 3558 // scope. 3559 Decl *PrevDecl = LookupDeclInScope(Id, Decl::IDNS_Ordinary, S); 3560 if (PrevDecl && PrevDecl->isTemplateParameter()) { 3561 // Maybe we will complain about the shadowed template parameter. 3562 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 3563 // Just pretend that we didn't see the previous declaration. 3564 PrevDecl = 0; 3565 } 3566 3567 if (PrevDecl) { 3568 // When in C++, we may get a TagDecl with the same name; in this case the 3569 // enum constant will 'hide' the tag. 3570 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 3571 "Received TagDecl when not in C++!"); 3572 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 3573 if (isa<EnumConstantDecl>(PrevDecl)) 3574 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 3575 else 3576 Diag(IdLoc, diag::err_redefinition) << Id; 3577 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 3578 delete Val; 3579 return 0; 3580 } 3581 } 3582 3583 llvm::APSInt EnumVal(32); 3584 QualType EltTy; 3585 if (Val) { 3586 // Make sure to promote the operand type to int. 3587 UsualUnaryConversions(Val); 3588 3589 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 3590 SourceLocation ExpLoc; 3591 if (VerifyIntegerConstantExpression(Val, &EnumVal)) { 3592 delete Val; 3593 Val = 0; // Just forget about it. 3594 } else { 3595 EltTy = Val->getType(); 3596 } 3597 } 3598 3599 if (!Val) { 3600 if (LastEnumConst) { 3601 // Assign the last value + 1. 3602 EnumVal = LastEnumConst->getInitVal(); 3603 ++EnumVal; 3604 3605 // Check for overflow on increment. 3606 if (EnumVal < LastEnumConst->getInitVal()) 3607 Diag(IdLoc, diag::warn_enum_value_overflow); 3608 3609 EltTy = LastEnumConst->getType(); 3610 } else { 3611 // First value, set to zero. 3612 EltTy = Context.IntTy; 3613 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy))); 3614 } 3615 } 3616 3617 EnumConstantDecl *New = 3618 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy, 3619 Val, EnumVal); 3620 3621 // Register this decl in the current scope stack. 3622 PushOnScopeChains(New, S); 3623 3624 return New; 3625} 3626 3627// FIXME: For consistency with ActOnFields(), we should have the parser 3628// pass in the source location for the left/right braces. 3629void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX, 3630 DeclTy **Elements, unsigned NumElements) { 3631 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX)); 3632 QualType EnumType = Context.getTypeDeclType(Enum); 3633 3634 // TODO: If the result value doesn't fit in an int, it must be a long or long 3635 // long value. ISO C does not support this, but GCC does as an extension, 3636 // emit a warning. 3637 unsigned IntWidth = Context.Target.getIntWidth(); 3638 3639 // Verify that all the values are okay, compute the size of the values, and 3640 // reverse the list. 3641 unsigned NumNegativeBits = 0; 3642 unsigned NumPositiveBits = 0; 3643 3644 // Keep track of whether all elements have type int. 3645 bool AllElementsInt = true; 3646 3647 for (unsigned i = 0; i != NumElements; ++i) { 3648 EnumConstantDecl *ECD = 3649 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 3650 if (!ECD) continue; // Already issued a diagnostic. 3651 3652 // If the enum value doesn't fit in an int, emit an extension warning. 3653 const llvm::APSInt &InitVal = ECD->getInitVal(); 3654 assert(InitVal.getBitWidth() >= IntWidth && 3655 "Should have promoted value to int"); 3656 if (InitVal.getBitWidth() > IntWidth) { 3657 llvm::APSInt V(InitVal); 3658 V.trunc(IntWidth); 3659 V.extend(InitVal.getBitWidth()); 3660 if (V != InitVal) 3661 Diag(ECD->getLocation(), diag::ext_enum_value_not_int) 3662 << InitVal.toString(10); 3663 } 3664 3665 // Keep track of the size of positive and negative values. 3666 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 3667 NumPositiveBits = std::max(NumPositiveBits, 3668 (unsigned)InitVal.getActiveBits()); 3669 else 3670 NumNegativeBits = std::max(NumNegativeBits, 3671 (unsigned)InitVal.getMinSignedBits()); 3672 3673 // Keep track of whether every enum element has type int (very commmon). 3674 if (AllElementsInt) 3675 AllElementsInt = ECD->getType() == Context.IntTy; 3676 } 3677 3678 // Figure out the type that should be used for this enum. 3679 // FIXME: Support attribute(packed) on enums and -fshort-enums. 3680 QualType BestType; 3681 unsigned BestWidth; 3682 3683 if (NumNegativeBits) { 3684 // If there is a negative value, figure out the smallest integer type (of 3685 // int/long/longlong) that fits. 3686 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 3687 BestType = Context.IntTy; 3688 BestWidth = IntWidth; 3689 } else { 3690 BestWidth = Context.Target.getLongWidth(); 3691 3692 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) 3693 BestType = Context.LongTy; 3694 else { 3695 BestWidth = Context.Target.getLongLongWidth(); 3696 3697 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 3698 Diag(Enum->getLocation(), diag::warn_enum_too_large); 3699 BestType = Context.LongLongTy; 3700 } 3701 } 3702 } else { 3703 // If there is no negative value, figure out which of uint, ulong, ulonglong 3704 // fits. 3705 if (NumPositiveBits <= IntWidth) { 3706 BestType = Context.UnsignedIntTy; 3707 BestWidth = IntWidth; 3708 } else if (NumPositiveBits <= 3709 (BestWidth = Context.Target.getLongWidth())) { 3710 BestType = Context.UnsignedLongTy; 3711 } else { 3712 BestWidth = Context.Target.getLongLongWidth(); 3713 assert(NumPositiveBits <= BestWidth && 3714 "How could an initializer get larger than ULL?"); 3715 BestType = Context.UnsignedLongLongTy; 3716 } 3717 } 3718 3719 // Loop over all of the enumerator constants, changing their types to match 3720 // the type of the enum if needed. 3721 for (unsigned i = 0; i != NumElements; ++i) { 3722 EnumConstantDecl *ECD = 3723 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 3724 if (!ECD) continue; // Already issued a diagnostic. 3725 3726 // Standard C says the enumerators have int type, but we allow, as an 3727 // extension, the enumerators to be larger than int size. If each 3728 // enumerator value fits in an int, type it as an int, otherwise type it the 3729 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 3730 // that X has type 'int', not 'unsigned'. 3731 if (ECD->getType() == Context.IntTy) { 3732 // Make sure the init value is signed. 3733 llvm::APSInt IV = ECD->getInitVal(); 3734 IV.setIsSigned(true); 3735 ECD->setInitVal(IV); 3736 3737 if (getLangOptions().CPlusPlus) 3738 // C++ [dcl.enum]p4: Following the closing brace of an 3739 // enum-specifier, each enumerator has the type of its 3740 // enumeration. 3741 ECD->setType(EnumType); 3742 continue; // Already int type. 3743 } 3744 3745 // Determine whether the value fits into an int. 3746 llvm::APSInt InitVal = ECD->getInitVal(); 3747 bool FitsInInt; 3748 if (InitVal.isUnsigned() || !InitVal.isNegative()) 3749 FitsInInt = InitVal.getActiveBits() < IntWidth; 3750 else 3751 FitsInInt = InitVal.getMinSignedBits() <= IntWidth; 3752 3753 // If it fits into an integer type, force it. Otherwise force it to match 3754 // the enum decl type. 3755 QualType NewTy; 3756 unsigned NewWidth; 3757 bool NewSign; 3758 if (FitsInInt) { 3759 NewTy = Context.IntTy; 3760 NewWidth = IntWidth; 3761 NewSign = true; 3762 } else if (ECD->getType() == BestType) { 3763 // Already the right type! 3764 if (getLangOptions().CPlusPlus) 3765 // C++ [dcl.enum]p4: Following the closing brace of an 3766 // enum-specifier, each enumerator has the type of its 3767 // enumeration. 3768 ECD->setType(EnumType); 3769 continue; 3770 } else { 3771 NewTy = BestType; 3772 NewWidth = BestWidth; 3773 NewSign = BestType->isSignedIntegerType(); 3774 } 3775 3776 // Adjust the APSInt value. 3777 InitVal.extOrTrunc(NewWidth); 3778 InitVal.setIsSigned(NewSign); 3779 ECD->setInitVal(InitVal); 3780 3781 // Adjust the Expr initializer and type. 3782 if (ECD->getInitExpr()) 3783 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(), 3784 /*isLvalue=*/false)); 3785 if (getLangOptions().CPlusPlus) 3786 // C++ [dcl.enum]p4: Following the closing brace of an 3787 // enum-specifier, each enumerator has the type of its 3788 // enumeration. 3789 ECD->setType(EnumType); 3790 else 3791 ECD->setType(NewTy); 3792 } 3793 3794 Enum->completeDefinition(Context, BestType); 3795} 3796 3797Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, 3798 ExprArg expr) { 3799 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release()); 3800 3801 return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString); 3802} 3803 3804 3805void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name, 3806 ExprTy *alignment, SourceLocation PragmaLoc, 3807 SourceLocation LParenLoc, SourceLocation RParenLoc) { 3808 Expr *Alignment = static_cast<Expr *>(alignment); 3809 3810 // If specified then alignment must be a "small" power of two. 3811 unsigned AlignmentVal = 0; 3812 if (Alignment) { 3813 llvm::APSInt Val; 3814 if (!Alignment->isIntegerConstantExpr(Val, Context) || 3815 !Val.isPowerOf2() || 3816 Val.getZExtValue() > 16) { 3817 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment); 3818 delete Alignment; 3819 return; // Ignore 3820 } 3821 3822 AlignmentVal = (unsigned) Val.getZExtValue(); 3823 } 3824 3825 switch (Kind) { 3826 case Action::PPK_Default: // pack([n]) 3827 PackContext.setAlignment(AlignmentVal); 3828 break; 3829 3830 case Action::PPK_Show: // pack(show) 3831 // Show the current alignment, making sure to show the right value 3832 // for the default. 3833 AlignmentVal = PackContext.getAlignment(); 3834 // FIXME: This should come from the target. 3835 if (AlignmentVal == 0) 3836 AlignmentVal = 8; 3837 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal; 3838 break; 3839 3840 case Action::PPK_Push: // pack(push [, id] [, [n]) 3841 PackContext.push(Name); 3842 // Set the new alignment if specified. 3843 if (Alignment) 3844 PackContext.setAlignment(AlignmentVal); 3845 break; 3846 3847 case Action::PPK_Pop: // pack(pop [, id] [, n]) 3848 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack: 3849 // "#pragma pack(pop, identifier, n) is undefined" 3850 if (Alignment && Name) 3851 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment); 3852 3853 // Do the pop. 3854 if (!PackContext.pop(Name)) { 3855 // If a name was specified then failure indicates the name 3856 // wasn't found. Otherwise failure indicates the stack was 3857 // empty. 3858 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed) 3859 << (Name ? "no record matching name" : "stack empty"); 3860 3861 // FIXME: Warn about popping named records as MSVC does. 3862 } else { 3863 // Pop succeeded, set the new alignment if specified. 3864 if (Alignment) 3865 PackContext.setAlignment(AlignmentVal); 3866 } 3867 break; 3868 3869 default: 3870 assert(0 && "Invalid #pragma pack kind."); 3871 } 3872} 3873 3874bool PragmaPackStack::pop(IdentifierInfo *Name) { 3875 if (Stack.empty()) 3876 return false; 3877 3878 // If name is empty just pop top. 3879 if (!Name) { 3880 Alignment = Stack.back().first; 3881 Stack.pop_back(); 3882 return true; 3883 } 3884 3885 // Otherwise, find the named record. 3886 for (unsigned i = Stack.size(); i != 0; ) { 3887 --i; 3888 if (Stack[i].second == Name) { 3889 // Found it, pop up to and including this record. 3890 Alignment = Stack[i].first; 3891 Stack.erase(Stack.begin() + i, Stack.end()); 3892 return true; 3893 } 3894 } 3895 3896 return false; 3897} 3898