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