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