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