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