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