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