SemaDecl.cpp revision 18fe56863be253a27b940022d27a3101778adaf6
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 // C++ [dcl.init.ref]p1: 632 // A variable declared to be a T&, that is “reference to type T” 633 // (8.3.2), shall be initialized by an object, or function, of 634 // type T or by an object that can be converted into a T. 635 if (DeclType->isReferenceType()) 636 return CheckReferenceInit(Init, DeclType); 637 638 // C99 6.7.8p3: The type of the entity to be initialized shall be an array 639 // of unknown size ("[]") or an object type that is not a variable array type. 640 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType)) 641 return Diag(VAT->getSizeExpr()->getLocStart(), 642 diag::err_variable_object_no_init, 643 VAT->getSizeExpr()->getSourceRange()); 644 645 InitListExpr *InitList = dyn_cast<InitListExpr>(Init); 646 if (!InitList) { 647 // FIXME: Handle wide strings 648 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType)) 649 return CheckStringLiteralInit(strLiteral, DeclType); 650 651 // C99 6.7.8p16. 652 if (DeclType->isArrayType()) 653 return Diag(Init->getLocStart(), 654 diag::err_array_init_list_required, 655 Init->getSourceRange()); 656 657 return CheckSingleInitializer(Init, DeclType); 658 } 659 660 InitListChecker CheckInitList(this, InitList, DeclType); 661 return CheckInitList.HadError(); 662} 663 664Sema::DeclTy * 665Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) { 666 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl); 667 IdentifierInfo *II = D.getIdentifier(); 668 669 // All of these full declarators require an identifier. If it doesn't have 670 // one, the ParsedFreeStandingDeclSpec action should be used. 671 if (II == 0) { 672 Diag(D.getDeclSpec().getSourceRange().getBegin(), 673 diag::err_declarator_need_ident, 674 D.getDeclSpec().getSourceRange(), D.getSourceRange()); 675 return 0; 676 } 677 678 // The scope passed in may not be a decl scope. Zip up the scope tree until 679 // we find one that is. 680 while ((S->getFlags() & Scope::DeclScope) == 0) 681 S = S->getParent(); 682 683 // See if this is a redefinition of a variable in the same scope. 684 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S); 685 ScopedDecl *New; 686 bool InvalidDecl = false; 687 688 // In C++, the previous declaration we find might be a tag type 689 // (class or enum). In this case, the new declaration will hide the 690 // tag type. 691 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 692 PrevDecl = 0; 693 694 QualType R = GetTypeForDeclarator(D, S); 695 assert(!R.isNull() && "GetTypeForDeclarator() returned null type"); 696 697 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 698 // Check that there are no default arguments (C++ only). 699 if (getLangOptions().CPlusPlus) 700 CheckExtraCXXDefaultArguments(D); 701 702 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator); 703 if (!NewTD) return 0; 704 705 // Handle attributes prior to checking for duplicates in MergeVarDecl 706 ProcessDeclAttributes(NewTD, D); 707 // Merge the decl with the existing one if appropriate. If the decl is 708 // in an outer scope, it isn't the same thing. 709 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) { 710 NewTD = MergeTypeDefDecl(NewTD, PrevDecl); 711 if (NewTD == 0) return 0; 712 } 713 New = NewTD; 714 if (S->getFnParent() == 0) { 715 // C99 6.7.7p2: If a typedef name specifies a variably modified type 716 // then it shall have block scope. 717 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) { 718 // FIXME: Diagnostic needs to be fixed. 719 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla); 720 InvalidDecl = true; 721 } 722 } 723 } else if (R.getTypePtr()->isFunctionType()) { 724 FunctionDecl::StorageClass SC = FunctionDecl::None; 725 switch (D.getDeclSpec().getStorageClassSpec()) { 726 default: assert(0 && "Unknown storage class!"); 727 case DeclSpec::SCS_auto: 728 case DeclSpec::SCS_register: 729 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func, 730 R.getAsString()); 731 InvalidDecl = true; 732 break; 733 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break; 734 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break; 735 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break; 736 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break; 737 } 738 739 bool isInline = D.getDeclSpec().isInlineSpecified(); 740 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 741 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 742 743 FunctionDecl *NewFD; 744 if (isCurrentClassName(*II, S)) { 745 // This is a C++ constructor declaration. 746 assert(D.getContext() == Declarator::MemberContext && 747 "Constructors can only be declared in a member context"); 748 749 // C++ [class.ctor]p3: 750 // A constructor shall not be virtual (10.3) or static (9.4). A 751 // constructor can be invoked for a const, volatile or const 752 // volatile object. A constructor shall not be declared const, 753 // volatile, or const volatile (9.3.2). 754 if (isVirtual) { 755 Diag(D.getIdentifierLoc(), 756 diag::err_constructor_cannot_be, 757 "virtual", 758 SourceRange(D.getDeclSpec().getVirtualSpecLoc()), 759 SourceRange(D.getIdentifierLoc())); 760 isVirtual = false; 761 } 762 if (SC == FunctionDecl::Static) { 763 Diag(D.getIdentifierLoc(), 764 diag::err_constructor_cannot_be, 765 "static", 766 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()), 767 SourceRange(D.getIdentifierLoc())); 768 isVirtual = false; 769 } 770 if (D.getDeclSpec().hasTypeSpecifier()) { 771 // Constructors don't have return types, but the parser will 772 // happily parse something like: 773 // 774 // class X { 775 // float X(float); 776 // }; 777 // 778 // The return type will be eliminated later. 779 Diag(D.getIdentifierLoc(), 780 diag::err_constructor_return_type, 781 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()), 782 SourceRange(D.getIdentifierLoc())); 783 } 784 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) { 785 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 786 if (FTI.TypeQuals & QualType::Const) 787 Diag(D.getIdentifierLoc(), 788 diag::err_invalid_qualified_constructor, 789 "const", 790 SourceRange(D.getIdentifierLoc())); 791 if (FTI.TypeQuals & QualType::Volatile) 792 Diag(D.getIdentifierLoc(), 793 diag::err_invalid_qualified_constructor, 794 "volatile", 795 SourceRange(D.getIdentifierLoc())); 796 if (FTI.TypeQuals & QualType::Restrict) 797 Diag(D.getIdentifierLoc(), 798 diag::err_invalid_qualified_constructor, 799 "restrict", 800 SourceRange(D.getIdentifierLoc())); 801 } 802 803 // Rebuild the function type "R" without any type qualifiers (in 804 // case any of the errors above fired) and with "void" as the 805 // return type, since constructors don't have return types. We 806 // *always* have to do this, because GetTypeForDeclarator will 807 // put in a result type of "int" when none was specified. 808 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto(); 809 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(), 810 Proto->getNumArgs(), 811 Proto->isVariadic(), 812 0); 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 } else if (D.getContext() == Declarator::MemberContext) { 822 // This is a C++ method declaration. 823 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext), 824 D.getIdentifierLoc(), II, R, 825 (SC == FunctionDecl::Static), isInline, 826 LastDeclarator); 827 } else { 828 NewFD = FunctionDecl::Create(Context, CurContext, 829 D.getIdentifierLoc(), 830 II, R, SC, isInline, LastDeclarator, 831 // FIXME: Move to DeclGroup... 832 D.getDeclSpec().getSourceRange().getBegin()); 833 } 834 // Handle attributes. 835 ProcessDeclAttributes(NewFD, D); 836 837 // Handle GNU asm-label extension (encoded as an attribute). 838 if (Expr *E = (Expr*) D.getAsmLabel()) { 839 // The parser guarantees this is a string. 840 StringLiteral *SE = cast<StringLiteral>(E); 841 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(), 842 SE->getByteLength()))); 843 } 844 845 // Copy the parameter declarations from the declarator D to 846 // the function declaration NewFD, if they are available. 847 if (D.getNumTypeObjects() > 0) { 848 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 849 850 // Create Decl objects for each parameter, adding them to the 851 // FunctionDecl. 852 llvm::SmallVector<ParmVarDecl*, 16> Params; 853 854 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 855 // function that takes no arguments, not a function that takes a 856 // single void argument. 857 // We let through "const void" here because Sema::GetTypeForDeclarator 858 // already checks for that case. 859 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 860 FTI.ArgInfo[0].Param && 861 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 862 // empty arg list, don't push any params. 863 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param; 864 865 // In C++, the empty parameter-type-list must be spelled "void"; a 866 // typedef of void is not permitted. 867 if (getLangOptions().CPlusPlus && 868 Param->getType().getUnqualifiedType() != Context.VoidTy) { 869 Diag(Param->getLocation(), diag::ext_param_typedef_of_void); 870 } 871 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 872 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 873 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param); 874 } 875 876 NewFD->setParams(&Params[0], Params.size()); 877 } else if (R->getAsTypedefType()) { 878 // When we're declaring a function with a typedef, as in the 879 // following example, we'll need to synthesize (unnamed) 880 // parameters for use in the declaration. 881 // 882 // @code 883 // typedef void fn(int); 884 // fn f; 885 // @endcode 886 const FunctionTypeProto *FT = R->getAsFunctionTypeProto(); 887 if (!FT) { 888 // This is a typedef of a function with no prototype, so we 889 // don't need to do anything. 890 } else if ((FT->getNumArgs() == 0) || 891 (FT->getNumArgs() == 1 && !FT->isVariadic() && 892 FT->getArgType(0)->isVoidType())) { 893 // This is a zero-argument function. We don't need to do anything. 894 } else { 895 // Synthesize a parameter for each argument type. 896 llvm::SmallVector<ParmVarDecl*, 16> Params; 897 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin(); 898 ArgType != FT->arg_type_end(); ++ArgType) { 899 Params.push_back(ParmVarDecl::Create(Context, CurContext, 900 SourceLocation(), 0, 901 *ArgType, VarDecl::None, 902 0, 0)); 903 } 904 905 NewFD->setParams(&Params[0], Params.size()); 906 } 907 } 908 909 // C++ constructors are handled by a separate routine, since they 910 // don't require any declaration merging (C++ [class.mfct]p2) and 911 // they aren't ever pushed into scope, because they can't be found 912 // by name lookup anyway (C++ [class.ctor]p2). 913 if (CXXConstructorDecl *ConDecl = dyn_cast<CXXConstructorDecl>(NewFD)) 914 return ActOnConstructorDeclarator(ConDecl); 915 916 // Merge the decl with the existing one if appropriate. Since C functions 917 // are in a flat namespace, make sure we consider decls in outer scopes. 918 if (PrevDecl && 919 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, CurContext, S))) { 920 bool Redeclaration = false; 921 922 // If C++, determine whether NewFD is an overload of PrevDecl or 923 // a declaration that requires merging. If it's an overload, 924 // there's no more work to do here; we'll just add the new 925 // function to the scope. 926 OverloadedFunctionDecl::function_iterator MatchedDecl; 927 if (!getLangOptions().CPlusPlus || 928 !IsOverload(NewFD, PrevDecl, MatchedDecl)) { 929 Decl *OldDecl = PrevDecl; 930 931 // If PrevDecl was an overloaded function, extract the 932 // FunctionDecl that matched. 933 if (isa<OverloadedFunctionDecl>(PrevDecl)) 934 OldDecl = *MatchedDecl; 935 936 // NewFD and PrevDecl represent declarations that need to be 937 // merged. 938 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration); 939 940 if (NewFD == 0) return 0; 941 if (Redeclaration) { 942 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 943 944 if (OldDecl == PrevDecl) { 945 // Remove the name binding for the previous 946 // declaration. We'll add the binding back later, but then 947 // it will refer to the new declaration (which will 948 // contain more information). 949 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl)); 950 } else { 951 // We need to update the OverloadedFunctionDecl with the 952 // latest declaration of this function, so that name 953 // lookup will always refer to the latest declaration of 954 // this function. 955 *MatchedDecl = NewFD; 956 957 // Add the redeclaration to the current scope, since we'll 958 // be skipping PushOnScopeChains. 959 S->AddDecl(NewFD); 960 961 return NewFD; 962 } 963 } 964 } 965 } 966 New = NewFD; 967 968 // In C++, check default arguments now that we have merged decls. 969 if (getLangOptions().CPlusPlus) 970 CheckCXXDefaultArguments(NewFD); 971 } else { 972 // Check that there are no default arguments (C++ only). 973 if (getLangOptions().CPlusPlus) 974 CheckExtraCXXDefaultArguments(D); 975 976 if (R.getTypePtr()->isObjCInterfaceType()) { 977 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object, 978 D.getIdentifier()->getName()); 979 InvalidDecl = true; 980 } 981 982 VarDecl *NewVD; 983 VarDecl::StorageClass SC; 984 switch (D.getDeclSpec().getStorageClassSpec()) { 985 default: assert(0 && "Unknown storage class!"); 986 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 987 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 988 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 989 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 990 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 991 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 992 } 993 if (D.getContext() == Declarator::MemberContext) { 994 assert(SC == VarDecl::Static && "Invalid storage class for member!"); 995 // This is a static data member for a C++ class. 996 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext), 997 D.getIdentifierLoc(), II, 998 R, LastDeclarator); 999 } else { 1000 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified(); 1001 if (S->getFnParent() == 0) { 1002 // C99 6.9p2: The storage-class specifiers auto and register shall not 1003 // appear in the declaration specifiers in an external declaration. 1004 if (SC == VarDecl::Auto || SC == VarDecl::Register) { 1005 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope, 1006 R.getAsString()); 1007 InvalidDecl = true; 1008 } 1009 } 1010 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(), 1011 II, R, SC, LastDeclarator, 1012 // FIXME: Move to DeclGroup... 1013 D.getDeclSpec().getSourceRange().getBegin()); 1014 NewVD->setThreadSpecified(ThreadSpecified); 1015 } 1016 // Handle attributes prior to checking for duplicates in MergeVarDecl 1017 ProcessDeclAttributes(NewVD, D); 1018 1019 // Handle GNU asm-label extension (encoded as an attribute). 1020 if (Expr *E = (Expr*) D.getAsmLabel()) { 1021 // The parser guarantees this is a string. 1022 StringLiteral *SE = cast<StringLiteral>(E); 1023 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(), 1024 SE->getByteLength()))); 1025 } 1026 1027 // Emit an error if an address space was applied to decl with local storage. 1028 // This includes arrays of objects with address space qualifiers, but not 1029 // automatic variables that point to other address spaces. 1030 // ISO/IEC TR 18037 S5.1.2 1031 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) { 1032 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl); 1033 InvalidDecl = true; 1034 } 1035 // Merge the decl with the existing one if appropriate. If the decl is 1036 // in an outer scope, it isn't the same thing. 1037 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) { 1038 NewVD = MergeVarDecl(NewVD, PrevDecl); 1039 if (NewVD == 0) return 0; 1040 } 1041 New = NewVD; 1042 } 1043 1044 // If this has an identifier, add it to the scope stack. 1045 if (II) 1046 PushOnScopeChains(New, S); 1047 // If any semantic error occurred, mark the decl as invalid. 1048 if (D.getInvalidType() || InvalidDecl) 1049 New->setInvalidDecl(); 1050 1051 return New; 1052} 1053 1054void Sema::InitializerElementNotConstant(const Expr *Init) { 1055 Diag(Init->getExprLoc(), 1056 diag::err_init_element_not_constant, Init->getSourceRange()); 1057} 1058 1059bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) { 1060 switch (Init->getStmtClass()) { 1061 default: 1062 InitializerElementNotConstant(Init); 1063 return true; 1064 case Expr::ParenExprClass: { 1065 const ParenExpr* PE = cast<ParenExpr>(Init); 1066 return CheckAddressConstantExpressionLValue(PE->getSubExpr()); 1067 } 1068 case Expr::CompoundLiteralExprClass: 1069 return cast<CompoundLiteralExpr>(Init)->isFileScope(); 1070 case Expr::DeclRefExprClass: { 1071 const Decl *D = cast<DeclRefExpr>(Init)->getDecl(); 1072 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1073 if (VD->hasGlobalStorage()) 1074 return false; 1075 InitializerElementNotConstant(Init); 1076 return true; 1077 } 1078 if (isa<FunctionDecl>(D)) 1079 return false; 1080 InitializerElementNotConstant(Init); 1081 return true; 1082 } 1083 case Expr::MemberExprClass: { 1084 const MemberExpr *M = cast<MemberExpr>(Init); 1085 if (M->isArrow()) 1086 return CheckAddressConstantExpression(M->getBase()); 1087 return CheckAddressConstantExpressionLValue(M->getBase()); 1088 } 1089 case Expr::ArraySubscriptExprClass: { 1090 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)? 1091 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init); 1092 return CheckAddressConstantExpression(ASE->getBase()) || 1093 CheckArithmeticConstantExpression(ASE->getIdx()); 1094 } 1095 case Expr::StringLiteralClass: 1096 case Expr::PredefinedExprClass: 1097 return false; 1098 case Expr::UnaryOperatorClass: { 1099 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1100 1101 // C99 6.6p9 1102 if (Exp->getOpcode() == UnaryOperator::Deref) 1103 return CheckAddressConstantExpression(Exp->getSubExpr()); 1104 1105 InitializerElementNotConstant(Init); 1106 return true; 1107 } 1108 } 1109} 1110 1111bool Sema::CheckAddressConstantExpression(const Expr* Init) { 1112 switch (Init->getStmtClass()) { 1113 default: 1114 InitializerElementNotConstant(Init); 1115 return true; 1116 case Expr::ParenExprClass: 1117 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr()); 1118 case Expr::StringLiteralClass: 1119 case Expr::ObjCStringLiteralClass: 1120 return false; 1121 case Expr::CallExprClass: 1122 // __builtin___CFStringMakeConstantString is a valid constant l-value. 1123 if (cast<CallExpr>(Init)->isBuiltinCall() == 1124 Builtin::BI__builtin___CFStringMakeConstantString) 1125 return false; 1126 1127 InitializerElementNotConstant(Init); 1128 return true; 1129 1130 case Expr::UnaryOperatorClass: { 1131 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1132 1133 // C99 6.6p9 1134 if (Exp->getOpcode() == UnaryOperator::AddrOf) 1135 return CheckAddressConstantExpressionLValue(Exp->getSubExpr()); 1136 1137 if (Exp->getOpcode() == UnaryOperator::Extension) 1138 return CheckAddressConstantExpression(Exp->getSubExpr()); 1139 1140 InitializerElementNotConstant(Init); 1141 return true; 1142 } 1143 case Expr::BinaryOperatorClass: { 1144 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"? 1145 const BinaryOperator *Exp = cast<BinaryOperator>(Init); 1146 1147 Expr *PExp = Exp->getLHS(); 1148 Expr *IExp = Exp->getRHS(); 1149 if (IExp->getType()->isPointerType()) 1150 std::swap(PExp, IExp); 1151 1152 // FIXME: Should we pedwarn if IExp isn't an integer constant expression? 1153 return CheckAddressConstantExpression(PExp) || 1154 CheckArithmeticConstantExpression(IExp); 1155 } 1156 case Expr::ImplicitCastExprClass: 1157 case Expr::CStyleCastExprClass: { 1158 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr(); 1159 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) { 1160 // Check for implicit promotion 1161 if (SubExpr->getType()->isFunctionType() || 1162 SubExpr->getType()->isArrayType()) 1163 return CheckAddressConstantExpressionLValue(SubExpr); 1164 } 1165 1166 // Check for pointer->pointer cast 1167 if (SubExpr->getType()->isPointerType()) 1168 return CheckAddressConstantExpression(SubExpr); 1169 1170 if (SubExpr->getType()->isIntegralType()) { 1171 // Check for the special-case of a pointer->int->pointer cast; 1172 // this isn't standard, but some code requires it. See 1173 // PR2720 for an example. 1174 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) { 1175 if (SubCast->getSubExpr()->getType()->isPointerType()) { 1176 unsigned IntWidth = Context.getIntWidth(SubCast->getType()); 1177 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy); 1178 if (IntWidth >= PointerWidth) { 1179 return CheckAddressConstantExpression(SubCast->getSubExpr()); 1180 } 1181 } 1182 } 1183 } 1184 if (SubExpr->getType()->isArithmeticType()) { 1185 return CheckArithmeticConstantExpression(SubExpr); 1186 } 1187 1188 InitializerElementNotConstant(Init); 1189 return true; 1190 } 1191 case Expr::ConditionalOperatorClass: { 1192 // FIXME: Should we pedwarn here? 1193 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init); 1194 if (!Exp->getCond()->getType()->isArithmeticType()) { 1195 InitializerElementNotConstant(Init); 1196 return true; 1197 } 1198 if (CheckArithmeticConstantExpression(Exp->getCond())) 1199 return true; 1200 if (Exp->getLHS() && 1201 CheckAddressConstantExpression(Exp->getLHS())) 1202 return true; 1203 return CheckAddressConstantExpression(Exp->getRHS()); 1204 } 1205 case Expr::AddrLabelExprClass: 1206 return false; 1207 } 1208} 1209 1210static const Expr* FindExpressionBaseAddress(const Expr* E); 1211 1212static const Expr* FindExpressionBaseAddressLValue(const Expr* E) { 1213 switch (E->getStmtClass()) { 1214 default: 1215 return E; 1216 case Expr::ParenExprClass: { 1217 const ParenExpr* PE = cast<ParenExpr>(E); 1218 return FindExpressionBaseAddressLValue(PE->getSubExpr()); 1219 } 1220 case Expr::MemberExprClass: { 1221 const MemberExpr *M = cast<MemberExpr>(E); 1222 if (M->isArrow()) 1223 return FindExpressionBaseAddress(M->getBase()); 1224 return FindExpressionBaseAddressLValue(M->getBase()); 1225 } 1226 case Expr::ArraySubscriptExprClass: { 1227 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E); 1228 return FindExpressionBaseAddress(ASE->getBase()); 1229 } 1230 case Expr::UnaryOperatorClass: { 1231 const UnaryOperator *Exp = cast<UnaryOperator>(E); 1232 1233 if (Exp->getOpcode() == UnaryOperator::Deref) 1234 return FindExpressionBaseAddress(Exp->getSubExpr()); 1235 1236 return E; 1237 } 1238 } 1239} 1240 1241static const Expr* FindExpressionBaseAddress(const Expr* E) { 1242 switch (E->getStmtClass()) { 1243 default: 1244 return E; 1245 case Expr::ParenExprClass: { 1246 const ParenExpr* PE = cast<ParenExpr>(E); 1247 return FindExpressionBaseAddress(PE->getSubExpr()); 1248 } 1249 case Expr::UnaryOperatorClass: { 1250 const UnaryOperator *Exp = cast<UnaryOperator>(E); 1251 1252 // C99 6.6p9 1253 if (Exp->getOpcode() == UnaryOperator::AddrOf) 1254 return FindExpressionBaseAddressLValue(Exp->getSubExpr()); 1255 1256 if (Exp->getOpcode() == UnaryOperator::Extension) 1257 return FindExpressionBaseAddress(Exp->getSubExpr()); 1258 1259 return E; 1260 } 1261 case Expr::BinaryOperatorClass: { 1262 const BinaryOperator *Exp = cast<BinaryOperator>(E); 1263 1264 Expr *PExp = Exp->getLHS(); 1265 Expr *IExp = Exp->getRHS(); 1266 if (IExp->getType()->isPointerType()) 1267 std::swap(PExp, IExp); 1268 1269 return FindExpressionBaseAddress(PExp); 1270 } 1271 case Expr::ImplicitCastExprClass: { 1272 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr(); 1273 1274 // Check for implicit promotion 1275 if (SubExpr->getType()->isFunctionType() || 1276 SubExpr->getType()->isArrayType()) 1277 return FindExpressionBaseAddressLValue(SubExpr); 1278 1279 // Check for pointer->pointer cast 1280 if (SubExpr->getType()->isPointerType()) 1281 return FindExpressionBaseAddress(SubExpr); 1282 1283 // We assume that we have an arithmetic expression here; 1284 // if we don't, we'll figure it out later 1285 return 0; 1286 } 1287 case Expr::CStyleCastExprClass: { 1288 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 1289 1290 // Check for pointer->pointer cast 1291 if (SubExpr->getType()->isPointerType()) 1292 return FindExpressionBaseAddress(SubExpr); 1293 1294 // We assume that we have an arithmetic expression here; 1295 // if we don't, we'll figure it out later 1296 return 0; 1297 } 1298 } 1299} 1300 1301bool Sema::CheckArithmeticConstantExpression(const Expr* Init) { 1302 switch (Init->getStmtClass()) { 1303 default: 1304 InitializerElementNotConstant(Init); 1305 return true; 1306 case Expr::ParenExprClass: { 1307 const ParenExpr* PE = cast<ParenExpr>(Init); 1308 return CheckArithmeticConstantExpression(PE->getSubExpr()); 1309 } 1310 case Expr::FloatingLiteralClass: 1311 case Expr::IntegerLiteralClass: 1312 case Expr::CharacterLiteralClass: 1313 case Expr::ImaginaryLiteralClass: 1314 case Expr::TypesCompatibleExprClass: 1315 case Expr::CXXBoolLiteralExprClass: 1316 return false; 1317 case Expr::CallExprClass: { 1318 const CallExpr *CE = cast<CallExpr>(Init); 1319 1320 // Allow any constant foldable calls to builtins. 1321 if (CE->isBuiltinCall() && CE->isEvaluatable(Context)) 1322 return false; 1323 1324 InitializerElementNotConstant(Init); 1325 return true; 1326 } 1327 case Expr::DeclRefExprClass: { 1328 const Decl *D = cast<DeclRefExpr>(Init)->getDecl(); 1329 if (isa<EnumConstantDecl>(D)) 1330 return false; 1331 InitializerElementNotConstant(Init); 1332 return true; 1333 } 1334 case Expr::CompoundLiteralExprClass: 1335 // Allow "(vector type){2,4}"; normal C constraints don't allow this, 1336 // but vectors are allowed to be magic. 1337 if (Init->getType()->isVectorType()) 1338 return false; 1339 InitializerElementNotConstant(Init); 1340 return true; 1341 case Expr::UnaryOperatorClass: { 1342 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1343 1344 switch (Exp->getOpcode()) { 1345 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 1346 // See C99 6.6p3. 1347 default: 1348 InitializerElementNotConstant(Init); 1349 return true; 1350 case UnaryOperator::SizeOf: 1351 case UnaryOperator::AlignOf: 1352 case UnaryOperator::OffsetOf: 1353 // sizeof(E) is a constantexpr if and only if E is not evaluted. 1354 // See C99 6.5.3.4p2 and 6.6p3. 1355 if (Exp->getSubExpr()->getType()->isConstantSizeType()) 1356 return false; 1357 InitializerElementNotConstant(Init); 1358 return true; 1359 case UnaryOperator::Extension: 1360 case UnaryOperator::LNot: 1361 case UnaryOperator::Plus: 1362 case UnaryOperator::Minus: 1363 case UnaryOperator::Not: 1364 return CheckArithmeticConstantExpression(Exp->getSubExpr()); 1365 } 1366 } 1367 case Expr::SizeOfAlignOfTypeExprClass: { 1368 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init); 1369 // Special check for void types, which are allowed as an extension 1370 if (Exp->getArgumentType()->isVoidType()) 1371 return false; 1372 // alignof always evaluates to a constant. 1373 // FIXME: is sizeof(int[3.0]) a constant expression? 1374 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) { 1375 InitializerElementNotConstant(Init); 1376 return true; 1377 } 1378 return false; 1379 } 1380 case Expr::BinaryOperatorClass: { 1381 const BinaryOperator *Exp = cast<BinaryOperator>(Init); 1382 1383 if (Exp->getLHS()->getType()->isArithmeticType() && 1384 Exp->getRHS()->getType()->isArithmeticType()) { 1385 return CheckArithmeticConstantExpression(Exp->getLHS()) || 1386 CheckArithmeticConstantExpression(Exp->getRHS()); 1387 } 1388 1389 if (Exp->getLHS()->getType()->isPointerType() && 1390 Exp->getRHS()->getType()->isPointerType()) { 1391 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS()); 1392 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS()); 1393 1394 // Only allow a null (constant integer) base; we could 1395 // allow some additional cases if necessary, but this 1396 // is sufficient to cover offsetof-like constructs. 1397 if (!LHSBase && !RHSBase) { 1398 return CheckAddressConstantExpression(Exp->getLHS()) || 1399 CheckAddressConstantExpression(Exp->getRHS()); 1400 } 1401 } 1402 1403 InitializerElementNotConstant(Init); 1404 return true; 1405 } 1406 case Expr::ImplicitCastExprClass: 1407 case Expr::CStyleCastExprClass: { 1408 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr(); 1409 if (SubExpr->getType()->isArithmeticType()) 1410 return CheckArithmeticConstantExpression(SubExpr); 1411 1412 if (SubExpr->getType()->isPointerType()) { 1413 const Expr* Base = FindExpressionBaseAddress(SubExpr); 1414 // If the pointer has a null base, this is an offsetof-like construct 1415 if (!Base) 1416 return CheckAddressConstantExpression(SubExpr); 1417 } 1418 1419 InitializerElementNotConstant(Init); 1420 return true; 1421 } 1422 case Expr::ConditionalOperatorClass: { 1423 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init); 1424 1425 // If GNU extensions are disabled, we require all operands to be arithmetic 1426 // constant expressions. 1427 if (getLangOptions().NoExtensions) { 1428 return CheckArithmeticConstantExpression(Exp->getCond()) || 1429 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) || 1430 CheckArithmeticConstantExpression(Exp->getRHS()); 1431 } 1432 1433 // Otherwise, we have to emulate some of the behavior of fold here. 1434 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant 1435 // because it can constant fold things away. To retain compatibility with 1436 // GCC code, we see if we can fold the condition to a constant (which we 1437 // should always be able to do in theory). If so, we only require the 1438 // specified arm of the conditional to be a constant. This is a horrible 1439 // hack, but is require by real world code that uses __builtin_constant_p. 1440 APValue Val; 1441 if (!Exp->getCond()->tryEvaluate(Val, Context)) { 1442 // If the tryEvaluate couldn't fold it, CheckArithmeticConstantExpression 1443 // won't be able to either. Use it to emit the diagnostic though. 1444 bool Res = CheckArithmeticConstantExpression(Exp->getCond()); 1445 assert(Res && "tryEvaluate couldn't evaluate this constant?"); 1446 return Res; 1447 } 1448 1449 // Verify that the side following the condition is also a constant. 1450 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS(); 1451 if (Val.getInt() == 0) 1452 std::swap(TrueSide, FalseSide); 1453 1454 if (TrueSide && CheckArithmeticConstantExpression(TrueSide)) 1455 return true; 1456 1457 // Okay, the evaluated side evaluates to a constant, so we accept this. 1458 // Check to see if the other side is obviously not a constant. If so, 1459 // emit a warning that this is a GNU extension. 1460 if (FalseSide && !FalseSide->isEvaluatable(Context)) 1461 Diag(Init->getExprLoc(), 1462 diag::ext_typecheck_expression_not_constant_but_accepted, 1463 FalseSide->getSourceRange()); 1464 return false; 1465 } 1466 } 1467} 1468 1469bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 1470 Init = Init->IgnoreParens(); 1471 1472 // Look through CXXDefaultArgExprs; they have no meaning in this context. 1473 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init)) 1474 return CheckForConstantInitializer(DAE->getExpr(), DclT); 1475 1476 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init)) 1477 return CheckForConstantInitializer(e->getInitializer(), DclT); 1478 1479 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) { 1480 unsigned numInits = Exp->getNumInits(); 1481 for (unsigned i = 0; i < numInits; i++) { 1482 // FIXME: Need to get the type of the declaration for C++, 1483 // because it could be a reference? 1484 if (CheckForConstantInitializer(Exp->getInit(i), 1485 Exp->getInit(i)->getType())) 1486 return true; 1487 } 1488 return false; 1489 } 1490 1491 if (Init->isNullPointerConstant(Context)) 1492 return false; 1493 if (Init->getType()->isArithmeticType()) { 1494 QualType InitTy = Context.getCanonicalType(Init->getType()) 1495 .getUnqualifiedType(); 1496 if (InitTy == Context.BoolTy) { 1497 // Special handling for pointers implicitly cast to bool; 1498 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level. 1499 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) { 1500 Expr* SubE = ICE->getSubExpr(); 1501 if (SubE->getType()->isPointerType() || 1502 SubE->getType()->isArrayType() || 1503 SubE->getType()->isFunctionType()) { 1504 return CheckAddressConstantExpression(Init); 1505 } 1506 } 1507 } else if (InitTy->isIntegralType()) { 1508 Expr* SubE = 0; 1509 if (CastExpr* CE = dyn_cast<CastExpr>(Init)) 1510 SubE = CE->getSubExpr(); 1511 // Special check for pointer cast to int; we allow as an extension 1512 // an address constant cast to an integer if the integer 1513 // is of an appropriate width (this sort of code is apparently used 1514 // in some places). 1515 // FIXME: Add pedwarn? 1516 // FIXME: Don't allow bitfields here! Need the FieldDecl for that. 1517 if (SubE && (SubE->getType()->isPointerType() || 1518 SubE->getType()->isArrayType() || 1519 SubE->getType()->isFunctionType())) { 1520 unsigned IntWidth = Context.getTypeSize(Init->getType()); 1521 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy); 1522 if (IntWidth >= PointerWidth) 1523 return CheckAddressConstantExpression(Init); 1524 } 1525 } 1526 1527 return CheckArithmeticConstantExpression(Init); 1528 } 1529 1530 if (Init->getType()->isPointerType()) 1531 return CheckAddressConstantExpression(Init); 1532 1533 // An array type at the top level that isn't an init-list must 1534 // be a string literal 1535 if (Init->getType()->isArrayType()) 1536 return false; 1537 1538 if (Init->getType()->isFunctionType()) 1539 return false; 1540 1541 // Allow block exprs at top level. 1542 if (Init->getType()->isBlockPointerType()) 1543 return false; 1544 1545 InitializerElementNotConstant(Init); 1546 return true; 1547} 1548 1549void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) { 1550 Decl *RealDecl = static_cast<Decl *>(dcl); 1551 Expr *Init = static_cast<Expr *>(init); 1552 assert(Init && "missing initializer"); 1553 1554 // If there is no declaration, there was an error parsing it. Just ignore 1555 // the initializer. 1556 if (RealDecl == 0) { 1557 delete Init; 1558 return; 1559 } 1560 1561 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 1562 if (!VDecl) { 1563 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(), 1564 diag::err_illegal_initializer); 1565 RealDecl->setInvalidDecl(); 1566 return; 1567 } 1568 // Get the decls type and save a reference for later, since 1569 // CheckInitializerTypes may change it. 1570 QualType DclT = VDecl->getType(), SavT = DclT; 1571 if (VDecl->isBlockVarDecl()) { 1572 VarDecl::StorageClass SC = VDecl->getStorageClass(); 1573 if (SC == VarDecl::Extern) { // C99 6.7.8p5 1574 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 1575 VDecl->setInvalidDecl(); 1576 } else if (!VDecl->isInvalidDecl()) { 1577 if (CheckInitializerTypes(Init, DclT)) 1578 VDecl->setInvalidDecl(); 1579 1580 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 1581 if (!getLangOptions().CPlusPlus) { 1582 if (SC == VarDecl::Static) // C99 6.7.8p4. 1583 CheckForConstantInitializer(Init, DclT); 1584 } 1585 } 1586 } else if (VDecl->isFileVarDecl()) { 1587 if (VDecl->getStorageClass() == VarDecl::Extern) 1588 Diag(VDecl->getLocation(), diag::warn_extern_init); 1589 if (!VDecl->isInvalidDecl()) 1590 if (CheckInitializerTypes(Init, DclT)) 1591 VDecl->setInvalidDecl(); 1592 1593 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 1594 if (!getLangOptions().CPlusPlus) { 1595 // C99 6.7.8p4. All file scoped initializers need to be constant. 1596 CheckForConstantInitializer(Init, DclT); 1597 } 1598 } 1599 // If the type changed, it means we had an incomplete type that was 1600 // completed by the initializer. For example: 1601 // int ary[] = { 1, 3, 5 }; 1602 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 1603 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 1604 VDecl->setType(DclT); 1605 Init->setType(DclT); 1606 } 1607 1608 // Attach the initializer to the decl. 1609 VDecl->setInit(Init); 1610 return; 1611} 1612 1613void Sema::ActOnUninitializedDecl(DeclTy *dcl) { 1614 Decl *RealDecl = static_cast<Decl *>(dcl); 1615 1616 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 1617 QualType Type = Var->getType(); 1618 // C++ [dcl.init.ref]p3: 1619 // The initializer can be omitted for a reference only in a 1620 // parameter declaration (8.3.5), in the declaration of a 1621 // function return type, in the declaration of a class member 1622 // within its class declaration (9.2), and where the extern 1623 // specifier is explicitly used. 1624 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) { 1625 Diag(Var->getLocation(), 1626 diag::err_reference_var_requires_init, 1627 Var->getName(), 1628 SourceRange(Var->getLocation(), Var->getLocation())); 1629 Var->setInvalidDecl(); 1630 return; 1631 } 1632 1633 // C++ [dcl.init]p9: 1634 // 1635 // If no initializer is specified for an object, and the object 1636 // is of (possibly cv-qualified) non-POD class type (or array 1637 // thereof), the object shall be default-initialized; if the 1638 // object is of const-qualified type, the underlying class type 1639 // shall have a user-declared default constructor. 1640 if (getLangOptions().CPlusPlus) { 1641 QualType InitType = Type; 1642 if (const ArrayType *Array = Context.getAsArrayType(Type)) 1643 InitType = Array->getElementType(); 1644 if (InitType->isRecordType()) { 1645 CXXConstructorDecl *Constructor 1646 = PerformDirectInitForClassType(InitType, 0, 0, Var->getLocation(), 1647 SourceRange(Var->getLocation(), 1648 Var->getLocation()), 1649 Var->getName(), 1650 /*HasInitializer=*/false); 1651 if (!Constructor) 1652 Var->setInvalidDecl(); 1653 } 1654 } 1655 1656#if 0 1657 // FIXME: Temporarily disabled because we are not properly parsing 1658 // linkage specifications on declarations, e.g., 1659 // 1660 // extern "C" const CGPoint CGPointerZero; 1661 // 1662 // C++ [dcl.init]p9: 1663 // 1664 // If no initializer is specified for an object, and the 1665 // object is of (possibly cv-qualified) non-POD class type (or 1666 // array thereof), the object shall be default-initialized; if 1667 // the object is of const-qualified type, the underlying class 1668 // type shall have a user-declared default 1669 // constructor. Otherwise, if no initializer is specified for 1670 // an object, the object and its subobjects, if any, have an 1671 // indeterminate initial value; if the object or any of its 1672 // subobjects are of const-qualified type, the program is 1673 // ill-formed. 1674 // 1675 // This isn't technically an error in C, so we don't diagnose it. 1676 // 1677 // FIXME: Actually perform the POD/user-defined default 1678 // constructor check. 1679 if (getLangOptions().CPlusPlus && 1680 Context.getCanonicalType(Type).isConstQualified() && 1681 Var->getStorageClass() != VarDecl::Extern) 1682 Diag(Var->getLocation(), 1683 diag::err_const_var_requires_init, 1684 Var->getName(), 1685 SourceRange(Var->getLocation(), Var->getLocation())); 1686#endif 1687 } 1688} 1689 1690/// The declarators are chained together backwards, reverse the list. 1691Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) { 1692 // Often we have single declarators, handle them quickly. 1693 Decl *GroupDecl = static_cast<Decl*>(group); 1694 if (GroupDecl == 0) 1695 return 0; 1696 1697 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl); 1698 ScopedDecl *NewGroup = 0; 1699 if (Group->getNextDeclarator() == 0) 1700 NewGroup = Group; 1701 else { // reverse the list. 1702 while (Group) { 1703 ScopedDecl *Next = Group->getNextDeclarator(); 1704 Group->setNextDeclarator(NewGroup); 1705 NewGroup = Group; 1706 Group = Next; 1707 } 1708 } 1709 // Perform semantic analysis that depends on having fully processed both 1710 // the declarator and initializer. 1711 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) { 1712 VarDecl *IDecl = dyn_cast<VarDecl>(ID); 1713 if (!IDecl) 1714 continue; 1715 QualType T = IDecl->getType(); 1716 1717 // C99 6.7.5.2p2: If an identifier is declared to be an object with 1718 // static storage duration, it shall not have a variable length array. 1719 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) && 1720 IDecl->getStorageClass() == VarDecl::Static) { 1721 if (T->isVariableArrayType()) { 1722 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla); 1723 IDecl->setInvalidDecl(); 1724 } 1725 } 1726 // Block scope. C99 6.7p7: If an identifier for an object is declared with 1727 // no linkage (C99 6.2.2p6), the type for the object shall be complete... 1728 if (IDecl->isBlockVarDecl() && 1729 IDecl->getStorageClass() != VarDecl::Extern) { 1730 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) { 1731 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type, 1732 T.getAsString()); 1733 IDecl->setInvalidDecl(); 1734 } 1735 } 1736 // File scope. C99 6.9.2p2: A declaration of an identifier for and 1737 // object that has file scope without an initializer, and without a 1738 // storage-class specifier or with the storage-class specifier "static", 1739 // constitutes a tentative definition. Note: A tentative definition with 1740 // external linkage is valid (C99 6.2.2p5). 1741 if (isTentativeDefinition(IDecl)) { 1742 if (T->isIncompleteArrayType()) { 1743 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete 1744 // array to be completed. Don't issue a diagnostic. 1745 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) { 1746 // C99 6.9.2p3: If the declaration of an identifier for an object is 1747 // a tentative definition and has internal linkage (C99 6.2.2p3), the 1748 // declared type shall not be an incomplete type. 1749 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type, 1750 T.getAsString()); 1751 IDecl->setInvalidDecl(); 1752 } 1753 } 1754 if (IDecl->isFileVarDecl()) 1755 CheckForFileScopedRedefinitions(S, IDecl); 1756 } 1757 return NewGroup; 1758} 1759 1760/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 1761/// to introduce parameters into function prototype scope. 1762Sema::DeclTy * 1763Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 1764 const DeclSpec &DS = D.getDeclSpec(); 1765 1766 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 1767 VarDecl::StorageClass StorageClass = VarDecl::None; 1768 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 1769 StorageClass = VarDecl::Register; 1770 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 1771 Diag(DS.getStorageClassSpecLoc(), 1772 diag::err_invalid_storage_class_in_func_decl); 1773 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1774 } 1775 if (DS.isThreadSpecified()) { 1776 Diag(DS.getThreadSpecLoc(), 1777 diag::err_invalid_storage_class_in_func_decl); 1778 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1779 } 1780 1781 // Check that there are no default arguments inside the type of this 1782 // parameter (C++ only). 1783 if (getLangOptions().CPlusPlus) 1784 CheckExtraCXXDefaultArguments(D); 1785 1786 // In this context, we *do not* check D.getInvalidType(). If the declarator 1787 // type was invalid, GetTypeForDeclarator() still returns a "valid" type, 1788 // though it will not reflect the user specified type. 1789 QualType parmDeclType = GetTypeForDeclarator(D, S); 1790 1791 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type"); 1792 1793 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 1794 // Can this happen for params? We already checked that they don't conflict 1795 // among each other. Here they can only shadow globals, which is ok. 1796 IdentifierInfo *II = D.getIdentifier(); 1797 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) { 1798 if (S->isDeclScope(PrevDecl)) { 1799 Diag(D.getIdentifierLoc(), diag::err_param_redefinition, 1800 dyn_cast<NamedDecl>(PrevDecl)->getName()); 1801 1802 // Recover by removing the name 1803 II = 0; 1804 D.SetIdentifier(0, D.getIdentifierLoc()); 1805 } 1806 } 1807 1808 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]). 1809 // Doing the promotion here has a win and a loss. The win is the type for 1810 // both Decl's and DeclRefExpr's will match (a convenient invariant for the 1811 // code generator). The loss is the orginal type isn't preserved. For example: 1812 // 1813 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *" 1814 // int blockvardecl[5]; 1815 // sizeof(parmvardecl); // size == 4 1816 // sizeof(blockvardecl); // size == 20 1817 // } 1818 // 1819 // For expressions, all implicit conversions are captured using the 1820 // ImplicitCastExpr AST node (we have no such mechanism for Decl's). 1821 // 1822 // FIXME: If a source translation tool needs to see the original type, then 1823 // we need to consider storing both types (in ParmVarDecl)... 1824 // 1825 if (parmDeclType->isArrayType()) { 1826 // int x[restrict 4] -> int *restrict 1827 parmDeclType = Context.getArrayDecayedType(parmDeclType); 1828 } else if (parmDeclType->isFunctionType()) 1829 parmDeclType = Context.getPointerType(parmDeclType); 1830 1831 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, 1832 D.getIdentifierLoc(), II, 1833 parmDeclType, StorageClass, 1834 0, 0); 1835 1836 if (D.getInvalidType()) 1837 New->setInvalidDecl(); 1838 1839 if (II) 1840 PushOnScopeChains(New, S); 1841 1842 ProcessDeclAttributes(New, D); 1843 return New; 1844 1845} 1846 1847Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 1848 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 1849 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 1850 "Not a function declarator!"); 1851 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1852 1853 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 1854 // for a K&R function. 1855 if (!FTI.hasPrototype) { 1856 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 1857 if (FTI.ArgInfo[i].Param == 0) { 1858 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared, 1859 FTI.ArgInfo[i].Ident->getName()); 1860 // Implicitly declare the argument as type 'int' for lack of a better 1861 // type. 1862 DeclSpec DS; 1863 const char* PrevSpec; // unused 1864 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 1865 PrevSpec); 1866 Declarator ParamD(DS, Declarator::KNRTypeListContext); 1867 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 1868 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD); 1869 } 1870 } 1871 } else { 1872 // FIXME: Diagnose arguments without names in C. 1873 } 1874 1875 Scope *GlobalScope = FnBodyScope->getParent(); 1876 1877 return ActOnStartOfFunctionDef(FnBodyScope, 1878 ActOnDeclarator(GlobalScope, D, 0)); 1879} 1880 1881Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) { 1882 Decl *decl = static_cast<Decl*>(D); 1883 FunctionDecl *FD = cast<FunctionDecl>(decl); 1884 1885 // See if this is a redefinition. 1886 const FunctionDecl *Definition; 1887 if (FD->getBody(Definition)) { 1888 Diag(FD->getLocation(), diag::err_redefinition, 1889 FD->getName()); 1890 Diag(Definition->getLocation(), diag::err_previous_definition); 1891 } 1892 1893 PushDeclContext(FD); 1894 1895 // Check the validity of our function parameters 1896 CheckParmsForFunctionDef(FD); 1897 1898 // Introduce our parameters into the function scope 1899 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 1900 ParmVarDecl *Param = FD->getParamDecl(p); 1901 // If this has an identifier, add it to the scope stack. 1902 if (Param->getIdentifier()) 1903 PushOnScopeChains(Param, FnBodyScope); 1904 } 1905 1906 return FD; 1907} 1908 1909Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) { 1910 Decl *dcl = static_cast<Decl *>(D); 1911 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) { 1912 FD->setBody((Stmt*)Body); 1913 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 1914 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 1915 MD->setBody((Stmt*)Body); 1916 } else 1917 return 0; 1918 PopDeclContext(); 1919 // Verify and clean out per-function state. 1920 1921 // Check goto/label use. 1922 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 1923 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) { 1924 // Verify that we have no forward references left. If so, there was a goto 1925 // or address of a label taken, but no definition of it. Label fwd 1926 // definitions are indicated with a null substmt. 1927 if (I->second->getSubStmt() == 0) { 1928 LabelStmt *L = I->second; 1929 // Emit error. 1930 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName()); 1931 1932 // At this point, we have gotos that use the bogus label. Stitch it into 1933 // the function body so that they aren't leaked and that the AST is well 1934 // formed. 1935 if (Body) { 1936 L->setSubStmt(new NullStmt(L->getIdentLoc())); 1937 cast<CompoundStmt>((Stmt*)Body)->push_back(L); 1938 } else { 1939 // The whole function wasn't parsed correctly, just delete this. 1940 delete L; 1941 } 1942 } 1943 } 1944 LabelMap.clear(); 1945 1946 return D; 1947} 1948 1949/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 1950/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 1951ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 1952 IdentifierInfo &II, Scope *S) { 1953 // Extension in C99. Legal in C90, but warn about it. 1954 if (getLangOptions().C99) 1955 Diag(Loc, diag::ext_implicit_function_decl, II.getName()); 1956 else 1957 Diag(Loc, diag::warn_implicit_function_decl, II.getName()); 1958 1959 // FIXME: handle stuff like: 1960 // void foo() { extern float X(); } 1961 // void bar() { X(); } <-- implicit decl for X in another scope. 1962 1963 // Set a Declarator for the implicit definition: int foo(); 1964 const char *Dummy; 1965 DeclSpec DS; 1966 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy); 1967 Error = Error; // Silence warning. 1968 assert(!Error && "Error setting up implicit decl!"); 1969 Declarator D(DS, Declarator::BlockContext); 1970 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc)); 1971 D.SetIdentifier(&II, Loc); 1972 1973 // Insert this function into translation-unit scope. 1974 1975 DeclContext *PrevDC = CurContext; 1976 CurContext = Context.getTranslationUnitDecl(); 1977 1978 FunctionDecl *FD = 1979 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0))); 1980 FD->setImplicit(); 1981 1982 CurContext = PrevDC; 1983 1984 return FD; 1985} 1986 1987 1988TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 1989 ScopedDecl *LastDeclarator) { 1990 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 1991 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 1992 1993 // Scope manipulation handled by caller. 1994 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 1995 D.getIdentifierLoc(), 1996 D.getIdentifier(), 1997 T, LastDeclarator); 1998 if (D.getInvalidType()) 1999 NewTD->setInvalidDecl(); 2000 return NewTD; 2001} 2002 2003/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 2004/// former case, Name will be non-null. In the later case, Name will be null. 2005/// TagType indicates what kind of tag this is. TK indicates whether this is a 2006/// reference/declaration/definition of a tag. 2007Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK, 2008 SourceLocation KWLoc, IdentifierInfo *Name, 2009 SourceLocation NameLoc, AttributeList *Attr) { 2010 // If this is a use of an existing tag, it must have a name. 2011 assert((Name != 0 || TK == TK_Definition) && 2012 "Nameless record must be a definition!"); 2013 2014 TagDecl::TagKind Kind; 2015 switch (TagType) { 2016 default: assert(0 && "Unknown tag type!"); 2017 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 2018 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 2019 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 2020 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break; 2021 } 2022 2023 // Two code paths: a new one for structs/unions/classes where we create 2024 // separate decls for forward declarations, and an old (eventually to 2025 // be removed) code path for enums. 2026 if (Kind != TagDecl::TK_enum) 2027 return ActOnTagStruct(S, Kind, TK, KWLoc, Name, NameLoc, Attr); 2028 2029 // If this is a named struct, check to see if there was a previous forward 2030 // declaration or definition. 2031 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up. 2032 ScopedDecl *PrevDecl = 2033 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S)); 2034 2035 if (PrevDecl) { 2036 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) && 2037 "unexpected Decl type"); 2038 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 2039 // If this is a use of a previous tag, or if the tag is already declared 2040 // in the same scope (so that the definition/declaration completes or 2041 // rementions the tag), reuse the decl. 2042 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) { 2043 // Make sure that this wasn't declared as an enum and now used as a 2044 // struct or something similar. 2045 if (PrevTagDecl->getTagKind() != Kind) { 2046 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName()); 2047 Diag(PrevDecl->getLocation(), diag::err_previous_use); 2048 // Recover by making this an anonymous redefinition. 2049 Name = 0; 2050 PrevDecl = 0; 2051 } else { 2052 // If this is a use or a forward declaration, we're good. 2053 if (TK != TK_Definition) 2054 return PrevDecl; 2055 2056 // Diagnose attempts to redefine a tag. 2057 if (PrevTagDecl->isDefinition()) { 2058 Diag(NameLoc, diag::err_redefinition, Name->getName()); 2059 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 2060 // If this is a redefinition, recover by making this struct be 2061 // anonymous, which will make any later references get the previous 2062 // definition. 2063 Name = 0; 2064 } else { 2065 // Okay, this is definition of a previously declared or referenced 2066 // tag. Move the location of the decl to be the definition site. 2067 PrevDecl->setLocation(NameLoc); 2068 return PrevDecl; 2069 } 2070 } 2071 } 2072 // If we get here, this is a definition of a new struct type in a nested 2073 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new 2074 // type. 2075 } else { 2076 // PrevDecl is a namespace. 2077 if (isDeclInScope(PrevDecl, CurContext, S)) { 2078 // The tag name clashes with a namespace name, issue an error and 2079 // recover by making this tag be anonymous. 2080 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName()); 2081 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 2082 Name = 0; 2083 } 2084 } 2085 } 2086 2087 // If there is an identifier, use the location of the identifier as the 2088 // location of the decl, otherwise use the location of the struct/union 2089 // keyword. 2090 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 2091 2092 // Otherwise, if this is the first time we've seen this tag, create the decl. 2093 TagDecl *New; 2094 if (Kind == TagDecl::TK_enum) { 2095 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 2096 // enum X { A, B, C } D; D should chain to X. 2097 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0); 2098 // If this is an undefined enum, warn. 2099 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum); 2100 } else { 2101 // struct/union/class 2102 2103 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 2104 // struct X { int A; } D; D should chain to X. 2105 if (getLangOptions().CPlusPlus) 2106 // FIXME: Look for a way to use RecordDecl for simple structs. 2107 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name); 2108 else 2109 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name); 2110 } 2111 2112 // If this has an identifier, add it to the scope stack. 2113 if (Name) { 2114 // The scope passed in may not be a decl scope. Zip up the scope tree until 2115 // we find one that is. 2116 while ((S->getFlags() & Scope::DeclScope) == 0) 2117 S = S->getParent(); 2118 2119 // Add it to the decl chain. 2120 PushOnScopeChains(New, S); 2121 } 2122 2123 if (Attr) 2124 ProcessDeclAttributeList(New, Attr); 2125 return New; 2126} 2127 2128/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike 2129/// the logic for enums, we create separate decls for forward declarations. 2130/// This is called by ActOnTag, but eventually will replace its logic. 2131Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK, 2132 SourceLocation KWLoc, IdentifierInfo *Name, 2133 SourceLocation NameLoc, AttributeList *Attr) { 2134 2135 // If this is a named struct, check to see if there was a previous forward 2136 // declaration or definition. 2137 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up. 2138 ScopedDecl *PrevDecl = 2139 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S)); 2140 2141 if (PrevDecl) { 2142 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) && 2143 "unexpected Decl type"); 2144 2145 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 2146 // If this is a use of a previous tag, or if the tag is already declared 2147 // in the same scope (so that the definition/declaration completes or 2148 // rementions the tag), reuse the decl. 2149 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) { 2150 // Make sure that this wasn't declared as an enum and now used as a 2151 // struct or something similar. 2152 if (PrevTagDecl->getTagKind() != Kind) { 2153 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName()); 2154 Diag(PrevDecl->getLocation(), diag::err_previous_use); 2155 // Recover by making this an anonymous redefinition. 2156 Name = 0; 2157 PrevDecl = 0; 2158 } else { 2159 // If this is a use, return the original decl. 2160 2161 // FIXME: In the future, return a variant or some other clue 2162 // for the consumer of this Decl to know it doesn't own it. 2163 // For our current ASTs this shouldn't be a problem, but will 2164 // need to be changed with DeclGroups. 2165 if (TK == TK_Reference) 2166 return PrevDecl; 2167 2168 // The new decl is a definition? 2169 if (TK == TK_Definition) { 2170 // Diagnose attempts to redefine a tag. 2171 if (RecordDecl* DefRecord = 2172 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) { 2173 Diag(NameLoc, diag::err_redefinition, Name->getName()); 2174 Diag(DefRecord->getLocation(), diag::err_previous_definition); 2175 // If this is a redefinition, recover by making this struct be 2176 // anonymous, which will make any later references get the previous 2177 // definition. 2178 Name = 0; 2179 PrevDecl = 0; 2180 } 2181 // Okay, this is definition of a previously declared or referenced 2182 // tag. We're going to create a new Decl. 2183 } 2184 } 2185 // If we get here we have (another) forward declaration. Just create 2186 // a new decl. 2187 } 2188 else { 2189 // If we get here, this is a definition of a new struct type in a nested 2190 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 2191 // new decl/type. We set PrevDecl to NULL so that the Records 2192 // have distinct types. 2193 PrevDecl = 0; 2194 } 2195 } else { 2196 // PrevDecl is a namespace. 2197 if (isDeclInScope(PrevDecl, CurContext, S)) { 2198 // The tag name clashes with a namespace name, issue an error and 2199 // recover by making this tag be anonymous. 2200 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName()); 2201 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 2202 Name = 0; 2203 } 2204 } 2205 } 2206 2207 // If there is an identifier, use the location of the identifier as the 2208 // location of the decl, otherwise use the location of the struct/union 2209 // keyword. 2210 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 2211 2212 // Otherwise, if this is the first time we've seen this tag, create the decl. 2213 TagDecl *New; 2214 2215 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 2216 // struct X { int A; } D; D should chain to X. 2217 if (getLangOptions().CPlusPlus) 2218 // FIXME: Look for a way to use RecordDecl for simple structs. 2219 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name, 2220 dyn_cast_or_null<CXXRecordDecl>(PrevDecl)); 2221 else 2222 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 2223 dyn_cast_or_null<RecordDecl>(PrevDecl)); 2224 2225 // If this has an identifier, add it to the scope stack. 2226 if ((TK == TK_Definition || !PrevDecl) && Name) { 2227 // The scope passed in may not be a decl scope. Zip up the scope tree until 2228 // we find one that is. 2229 while ((S->getFlags() & Scope::DeclScope) == 0) 2230 S = S->getParent(); 2231 2232 // Add it to the decl chain. 2233 PushOnScopeChains(New, S); 2234 } 2235 2236 // Handle #pragma pack: if the #pragma pack stack has non-default 2237 // alignment, make up a packed attribute for this decl. These 2238 // attributes are checked when the ASTContext lays out the 2239 // structure. 2240 // 2241 // It is important for implementing the correct semantics that this 2242 // happen here (in act on tag decl). The #pragma pack stack is 2243 // maintained as a result of parser callbacks which can occur at 2244 // many points during the parsing of a struct declaration (because 2245 // the #pragma tokens are effectively skipped over during the 2246 // parsing of the struct). 2247 if (unsigned Alignment = PackContext.getAlignment()) 2248 New->addAttr(new PackedAttr(Alignment * 8)); 2249 2250 if (Attr) 2251 ProcessDeclAttributeList(New, Attr); 2252 2253 return New; 2254} 2255 2256 2257/// Collect the instance variables declared in an Objective-C object. Used in 2258/// the creation of structures from objects using the @defs directive. 2259static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx, 2260 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) { 2261 if (Class->getSuperClass()) 2262 CollectIvars(Class->getSuperClass(), Ctx, ivars); 2263 2264 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 2265 for (ObjCInterfaceDecl::ivar_iterator 2266 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) { 2267 2268 ObjCIvarDecl* ID = *I; 2269 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(), 2270 ID->getIdentifier(), 2271 ID->getType(), 2272 ID->getBitWidth())); 2273 } 2274} 2275 2276/// Called whenever @defs(ClassName) is encountered in the source. Inserts the 2277/// instance variables of ClassName into Decls. 2278void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart, 2279 IdentifierInfo *ClassName, 2280 llvm::SmallVectorImpl<DeclTy*> &Decls) { 2281 // Check that ClassName is a valid class 2282 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName); 2283 if (!Class) { 2284 Diag(DeclStart, diag::err_undef_interface, ClassName->getName()); 2285 return; 2286 } 2287 // Collect the instance variables 2288 CollectIvars(Class, Context, Decls); 2289} 2290 2291QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) { 2292 // This method tries to turn a variable array into a constant 2293 // array even when the size isn't an ICE. This is necessary 2294 // for compatibility with code that depends on gcc's buggy 2295 // constant expression folding, like struct {char x[(int)(char*)2];} 2296 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) { 2297 APValue Result; 2298 if (VLATy->getSizeExpr() && 2299 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) { 2300 llvm::APSInt &Res = Result.getInt(); 2301 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) 2302 return Context.getConstantArrayType(VLATy->getElementType(), 2303 Res, ArrayType::Normal, 0); 2304 } 2305 } 2306 return QualType(); 2307} 2308 2309/// ActOnField - Each field of a struct/union/class is passed into this in order 2310/// to create a FieldDecl object for it. 2311Sema::DeclTy *Sema::ActOnField(Scope *S, 2312 SourceLocation DeclStart, 2313 Declarator &D, ExprTy *BitfieldWidth) { 2314 IdentifierInfo *II = D.getIdentifier(); 2315 Expr *BitWidth = (Expr*)BitfieldWidth; 2316 SourceLocation Loc = DeclStart; 2317 if (II) Loc = D.getIdentifierLoc(); 2318 2319 // FIXME: Unnamed fields can be handled in various different ways, for 2320 // example, unnamed unions inject all members into the struct namespace! 2321 2322 if (BitWidth) { 2323 // TODO: Validate. 2324 //printf("WARNING: BITFIELDS IGNORED!\n"); 2325 2326 // 6.7.2.1p3 2327 // 6.7.2.1p4 2328 2329 } else { 2330 // Not a bitfield. 2331 2332 // validate II. 2333 2334 } 2335 2336 QualType T = GetTypeForDeclarator(D, S); 2337 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 2338 bool InvalidDecl = false; 2339 2340 // C99 6.7.2.1p8: A member of a structure or union may have any type other 2341 // than a variably modified type. 2342 if (T->isVariablyModifiedType()) { 2343 QualType FixedTy = TryFixInvalidVariablyModifiedType(T); 2344 if (!FixedTy.isNull()) { 2345 Diag(Loc, diag::warn_illegal_constant_array_size, Loc); 2346 T = FixedTy; 2347 } else { 2348 // FIXME: This diagnostic needs work 2349 Diag(Loc, diag::err_typecheck_illegal_vla, Loc); 2350 InvalidDecl = true; 2351 } 2352 } 2353 // FIXME: Chain fielddecls together. 2354 FieldDecl *NewFD; 2355 2356 if (getLangOptions().CPlusPlus) { 2357 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs. 2358 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext), 2359 Loc, II, T, BitWidth); 2360 if (II) 2361 PushOnScopeChains(NewFD, S); 2362 } 2363 else 2364 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth); 2365 2366 ProcessDeclAttributes(NewFD, D); 2367 2368 if (D.getInvalidType() || InvalidDecl) 2369 NewFD->setInvalidDecl(); 2370 return NewFD; 2371} 2372 2373/// TranslateIvarVisibility - Translate visibility from a token ID to an 2374/// AST enum value. 2375static ObjCIvarDecl::AccessControl 2376TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 2377 switch (ivarVisibility) { 2378 default: assert(0 && "Unknown visitibility kind"); 2379 case tok::objc_private: return ObjCIvarDecl::Private; 2380 case tok::objc_public: return ObjCIvarDecl::Public; 2381 case tok::objc_protected: return ObjCIvarDecl::Protected; 2382 case tok::objc_package: return ObjCIvarDecl::Package; 2383 } 2384} 2385 2386/// ActOnIvar - Each ivar field of an objective-c class is passed into this 2387/// in order to create an IvarDecl object for it. 2388Sema::DeclTy *Sema::ActOnIvar(Scope *S, 2389 SourceLocation DeclStart, 2390 Declarator &D, ExprTy *BitfieldWidth, 2391 tok::ObjCKeywordKind Visibility) { 2392 IdentifierInfo *II = D.getIdentifier(); 2393 Expr *BitWidth = (Expr*)BitfieldWidth; 2394 SourceLocation Loc = DeclStart; 2395 if (II) Loc = D.getIdentifierLoc(); 2396 2397 // FIXME: Unnamed fields can be handled in various different ways, for 2398 // example, unnamed unions inject all members into the struct namespace! 2399 2400 2401 if (BitWidth) { 2402 // TODO: Validate. 2403 //printf("WARNING: BITFIELDS IGNORED!\n"); 2404 2405 // 6.7.2.1p3 2406 // 6.7.2.1p4 2407 2408 } else { 2409 // Not a bitfield. 2410 2411 // validate II. 2412 2413 } 2414 2415 QualType T = GetTypeForDeclarator(D, S); 2416 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 2417 bool InvalidDecl = false; 2418 2419 // C99 6.7.2.1p8: A member of a structure or union may have any type other 2420 // than a variably modified type. 2421 if (T->isVariablyModifiedType()) { 2422 // FIXME: This diagnostic needs work 2423 Diag(Loc, diag::err_typecheck_illegal_vla, Loc); 2424 InvalidDecl = true; 2425 } 2426 2427 // Get the visibility (access control) for this ivar. 2428 ObjCIvarDecl::AccessControl ac = 2429 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 2430 : ObjCIvarDecl::None; 2431 2432 // Construct the decl. 2433 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac, 2434 (Expr *)BitfieldWidth); 2435 2436 // Process attributes attached to the ivar. 2437 ProcessDeclAttributes(NewID, D); 2438 2439 if (D.getInvalidType() || InvalidDecl) 2440 NewID->setInvalidDecl(); 2441 2442 return NewID; 2443} 2444 2445void Sema::ActOnFields(Scope* S, 2446 SourceLocation RecLoc, DeclTy *RecDecl, 2447 DeclTy **Fields, unsigned NumFields, 2448 SourceLocation LBrac, SourceLocation RBrac, 2449 AttributeList *Attr) { 2450 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl); 2451 assert(EnclosingDecl && "missing record or interface decl"); 2452 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 2453 2454 if (Record) 2455 if (RecordDecl* DefRecord = Record->getDefinition(Context)) { 2456 // Diagnose code like: 2457 // struct S { struct S {} X; }; 2458 // We discover this when we complete the outer S. Reject and ignore the 2459 // outer S. 2460 Diag(DefRecord->getLocation(), diag::err_nested_redefinition, 2461 DefRecord->getKindName()); 2462 Diag(RecLoc, diag::err_previous_definition); 2463 Record->setInvalidDecl(); 2464 return; 2465 } 2466 2467 // Verify that all the fields are okay. 2468 unsigned NumNamedMembers = 0; 2469 llvm::SmallVector<FieldDecl*, 32> RecFields; 2470 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs; 2471 2472 for (unsigned i = 0; i != NumFields; ++i) { 2473 2474 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i])); 2475 assert(FD && "missing field decl"); 2476 2477 // Remember all fields. 2478 RecFields.push_back(FD); 2479 2480 // Get the type for the field. 2481 Type *FDTy = FD->getType().getTypePtr(); 2482 2483 // C99 6.7.2.1p2 - A field may not be a function type. 2484 if (FDTy->isFunctionType()) { 2485 Diag(FD->getLocation(), diag::err_field_declared_as_function, 2486 FD->getName()); 2487 FD->setInvalidDecl(); 2488 EnclosingDecl->setInvalidDecl(); 2489 continue; 2490 } 2491 // C99 6.7.2.1p2 - A field may not be an incomplete type except... 2492 if (FDTy->isIncompleteType()) { 2493 if (!Record) { // Incomplete ivar type is always an error. 2494 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName()); 2495 FD->setInvalidDecl(); 2496 EnclosingDecl->setInvalidDecl(); 2497 continue; 2498 } 2499 if (i != NumFields-1 || // ... that the last member ... 2500 !Record->isStruct() || // ... of a structure ... 2501 !FDTy->isArrayType()) { //... may have incomplete array type. 2502 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName()); 2503 FD->setInvalidDecl(); 2504 EnclosingDecl->setInvalidDecl(); 2505 continue; 2506 } 2507 if (NumNamedMembers < 1) { //... must have more than named member ... 2508 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct, 2509 FD->getName()); 2510 FD->setInvalidDecl(); 2511 EnclosingDecl->setInvalidDecl(); 2512 continue; 2513 } 2514 // Okay, we have a legal flexible array member at the end of the struct. 2515 if (Record) 2516 Record->setHasFlexibleArrayMember(true); 2517 } 2518 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the 2519 /// field of another structure or the element of an array. 2520 if (const RecordType *FDTTy = FDTy->getAsRecordType()) { 2521 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 2522 // If this is a member of a union, then entire union becomes "flexible". 2523 if (Record && Record->isUnion()) { 2524 Record->setHasFlexibleArrayMember(true); 2525 } else { 2526 // If this is a struct/class and this is not the last element, reject 2527 // it. Note that GCC supports variable sized arrays in the middle of 2528 // structures. 2529 if (i != NumFields-1) { 2530 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct, 2531 FD->getName()); 2532 FD->setInvalidDecl(); 2533 EnclosingDecl->setInvalidDecl(); 2534 continue; 2535 } 2536 // We support flexible arrays at the end of structs in other structs 2537 // as an extension. 2538 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct, 2539 FD->getName()); 2540 if (Record) 2541 Record->setHasFlexibleArrayMember(true); 2542 } 2543 } 2544 } 2545 /// A field cannot be an Objective-c object 2546 if (FDTy->isObjCInterfaceType()) { 2547 Diag(FD->getLocation(), diag::err_statically_allocated_object, 2548 FD->getName()); 2549 FD->setInvalidDecl(); 2550 EnclosingDecl->setInvalidDecl(); 2551 continue; 2552 } 2553 // Keep track of the number of named members. 2554 if (IdentifierInfo *II = FD->getIdentifier()) { 2555 // Detect duplicate member names. 2556 if (!FieldIDs.insert(II)) { 2557 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName()); 2558 // Find the previous decl. 2559 SourceLocation PrevLoc; 2560 for (unsigned i = 0; ; ++i) { 2561 assert(i != RecFields.size() && "Didn't find previous def!"); 2562 if (RecFields[i]->getIdentifier() == II) { 2563 PrevLoc = RecFields[i]->getLocation(); 2564 break; 2565 } 2566 } 2567 Diag(PrevLoc, diag::err_previous_definition); 2568 FD->setInvalidDecl(); 2569 EnclosingDecl->setInvalidDecl(); 2570 continue; 2571 } 2572 ++NumNamedMembers; 2573 } 2574 } 2575 2576 // Okay, we successfully defined 'Record'. 2577 if (Record) { 2578 Record->defineBody(Context, &RecFields[0], RecFields.size()); 2579 // If this is a C++ record, HandleTagDeclDefinition will be invoked in 2580 // Sema::ActOnFinishCXXClassDef. 2581 if (!isa<CXXRecordDecl>(Record)) 2582 Consumer.HandleTagDeclDefinition(Record); 2583 } else { 2584 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]); 2585 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) 2586 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac); 2587 else if (ObjCImplementationDecl *IMPDecl = 2588 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 2589 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 2590 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size()); 2591 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 2592 } 2593 } 2594 2595 if (Attr) 2596 ProcessDeclAttributeList(Record, Attr); 2597} 2598 2599Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl, 2600 DeclTy *lastEnumConst, 2601 SourceLocation IdLoc, IdentifierInfo *Id, 2602 SourceLocation EqualLoc, ExprTy *val) { 2603 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl)); 2604 EnumConstantDecl *LastEnumConst = 2605 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst)); 2606 Expr *Val = static_cast<Expr*>(val); 2607 2608 // The scope passed in may not be a decl scope. Zip up the scope tree until 2609 // we find one that is. 2610 while ((S->getFlags() & Scope::DeclScope) == 0) 2611 S = S->getParent(); 2612 2613 // Verify that there isn't already something declared with this name in this 2614 // scope. 2615 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) { 2616 // When in C++, we may get a TagDecl with the same name; in this case the 2617 // enum constant will 'hide' the tag. 2618 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 2619 "Received TagDecl when not in C++!"); 2620 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 2621 if (isa<EnumConstantDecl>(PrevDecl)) 2622 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName()); 2623 else 2624 Diag(IdLoc, diag::err_redefinition, Id->getName()); 2625 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 2626 delete Val; 2627 return 0; 2628 } 2629 } 2630 2631 llvm::APSInt EnumVal(32); 2632 QualType EltTy; 2633 if (Val) { 2634 // Make sure to promote the operand type to int. 2635 UsualUnaryConversions(Val); 2636 2637 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 2638 SourceLocation ExpLoc; 2639 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) { 2640 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr, 2641 Id->getName()); 2642 delete Val; 2643 Val = 0; // Just forget about it. 2644 } else { 2645 EltTy = Val->getType(); 2646 } 2647 } 2648 2649 if (!Val) { 2650 if (LastEnumConst) { 2651 // Assign the last value + 1. 2652 EnumVal = LastEnumConst->getInitVal(); 2653 ++EnumVal; 2654 2655 // Check for overflow on increment. 2656 if (EnumVal < LastEnumConst->getInitVal()) 2657 Diag(IdLoc, diag::warn_enum_value_overflow); 2658 2659 EltTy = LastEnumConst->getType(); 2660 } else { 2661 // First value, set to zero. 2662 EltTy = Context.IntTy; 2663 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy))); 2664 } 2665 } 2666 2667 EnumConstantDecl *New = 2668 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy, 2669 Val, EnumVal, 2670 LastEnumConst); 2671 2672 // Register this decl in the current scope stack. 2673 PushOnScopeChains(New, S); 2674 return New; 2675} 2676 2677// FIXME: For consistency with ActOnFields(), we should have the parser 2678// pass in the source location for the left/right braces. 2679void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX, 2680 DeclTy **Elements, unsigned NumElements) { 2681 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX)); 2682 2683 if (Enum && Enum->isDefinition()) { 2684 // Diagnose code like: 2685 // enum e0 { 2686 // E0 = sizeof(enum e0 { E1 }) 2687 // }; 2688 Diag(Enum->getLocation(), diag::err_nested_redefinition, 2689 Enum->getName()); 2690 Diag(EnumLoc, diag::err_previous_definition); 2691 Enum->setInvalidDecl(); 2692 return; 2693 } 2694 // TODO: If the result value doesn't fit in an int, it must be a long or long 2695 // long value. ISO C does not support this, but GCC does as an extension, 2696 // emit a warning. 2697 unsigned IntWidth = Context.Target.getIntWidth(); 2698 2699 // Verify that all the values are okay, compute the size of the values, and 2700 // reverse the list. 2701 unsigned NumNegativeBits = 0; 2702 unsigned NumPositiveBits = 0; 2703 2704 // Keep track of whether all elements have type int. 2705 bool AllElementsInt = true; 2706 2707 EnumConstantDecl *EltList = 0; 2708 for (unsigned i = 0; i != NumElements; ++i) { 2709 EnumConstantDecl *ECD = 2710 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 2711 if (!ECD) continue; // Already issued a diagnostic. 2712 2713 // If the enum value doesn't fit in an int, emit an extension warning. 2714 const llvm::APSInt &InitVal = ECD->getInitVal(); 2715 assert(InitVal.getBitWidth() >= IntWidth && 2716 "Should have promoted value to int"); 2717 if (InitVal.getBitWidth() > IntWidth) { 2718 llvm::APSInt V(InitVal); 2719 V.trunc(IntWidth); 2720 V.extend(InitVal.getBitWidth()); 2721 if (V != InitVal) 2722 Diag(ECD->getLocation(), diag::ext_enum_value_not_int, 2723 InitVal.toString(10)); 2724 } 2725 2726 // Keep track of the size of positive and negative values. 2727 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 2728 NumPositiveBits = std::max(NumPositiveBits, 2729 (unsigned)InitVal.getActiveBits()); 2730 else 2731 NumNegativeBits = std::max(NumNegativeBits, 2732 (unsigned)InitVal.getMinSignedBits()); 2733 2734 // Keep track of whether every enum element has type int (very commmon). 2735 if (AllElementsInt) 2736 AllElementsInt = ECD->getType() == Context.IntTy; 2737 2738 ECD->setNextDeclarator(EltList); 2739 EltList = ECD; 2740 } 2741 2742 // Figure out the type that should be used for this enum. 2743 // FIXME: Support attribute(packed) on enums and -fshort-enums. 2744 QualType BestType; 2745 unsigned BestWidth; 2746 2747 if (NumNegativeBits) { 2748 // If there is a negative value, figure out the smallest integer type (of 2749 // int/long/longlong) that fits. 2750 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 2751 BestType = Context.IntTy; 2752 BestWidth = IntWidth; 2753 } else { 2754 BestWidth = Context.Target.getLongWidth(); 2755 2756 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) 2757 BestType = Context.LongTy; 2758 else { 2759 BestWidth = Context.Target.getLongLongWidth(); 2760 2761 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 2762 Diag(Enum->getLocation(), diag::warn_enum_too_large); 2763 BestType = Context.LongLongTy; 2764 } 2765 } 2766 } else { 2767 // If there is no negative value, figure out which of uint, ulong, ulonglong 2768 // fits. 2769 if (NumPositiveBits <= IntWidth) { 2770 BestType = Context.UnsignedIntTy; 2771 BestWidth = IntWidth; 2772 } else if (NumPositiveBits <= 2773 (BestWidth = Context.Target.getLongWidth())) { 2774 BestType = Context.UnsignedLongTy; 2775 } else { 2776 BestWidth = Context.Target.getLongLongWidth(); 2777 assert(NumPositiveBits <= BestWidth && 2778 "How could an initializer get larger than ULL?"); 2779 BestType = Context.UnsignedLongLongTy; 2780 } 2781 } 2782 2783 // Loop over all of the enumerator constants, changing their types to match 2784 // the type of the enum if needed. 2785 for (unsigned i = 0; i != NumElements; ++i) { 2786 EnumConstantDecl *ECD = 2787 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 2788 if (!ECD) continue; // Already issued a diagnostic. 2789 2790 // Standard C says the enumerators have int type, but we allow, as an 2791 // extension, the enumerators to be larger than int size. If each 2792 // enumerator value fits in an int, type it as an int, otherwise type it the 2793 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 2794 // that X has type 'int', not 'unsigned'. 2795 if (ECD->getType() == Context.IntTy) { 2796 // Make sure the init value is signed. 2797 llvm::APSInt IV = ECD->getInitVal(); 2798 IV.setIsSigned(true); 2799 ECD->setInitVal(IV); 2800 continue; // Already int type. 2801 } 2802 2803 // Determine whether the value fits into an int. 2804 llvm::APSInt InitVal = ECD->getInitVal(); 2805 bool FitsInInt; 2806 if (InitVal.isUnsigned() || !InitVal.isNegative()) 2807 FitsInInt = InitVal.getActiveBits() < IntWidth; 2808 else 2809 FitsInInt = InitVal.getMinSignedBits() <= IntWidth; 2810 2811 // If it fits into an integer type, force it. Otherwise force it to match 2812 // the enum decl type. 2813 QualType NewTy; 2814 unsigned NewWidth; 2815 bool NewSign; 2816 if (FitsInInt) { 2817 NewTy = Context.IntTy; 2818 NewWidth = IntWidth; 2819 NewSign = true; 2820 } else if (ECD->getType() == BestType) { 2821 // Already the right type! 2822 continue; 2823 } else { 2824 NewTy = BestType; 2825 NewWidth = BestWidth; 2826 NewSign = BestType->isSignedIntegerType(); 2827 } 2828 2829 // Adjust the APSInt value. 2830 InitVal.extOrTrunc(NewWidth); 2831 InitVal.setIsSigned(NewSign); 2832 ECD->setInitVal(InitVal); 2833 2834 // Adjust the Expr initializer and type. 2835 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr())); 2836 ECD->setType(NewTy); 2837 } 2838 2839 Enum->defineElements(EltList, BestType); 2840 Consumer.HandleTagDeclDefinition(Enum); 2841} 2842 2843Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, 2844 ExprTy *expr) { 2845 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr); 2846 2847 return FileScopeAsmDecl::Create(Context, Loc, AsmString); 2848} 2849 2850Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc, 2851 SourceLocation LBrace, 2852 SourceLocation RBrace, 2853 const char *Lang, 2854 unsigned StrSize, 2855 DeclTy *D) { 2856 LinkageSpecDecl::LanguageIDs Language; 2857 Decl *dcl = static_cast<Decl *>(D); 2858 if (strncmp(Lang, "\"C\"", StrSize) == 0) 2859 Language = LinkageSpecDecl::lang_c; 2860 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 2861 Language = LinkageSpecDecl::lang_cxx; 2862 else { 2863 Diag(Loc, diag::err_bad_language); 2864 return 0; 2865 } 2866 2867 // FIXME: Add all the various semantics of linkage specifications 2868 return LinkageSpecDecl::Create(Context, Loc, Language, dcl); 2869} 2870 2871void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name, 2872 ExprTy *alignment, SourceLocation PragmaLoc, 2873 SourceLocation LParenLoc, SourceLocation RParenLoc) { 2874 Expr *Alignment = static_cast<Expr *>(alignment); 2875 2876 // If specified then alignment must be a "small" power of two. 2877 unsigned AlignmentVal = 0; 2878 if (Alignment) { 2879 llvm::APSInt Val; 2880 if (!Alignment->isIntegerConstantExpr(Val, Context) || 2881 !Val.isPowerOf2() || 2882 Val.getZExtValue() > 16) { 2883 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment); 2884 delete Alignment; 2885 return; // Ignore 2886 } 2887 2888 AlignmentVal = (unsigned) Val.getZExtValue(); 2889 } 2890 2891 switch (Kind) { 2892 case Action::PPK_Default: // pack([n]) 2893 PackContext.setAlignment(AlignmentVal); 2894 break; 2895 2896 case Action::PPK_Show: // pack(show) 2897 // Show the current alignment, making sure to show the right value 2898 // for the default. 2899 AlignmentVal = PackContext.getAlignment(); 2900 // FIXME: This should come from the target. 2901 if (AlignmentVal == 0) 2902 AlignmentVal = 8; 2903 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal)); 2904 break; 2905 2906 case Action::PPK_Push: // pack(push [, id] [, [n]) 2907 PackContext.push(Name); 2908 // Set the new alignment if specified. 2909 if (Alignment) 2910 PackContext.setAlignment(AlignmentVal); 2911 break; 2912 2913 case Action::PPK_Pop: // pack(pop [, id] [, n]) 2914 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack: 2915 // "#pragma pack(pop, identifier, n) is undefined" 2916 if (Alignment && Name) 2917 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment); 2918 2919 // Do the pop. 2920 if (!PackContext.pop(Name)) { 2921 // If a name was specified then failure indicates the name 2922 // wasn't found. Otherwise failure indicates the stack was 2923 // empty. 2924 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed, 2925 Name ? "no record matching name" : "stack empty"); 2926 2927 // FIXME: Warn about popping named records as MSVC does. 2928 } else { 2929 // Pop succeeded, set the new alignment if specified. 2930 if (Alignment) 2931 PackContext.setAlignment(AlignmentVal); 2932 } 2933 break; 2934 2935 default: 2936 assert(0 && "Invalid #pragma pack kind."); 2937 } 2938} 2939 2940bool PragmaPackStack::pop(IdentifierInfo *Name) { 2941 if (Stack.empty()) 2942 return false; 2943 2944 // If name is empty just pop top. 2945 if (!Name) { 2946 Alignment = Stack.back().first; 2947 Stack.pop_back(); 2948 return true; 2949 } 2950 2951 // Otherwise, find the named record. 2952 for (unsigned i = Stack.size(); i != 0; ) { 2953 --i; 2954 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) { 2955 // Found it, pop up to and including this record. 2956 Alignment = Stack[i].first; 2957 Stack.erase(Stack.begin() + i, Stack.end()); 2958 return true; 2959 } 2960 } 2961 2962 return false; 2963} 2964