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