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