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