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