SemaDecl.cpp revision c63a1f276f7b324fd9a4be82098b1c8f7bf30733
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) { 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 // Copy the parameter declarations from the declarator D to 704 // the function declaration NewFD, if they are available. 705 if (D.getNumTypeObjects() > 0 && 706 D.getTypeObject(0).Fun.hasPrototype) { 707 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 708 709 // Create Decl objects for each parameter, adding them to the 710 // FunctionDecl. 711 llvm::SmallVector<ParmVarDecl*, 16> Params; 712 713 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 714 // function that takes no arguments, not a function that takes a 715 // single void argument. 716 // We let through "const void" here because Sema::GetTypeForDeclarator 717 // already checks for that case. 718 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 719 FTI.ArgInfo[0].Param && 720 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 721 // empty arg list, don't push any params. 722 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param; 723 724 // In C++, the empty parameter-type-list must be spelled "void"; a 725 // typedef of void is not permitted. 726 if (getLangOptions().CPlusPlus && 727 Param->getType().getUnqualifiedType() != Context.VoidTy) { 728 Diag(Param->getLocation(), diag::ext_param_typedef_of_void); 729 } 730 731 } else { 732 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 733 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param); 734 } 735 736 NewFD->setParams(&Params[0], Params.size()); 737 } 738 739 // Merge the decl with the existing one if appropriate. Since C functions 740 // are in a flat namespace, make sure we consider decls in outer scopes. 741 if (PrevDecl && 742 (!getLangOptions().CPlusPlus || 743 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) { 744 bool Redeclaration = false; 745 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration); 746 if (NewFD == 0) return 0; 747 if (Redeclaration) { 748 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl)); 749 } 750 } 751 New = NewFD; 752 753 // In C++, check default arguments now that we have merged decls. 754 if (getLangOptions().CPlusPlus) 755 CheckCXXDefaultArguments(NewFD); 756 } else { 757 // Check that there are no default arguments (C++ only). 758 if (getLangOptions().CPlusPlus) 759 CheckExtraCXXDefaultArguments(D); 760 761 if (R.getTypePtr()->isObjCInterfaceType()) { 762 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object, 763 D.getIdentifier()->getName()); 764 InvalidDecl = true; 765 } 766 767 VarDecl *NewVD; 768 VarDecl::StorageClass SC; 769 switch (D.getDeclSpec().getStorageClassSpec()) { 770 default: assert(0 && "Unknown storage class!"); 771 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 772 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 773 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 774 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 775 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 776 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 777 } 778 if (D.getContext() == Declarator::MemberContext) { 779 assert(SC == VarDecl::Static && "Invalid storage class for member!"); 780 // This is a static data member for a C++ class. 781 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext), 782 D.getIdentifierLoc(), II, 783 R, LastDeclarator); 784 } else { 785 if (S->getFnParent() == 0) { 786 // C99 6.9p2: The storage-class specifiers auto and register shall not 787 // appear in the declaration specifiers in an external declaration. 788 if (SC == VarDecl::Auto || SC == VarDecl::Register) { 789 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope, 790 R.getAsString()); 791 InvalidDecl = true; 792 } 793 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(), 794 II, R, SC, LastDeclarator); 795 } else { 796 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(), 797 II, R, SC, LastDeclarator); 798 } 799 } 800 // Handle attributes prior to checking for duplicates in MergeVarDecl 801 ProcessDeclAttributes(NewVD, D); 802 803 // Emit an error if an address space was applied to decl with local storage. 804 // This includes arrays of objects with address space qualifiers, but not 805 // automatic variables that point to other address spaces. 806 // ISO/IEC TR 18037 S5.1.2 807 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) { 808 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl); 809 InvalidDecl = true; 810 } 811 // Merge the decl with the existing one if appropriate. If the decl is 812 // in an outer scope, it isn't the same thing. 813 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) { 814 NewVD = MergeVarDecl(NewVD, PrevDecl); 815 if (NewVD == 0) return 0; 816 } 817 New = NewVD; 818 } 819 820 // If this has an identifier, add it to the scope stack. 821 if (II) 822 PushOnScopeChains(New, S); 823 // If any semantic error occurred, mark the decl as invalid. 824 if (D.getInvalidType() || InvalidDecl) 825 New->setInvalidDecl(); 826 827 return New; 828} 829 830bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) { 831 switch (Init->getStmtClass()) { 832 default: 833 Diag(Init->getExprLoc(), 834 diag::err_init_element_not_constant, Init->getSourceRange()); 835 return true; 836 case Expr::ParenExprClass: { 837 const ParenExpr* PE = cast<ParenExpr>(Init); 838 return CheckAddressConstantExpressionLValue(PE->getSubExpr()); 839 } 840 case Expr::CompoundLiteralExprClass: 841 return cast<CompoundLiteralExpr>(Init)->isFileScope(); 842 case Expr::DeclRefExprClass: { 843 const Decl *D = cast<DeclRefExpr>(Init)->getDecl(); 844 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 845 if (VD->hasGlobalStorage()) 846 return false; 847 Diag(Init->getExprLoc(), 848 diag::err_init_element_not_constant, Init->getSourceRange()); 849 return true; 850 } 851 if (isa<FunctionDecl>(D)) 852 return false; 853 Diag(Init->getExprLoc(), 854 diag::err_init_element_not_constant, Init->getSourceRange()); 855 return true; 856 } 857 case Expr::MemberExprClass: { 858 const MemberExpr *M = cast<MemberExpr>(Init); 859 if (M->isArrow()) 860 return CheckAddressConstantExpression(M->getBase()); 861 return CheckAddressConstantExpressionLValue(M->getBase()); 862 } 863 case Expr::ArraySubscriptExprClass: { 864 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)? 865 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init); 866 return CheckAddressConstantExpression(ASE->getBase()) || 867 CheckArithmeticConstantExpression(ASE->getIdx()); 868 } 869 case Expr::StringLiteralClass: 870 case Expr::PreDefinedExprClass: 871 return false; 872 case Expr::UnaryOperatorClass: { 873 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 874 875 // C99 6.6p9 876 if (Exp->getOpcode() == UnaryOperator::Deref) 877 return CheckAddressConstantExpression(Exp->getSubExpr()); 878 879 Diag(Init->getExprLoc(), 880 diag::err_init_element_not_constant, Init->getSourceRange()); 881 return true; 882 } 883 } 884} 885 886bool Sema::CheckAddressConstantExpression(const Expr* Init) { 887 switch (Init->getStmtClass()) { 888 default: 889 Diag(Init->getExprLoc(), 890 diag::err_init_element_not_constant, Init->getSourceRange()); 891 return true; 892 case Expr::ParenExprClass: { 893 const ParenExpr* PE = cast<ParenExpr>(Init); 894 return CheckAddressConstantExpression(PE->getSubExpr()); 895 } 896 case Expr::StringLiteralClass: 897 case Expr::ObjCStringLiteralClass: 898 return false; 899 case Expr::CallExprClass: { 900 const CallExpr *CE = cast<CallExpr>(Init); 901 if (CE->isBuiltinConstantExpr()) 902 return false; 903 Diag(Init->getExprLoc(), 904 diag::err_init_element_not_constant, Init->getSourceRange()); 905 return true; 906 } 907 case Expr::UnaryOperatorClass: { 908 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 909 910 // C99 6.6p9 911 if (Exp->getOpcode() == UnaryOperator::AddrOf) 912 return CheckAddressConstantExpressionLValue(Exp->getSubExpr()); 913 914 if (Exp->getOpcode() == UnaryOperator::Extension) 915 return CheckAddressConstantExpression(Exp->getSubExpr()); 916 917 Diag(Init->getExprLoc(), 918 diag::err_init_element_not_constant, Init->getSourceRange()); 919 return true; 920 } 921 case Expr::BinaryOperatorClass: { 922 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"? 923 const BinaryOperator *Exp = cast<BinaryOperator>(Init); 924 925 Expr *PExp = Exp->getLHS(); 926 Expr *IExp = Exp->getRHS(); 927 if (IExp->getType()->isPointerType()) 928 std::swap(PExp, IExp); 929 930 // FIXME: Should we pedwarn if IExp isn't an integer constant expression? 931 return CheckAddressConstantExpression(PExp) || 932 CheckArithmeticConstantExpression(IExp); 933 } 934 case Expr::ImplicitCastExprClass: { 935 const Expr* SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr(); 936 937 // Check for implicit promotion 938 if (SubExpr->getType()->isFunctionType() || 939 SubExpr->getType()->isArrayType()) 940 return CheckAddressConstantExpressionLValue(SubExpr); 941 942 // Check for pointer->pointer cast 943 if (SubExpr->getType()->isPointerType()) 944 return CheckAddressConstantExpression(SubExpr); 945 946 if (SubExpr->getType()->isArithmeticType()) 947 return CheckArithmeticConstantExpression(SubExpr); 948 949 Diag(Init->getExprLoc(), 950 diag::err_init_element_not_constant, Init->getSourceRange()); 951 return true; 952 } 953 case Expr::CastExprClass: { 954 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr(); 955 956 // Check for pointer->pointer cast 957 if (SubExpr->getType()->isPointerType()) 958 return CheckAddressConstantExpression(SubExpr); 959 960 // FIXME: Should we pedwarn for (int*)(0+0)? 961 if (SubExpr->getType()->isArithmeticType()) 962 return CheckArithmeticConstantExpression(SubExpr); 963 964 Diag(Init->getExprLoc(), 965 diag::err_init_element_not_constant, Init->getSourceRange()); 966 return true; 967 } 968 case Expr::ConditionalOperatorClass: { 969 // FIXME: Should we pedwarn here? 970 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init); 971 if (!Exp->getCond()->getType()->isArithmeticType()) { 972 Diag(Init->getExprLoc(), 973 diag::err_init_element_not_constant, Init->getSourceRange()); 974 return true; 975 } 976 if (CheckArithmeticConstantExpression(Exp->getCond())) 977 return true; 978 if (Exp->getLHS() && 979 CheckAddressConstantExpression(Exp->getLHS())) 980 return true; 981 return CheckAddressConstantExpression(Exp->getRHS()); 982 } 983 case Expr::AddrLabelExprClass: 984 return false; 985 } 986} 987 988static const Expr* FindExpressionBaseAddress(const Expr* E); 989 990static const Expr* FindExpressionBaseAddressLValue(const Expr* E) { 991 switch (E->getStmtClass()) { 992 default: 993 return E; 994 case Expr::ParenExprClass: { 995 const ParenExpr* PE = cast<ParenExpr>(E); 996 return FindExpressionBaseAddressLValue(PE->getSubExpr()); 997 } 998 case Expr::MemberExprClass: { 999 const MemberExpr *M = cast<MemberExpr>(E); 1000 if (M->isArrow()) 1001 return FindExpressionBaseAddress(M->getBase()); 1002 return FindExpressionBaseAddressLValue(M->getBase()); 1003 } 1004 case Expr::ArraySubscriptExprClass: { 1005 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E); 1006 return FindExpressionBaseAddress(ASE->getBase()); 1007 } 1008 case Expr::UnaryOperatorClass: { 1009 const UnaryOperator *Exp = cast<UnaryOperator>(E); 1010 1011 if (Exp->getOpcode() == UnaryOperator::Deref) 1012 return FindExpressionBaseAddress(Exp->getSubExpr()); 1013 1014 return E; 1015 } 1016 } 1017} 1018 1019static const Expr* FindExpressionBaseAddress(const Expr* E) { 1020 switch (E->getStmtClass()) { 1021 default: 1022 return E; 1023 case Expr::ParenExprClass: { 1024 const ParenExpr* PE = cast<ParenExpr>(E); 1025 return FindExpressionBaseAddress(PE->getSubExpr()); 1026 } 1027 case Expr::UnaryOperatorClass: { 1028 const UnaryOperator *Exp = cast<UnaryOperator>(E); 1029 1030 // C99 6.6p9 1031 if (Exp->getOpcode() == UnaryOperator::AddrOf) 1032 return FindExpressionBaseAddressLValue(Exp->getSubExpr()); 1033 1034 if (Exp->getOpcode() == UnaryOperator::Extension) 1035 return FindExpressionBaseAddress(Exp->getSubExpr()); 1036 1037 return E; 1038 } 1039 case Expr::BinaryOperatorClass: { 1040 const BinaryOperator *Exp = cast<BinaryOperator>(E); 1041 1042 Expr *PExp = Exp->getLHS(); 1043 Expr *IExp = Exp->getRHS(); 1044 if (IExp->getType()->isPointerType()) 1045 std::swap(PExp, IExp); 1046 1047 return FindExpressionBaseAddress(PExp); 1048 } 1049 case Expr::ImplicitCastExprClass: { 1050 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr(); 1051 1052 // Check for implicit promotion 1053 if (SubExpr->getType()->isFunctionType() || 1054 SubExpr->getType()->isArrayType()) 1055 return FindExpressionBaseAddressLValue(SubExpr); 1056 1057 // Check for pointer->pointer cast 1058 if (SubExpr->getType()->isPointerType()) 1059 return FindExpressionBaseAddress(SubExpr); 1060 1061 // We assume that we have an arithmetic expression here; 1062 // if we don't, we'll figure it out later 1063 return 0; 1064 } 1065 case Expr::CastExprClass: { 1066 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 1067 1068 // Check for pointer->pointer cast 1069 if (SubExpr->getType()->isPointerType()) 1070 return FindExpressionBaseAddress(SubExpr); 1071 1072 // We assume that we have an arithmetic expression here; 1073 // if we don't, we'll figure it out later 1074 return 0; 1075 } 1076 } 1077} 1078 1079bool Sema::CheckArithmeticConstantExpression(const Expr* Init) { 1080 switch (Init->getStmtClass()) { 1081 default: 1082 Diag(Init->getExprLoc(), 1083 diag::err_init_element_not_constant, Init->getSourceRange()); 1084 return true; 1085 case Expr::ParenExprClass: { 1086 const ParenExpr* PE = cast<ParenExpr>(Init); 1087 return CheckArithmeticConstantExpression(PE->getSubExpr()); 1088 } 1089 case Expr::FloatingLiteralClass: 1090 case Expr::IntegerLiteralClass: 1091 case Expr::CharacterLiteralClass: 1092 case Expr::ImaginaryLiteralClass: 1093 case Expr::TypesCompatibleExprClass: 1094 case Expr::CXXBoolLiteralExprClass: 1095 return false; 1096 case Expr::CallExprClass: { 1097 const CallExpr *CE = cast<CallExpr>(Init); 1098 if (CE->isBuiltinConstantExpr()) 1099 return false; 1100 Diag(Init->getExprLoc(), 1101 diag::err_init_element_not_constant, Init->getSourceRange()); 1102 return true; 1103 } 1104 case Expr::DeclRefExprClass: { 1105 const Decl *D = cast<DeclRefExpr>(Init)->getDecl(); 1106 if (isa<EnumConstantDecl>(D)) 1107 return false; 1108 Diag(Init->getExprLoc(), 1109 diag::err_init_element_not_constant, Init->getSourceRange()); 1110 return true; 1111 } 1112 case Expr::CompoundLiteralExprClass: 1113 // Allow "(vector type){2,4}"; normal C constraints don't allow this, 1114 // but vectors are allowed to be magic. 1115 if (Init->getType()->isVectorType()) 1116 return false; 1117 Diag(Init->getExprLoc(), 1118 diag::err_init_element_not_constant, Init->getSourceRange()); 1119 return true; 1120 case Expr::UnaryOperatorClass: { 1121 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1122 1123 switch (Exp->getOpcode()) { 1124 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 1125 // See C99 6.6p3. 1126 default: 1127 Diag(Init->getExprLoc(), 1128 diag::err_init_element_not_constant, Init->getSourceRange()); 1129 return true; 1130 case UnaryOperator::SizeOf: 1131 case UnaryOperator::AlignOf: 1132 case UnaryOperator::OffsetOf: 1133 // sizeof(E) is a constantexpr if and only if E is not evaluted. 1134 // See C99 6.5.3.4p2 and 6.6p3. 1135 if (Exp->getSubExpr()->getType()->isConstantSizeType()) 1136 return false; 1137 Diag(Init->getExprLoc(), 1138 diag::err_init_element_not_constant, Init->getSourceRange()); 1139 return true; 1140 case UnaryOperator::Extension: 1141 case UnaryOperator::LNot: 1142 case UnaryOperator::Plus: 1143 case UnaryOperator::Minus: 1144 case UnaryOperator::Not: 1145 return CheckArithmeticConstantExpression(Exp->getSubExpr()); 1146 } 1147 } 1148 case Expr::SizeOfAlignOfTypeExprClass: { 1149 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init); 1150 // Special check for void types, which are allowed as an extension 1151 if (Exp->getArgumentType()->isVoidType()) 1152 return false; 1153 // alignof always evaluates to a constant. 1154 // FIXME: is sizeof(int[3.0]) a constant expression? 1155 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) { 1156 Diag(Init->getExprLoc(), 1157 diag::err_init_element_not_constant, Init->getSourceRange()); 1158 return true; 1159 } 1160 return false; 1161 } 1162 case Expr::BinaryOperatorClass: { 1163 const BinaryOperator *Exp = cast<BinaryOperator>(Init); 1164 1165 if (Exp->getLHS()->getType()->isArithmeticType() && 1166 Exp->getRHS()->getType()->isArithmeticType()) { 1167 return CheckArithmeticConstantExpression(Exp->getLHS()) || 1168 CheckArithmeticConstantExpression(Exp->getRHS()); 1169 } 1170 1171 if (Exp->getLHS()->getType()->isPointerType() && 1172 Exp->getRHS()->getType()->isPointerType()) { 1173 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS()); 1174 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS()); 1175 1176 // Only allow a null (constant integer) base; we could 1177 // allow some additional cases if necessary, but this 1178 // is sufficient to cover offsetof-like constructs. 1179 if (!LHSBase && !RHSBase) { 1180 return CheckAddressConstantExpression(Exp->getLHS()) || 1181 CheckAddressConstantExpression(Exp->getRHS()); 1182 } 1183 } 1184 1185 Diag(Init->getExprLoc(), 1186 diag::err_init_element_not_constant, Init->getSourceRange()); 1187 return true; 1188 } 1189 case Expr::ImplicitCastExprClass: 1190 case Expr::CastExprClass: { 1191 const Expr *SubExpr; 1192 if (const CastExpr *C = dyn_cast<CastExpr>(Init)) { 1193 SubExpr = C->getSubExpr(); 1194 } else { 1195 SubExpr = cast<ImplicitCastExpr>(Init)->getSubExpr(); 1196 } 1197 1198 if (SubExpr->getType()->isArithmeticType()) 1199 return CheckArithmeticConstantExpression(SubExpr); 1200 1201 Diag(Init->getExprLoc(), 1202 diag::err_init_element_not_constant, Init->getSourceRange()); 1203 return true; 1204 } 1205 case Expr::ConditionalOperatorClass: { 1206 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init); 1207 if (CheckArithmeticConstantExpression(Exp->getCond())) 1208 return true; 1209 if (Exp->getLHS() && 1210 CheckArithmeticConstantExpression(Exp->getLHS())) 1211 return true; 1212 return CheckArithmeticConstantExpression(Exp->getRHS()); 1213 } 1214 } 1215} 1216 1217bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 1218 Init = Init->IgnoreParens(); 1219 1220 // Look through CXXDefaultArgExprs; they have no meaning in this context. 1221 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init)) 1222 return CheckForConstantInitializer(DAE->getExpr(), DclT); 1223 1224 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init)) 1225 return CheckForConstantInitializer(e->getInitializer(), DclT); 1226 1227 if (Init->getType()->isReferenceType()) { 1228 // FIXME: Work out how the heck reference types work 1229 return false; 1230#if 0 1231 // A reference is constant if the address of the expression 1232 // is constant 1233 // We look through initlists here to simplify 1234 // CheckAddressConstantExpressionLValue. 1235 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) { 1236 assert(Exp->getNumInits() > 0 && 1237 "Refernce initializer cannot be empty"); 1238 Init = Exp->getInit(0); 1239 } 1240 return CheckAddressConstantExpressionLValue(Init); 1241#endif 1242 } 1243 1244 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) { 1245 unsigned numInits = Exp->getNumInits(); 1246 for (unsigned i = 0; i < numInits; i++) { 1247 // FIXME: Need to get the type of the declaration for C++, 1248 // because it could be a reference? 1249 if (CheckForConstantInitializer(Exp->getInit(i), 1250 Exp->getInit(i)->getType())) 1251 return true; 1252 } 1253 return false; 1254 } 1255 1256 if (Init->isNullPointerConstant(Context)) 1257 return false; 1258 if (Init->getType()->isArithmeticType()) { 1259 QualType InitTy = Context.getCanonicalType(Init->getType()) 1260 .getUnqualifiedType(); 1261 if (InitTy == Context.BoolTy) { 1262 // Special handling for pointers implicitly cast to bool; 1263 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level. 1264 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) { 1265 Expr* SubE = ICE->getSubExpr(); 1266 if (SubE->getType()->isPointerType() || 1267 SubE->getType()->isArrayType() || 1268 SubE->getType()->isFunctionType()) { 1269 return CheckAddressConstantExpression(Init); 1270 } 1271 } 1272 } else if (InitTy->isIntegralType()) { 1273 Expr* SubE = 0; 1274 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) 1275 SubE = ICE->getSubExpr(); 1276 else if (CastExpr* CE = dyn_cast<CastExpr>(Init)) 1277 SubE = CE->getSubExpr(); 1278 // Special check for pointer cast to int; we allow as an extension 1279 // an address constant cast to an integer if the integer 1280 // is of an appropriate width (this sort of code is apparently used 1281 // in some places). 1282 // FIXME: Add pedwarn? 1283 // FIXME: Don't allow bitfields here! Need the FieldDecl for that. 1284 if (SubE && (SubE->getType()->isPointerType() || 1285 SubE->getType()->isArrayType() || 1286 SubE->getType()->isFunctionType())) { 1287 unsigned IntWidth = Context.getTypeSize(Init->getType()); 1288 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy); 1289 if (IntWidth >= PointerWidth) 1290 return CheckAddressConstantExpression(Init); 1291 } 1292 } 1293 1294 return CheckArithmeticConstantExpression(Init); 1295 } 1296 1297 if (Init->getType()->isPointerType()) 1298 return CheckAddressConstantExpression(Init); 1299 1300 // An array type at the top level that isn't an init-list must 1301 // be a string literal 1302 if (Init->getType()->isArrayType()) 1303 return false; 1304 1305 Diag(Init->getExprLoc(), diag::err_init_element_not_constant, 1306 Init->getSourceRange()); 1307 return true; 1308} 1309 1310void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) { 1311 Decl *RealDecl = static_cast<Decl *>(dcl); 1312 Expr *Init = static_cast<Expr *>(init); 1313 assert(Init && "missing initializer"); 1314 1315 // If there is no declaration, there was an error parsing it. Just ignore 1316 // the initializer. 1317 if (RealDecl == 0) { 1318 delete Init; 1319 return; 1320 } 1321 1322 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 1323 if (!VDecl) { 1324 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(), 1325 diag::err_illegal_initializer); 1326 RealDecl->setInvalidDecl(); 1327 return; 1328 } 1329 // Get the decls type and save a reference for later, since 1330 // CheckInitializerTypes may change it. 1331 QualType DclT = VDecl->getType(), SavT = DclT; 1332 if (VDecl->isBlockVarDecl()) { 1333 VarDecl::StorageClass SC = VDecl->getStorageClass(); 1334 if (SC == VarDecl::Extern) { // C99 6.7.8p5 1335 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 1336 VDecl->setInvalidDecl(); 1337 } else if (!VDecl->isInvalidDecl()) { 1338 if (CheckInitializerTypes(Init, DclT)) 1339 VDecl->setInvalidDecl(); 1340 if (SC == VarDecl::Static) // C99 6.7.8p4. 1341 CheckForConstantInitializer(Init, DclT); 1342 } 1343 } else if (VDecl->isFileVarDecl()) { 1344 if (VDecl->getStorageClass() == VarDecl::Extern) 1345 Diag(VDecl->getLocation(), diag::warn_extern_init); 1346 if (!VDecl->isInvalidDecl()) 1347 if (CheckInitializerTypes(Init, DclT)) 1348 VDecl->setInvalidDecl(); 1349 1350 // C99 6.7.8p4. All file scoped initializers need to be constant. 1351 CheckForConstantInitializer(Init, DclT); 1352 } 1353 // If the type changed, it means we had an incomplete type that was 1354 // completed by the initializer. For example: 1355 // int ary[] = { 1, 3, 5 }; 1356 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 1357 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 1358 VDecl->setType(DclT); 1359 Init->setType(DclT); 1360 } 1361 1362 // Attach the initializer to the decl. 1363 VDecl->setInit(Init); 1364 return; 1365} 1366 1367/// The declarators are chained together backwards, reverse the list. 1368Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) { 1369 // Often we have single declarators, handle them quickly. 1370 Decl *GroupDecl = static_cast<Decl*>(group); 1371 if (GroupDecl == 0) 1372 return 0; 1373 1374 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl); 1375 ScopedDecl *NewGroup = 0; 1376 if (Group->getNextDeclarator() == 0) 1377 NewGroup = Group; 1378 else { // reverse the list. 1379 while (Group) { 1380 ScopedDecl *Next = Group->getNextDeclarator(); 1381 Group->setNextDeclarator(NewGroup); 1382 NewGroup = Group; 1383 Group = Next; 1384 } 1385 } 1386 // Perform semantic analysis that depends on having fully processed both 1387 // the declarator and initializer. 1388 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) { 1389 VarDecl *IDecl = dyn_cast<VarDecl>(ID); 1390 if (!IDecl) 1391 continue; 1392 QualType T = IDecl->getType(); 1393 1394 // C99 6.7.5.2p2: If an identifier is declared to be an object with 1395 // static storage duration, it shall not have a variable length array. 1396 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) && 1397 IDecl->getStorageClass() == VarDecl::Static) { 1398 if (T->isVariableArrayType()) { 1399 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla); 1400 IDecl->setInvalidDecl(); 1401 } 1402 } 1403 // Block scope. C99 6.7p7: If an identifier for an object is declared with 1404 // no linkage (C99 6.2.2p6), the type for the object shall be complete... 1405 if (IDecl->isBlockVarDecl() && 1406 IDecl->getStorageClass() != VarDecl::Extern) { 1407 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) { 1408 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type, 1409 T.getAsString()); 1410 IDecl->setInvalidDecl(); 1411 } 1412 } 1413 // File scope. C99 6.9.2p2: A declaration of an identifier for and 1414 // object that has file scope without an initializer, and without a 1415 // storage-class specifier or with the storage-class specifier "static", 1416 // constitutes a tentative definition. Note: A tentative definition with 1417 // external linkage is valid (C99 6.2.2p5). 1418 if (IDecl && !IDecl->getInit() && 1419 (IDecl->getStorageClass() == VarDecl::Static || 1420 IDecl->getStorageClass() == VarDecl::None)) { 1421 if (T->isIncompleteArrayType()) { 1422 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete 1423 // array to be completed. Don't issue a diagnostic. 1424 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) { 1425 // C99 6.9.2p3: If the declaration of an identifier for an object is 1426 // a tentative definition and has internal linkage (C99 6.2.2p3), the 1427 // declared type shall not be an incomplete type. 1428 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type, 1429 T.getAsString()); 1430 IDecl->setInvalidDecl(); 1431 } 1432 } 1433 } 1434 return NewGroup; 1435} 1436 1437/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 1438/// to introduce parameters into function prototype scope. 1439Sema::DeclTy * 1440Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 1441 const DeclSpec &DS = D.getDeclSpec(); 1442 1443 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 1444 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 1445 DS.getStorageClassSpec() != DeclSpec::SCS_register) { 1446 Diag(DS.getStorageClassSpecLoc(), 1447 diag::err_invalid_storage_class_in_func_decl); 1448 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1449 } 1450 if (DS.isThreadSpecified()) { 1451 Diag(DS.getThreadSpecLoc(), 1452 diag::err_invalid_storage_class_in_func_decl); 1453 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1454 } 1455 1456 // Check that there are no default arguments inside the type of this 1457 // parameter (C++ only). 1458 if (getLangOptions().CPlusPlus) 1459 CheckExtraCXXDefaultArguments(D); 1460 1461 // In this context, we *do not* check D.getInvalidType(). If the declarator 1462 // type was invalid, GetTypeForDeclarator() still returns a "valid" type, 1463 // though it will not reflect the user specified type. 1464 QualType parmDeclType = GetTypeForDeclarator(D, S); 1465 1466 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type"); 1467 1468 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 1469 // Can this happen for params? We already checked that they don't conflict 1470 // among each other. Here they can only shadow globals, which is ok. 1471 IdentifierInfo *II = D.getIdentifier(); 1472 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) { 1473 if (S->isDeclScope(PrevDecl)) { 1474 Diag(D.getIdentifierLoc(), diag::err_param_redefinition, 1475 dyn_cast<NamedDecl>(PrevDecl)->getName()); 1476 1477 // Recover by removing the name 1478 II = 0; 1479 D.SetIdentifier(0, D.getIdentifierLoc()); 1480 } 1481 } 1482 1483 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]). 1484 // Doing the promotion here has a win and a loss. The win is the type for 1485 // both Decl's and DeclRefExpr's will match (a convenient invariant for the 1486 // code generator). The loss is the orginal type isn't preserved. For example: 1487 // 1488 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *" 1489 // int blockvardecl[5]; 1490 // sizeof(parmvardecl); // size == 4 1491 // sizeof(blockvardecl); // size == 20 1492 // } 1493 // 1494 // For expressions, all implicit conversions are captured using the 1495 // ImplicitCastExpr AST node (we have no such mechanism for Decl's). 1496 // 1497 // FIXME: If a source translation tool needs to see the original type, then 1498 // we need to consider storing both types (in ParmVarDecl)... 1499 // 1500 if (parmDeclType->isArrayType()) { 1501 // int x[restrict 4] -> int *restrict 1502 parmDeclType = Context.getArrayDecayedType(parmDeclType); 1503 } else if (parmDeclType->isFunctionType()) 1504 parmDeclType = Context.getPointerType(parmDeclType); 1505 1506 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, 1507 D.getIdentifierLoc(), II, 1508 parmDeclType, VarDecl::None, 1509 0, 0); 1510 1511 if (D.getInvalidType()) 1512 New->setInvalidDecl(); 1513 1514 if (II) 1515 PushOnScopeChains(New, S); 1516 1517 ProcessDeclAttributes(New, D); 1518 return New; 1519 1520} 1521 1522Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 1523 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 1524 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 1525 "Not a function declarator!"); 1526 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1527 1528 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 1529 // for a K&R function. 1530 if (!FTI.hasPrototype) { 1531 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 1532 if (FTI.ArgInfo[i].Param == 0) { 1533 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared, 1534 FTI.ArgInfo[i].Ident->getName()); 1535 // Implicitly declare the argument as type 'int' for lack of a better 1536 // type. 1537 DeclSpec DS; 1538 const char* PrevSpec; // unused 1539 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 1540 PrevSpec); 1541 Declarator ParamD(DS, Declarator::KNRTypeListContext); 1542 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 1543 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD); 1544 } 1545 } 1546 1547 // Since this is a function definition, act as though we have information 1548 // about the arguments. 1549 if (FTI.NumArgs) 1550 FTI.hasPrototype = true; 1551 } else { 1552 // FIXME: Diagnose arguments without names in C. 1553 } 1554 1555 Scope *GlobalScope = FnBodyScope->getParent(); 1556 1557 // See if this is a redefinition. 1558 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary, 1559 GlobalScope); 1560 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) { 1561 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) { 1562 const FunctionDecl *Definition; 1563 if (FD->getBody(Definition)) { 1564 Diag(D.getIdentifierLoc(), diag::err_redefinition, 1565 D.getIdentifier()->getName()); 1566 Diag(Definition->getLocation(), diag::err_previous_definition); 1567 } 1568 } 1569 } 1570 1571 return ActOnStartOfFunctionDef(FnBodyScope, 1572 ActOnDeclarator(GlobalScope, D, 0)); 1573} 1574 1575Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) { 1576 Decl *decl = static_cast<Decl*>(D); 1577 FunctionDecl *FD = cast<FunctionDecl>(decl); 1578 PushDeclContext(FD); 1579 1580 // Check the validity of our function parameters 1581 CheckParmsForFunctionDef(FD); 1582 1583 // Introduce our parameters into the function scope 1584 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 1585 ParmVarDecl *Param = FD->getParamDecl(p); 1586 // If this has an identifier, add it to the scope stack. 1587 if (Param->getIdentifier()) 1588 PushOnScopeChains(Param, FnBodyScope); 1589 } 1590 1591 return FD; 1592} 1593 1594Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) { 1595 Decl *dcl = static_cast<Decl *>(D); 1596 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) { 1597 FD->setBody((Stmt*)Body); 1598 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 1599 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 1600 MD->setBody((Stmt*)Body); 1601 } else 1602 return 0; 1603 PopDeclContext(); 1604 // Verify and clean out per-function state. 1605 1606 // Check goto/label use. 1607 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 1608 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) { 1609 // Verify that we have no forward references left. If so, there was a goto 1610 // or address of a label taken, but no definition of it. Label fwd 1611 // definitions are indicated with a null substmt. 1612 if (I->second->getSubStmt() == 0) { 1613 LabelStmt *L = I->second; 1614 // Emit error. 1615 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName()); 1616 1617 // At this point, we have gotos that use the bogus label. Stitch it into 1618 // the function body so that they aren't leaked and that the AST is well 1619 // formed. 1620 if (Body) { 1621 L->setSubStmt(new NullStmt(L->getIdentLoc())); 1622 cast<CompoundStmt>((Stmt*)Body)->push_back(L); 1623 } else { 1624 // The whole function wasn't parsed correctly, just delete this. 1625 delete L; 1626 } 1627 } 1628 } 1629 LabelMap.clear(); 1630 1631 return D; 1632} 1633 1634/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 1635/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 1636ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 1637 IdentifierInfo &II, Scope *S) { 1638 // Extension in C99. Legal in C90, but warn about it. 1639 if (getLangOptions().C99) 1640 Diag(Loc, diag::ext_implicit_function_decl, II.getName()); 1641 else 1642 Diag(Loc, diag::warn_implicit_function_decl, II.getName()); 1643 1644 // FIXME: handle stuff like: 1645 // void foo() { extern float X(); } 1646 // void bar() { X(); } <-- implicit decl for X in another scope. 1647 1648 // Set a Declarator for the implicit definition: int foo(); 1649 const char *Dummy; 1650 DeclSpec DS; 1651 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy); 1652 Error = Error; // Silence warning. 1653 assert(!Error && "Error setting up implicit decl!"); 1654 Declarator D(DS, Declarator::BlockContext); 1655 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc)); 1656 D.SetIdentifier(&II, Loc); 1657 1658 // Insert this function into translation-unit scope. 1659 1660 DeclContext *PrevDC = CurContext; 1661 CurContext = Context.getTranslationUnitDecl(); 1662 1663 FunctionDecl *FD = 1664 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0))); 1665 FD->setImplicit(); 1666 1667 CurContext = PrevDC; 1668 1669 return FD; 1670} 1671 1672 1673TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 1674 ScopedDecl *LastDeclarator) { 1675 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 1676 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 1677 1678 // Scope manipulation handled by caller. 1679 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 1680 D.getIdentifierLoc(), 1681 D.getIdentifier(), 1682 T, LastDeclarator); 1683 if (D.getInvalidType()) 1684 NewTD->setInvalidDecl(); 1685 return NewTD; 1686} 1687 1688/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 1689/// former case, Name will be non-null. In the later case, Name will be null. 1690/// TagType indicates what kind of tag this is. TK indicates whether this is a 1691/// reference/declaration/definition of a tag. 1692Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK, 1693 SourceLocation KWLoc, IdentifierInfo *Name, 1694 SourceLocation NameLoc, AttributeList *Attr) { 1695 // If this is a use of an existing tag, it must have a name. 1696 assert((Name != 0 || TK == TK_Definition) && 1697 "Nameless record must be a definition!"); 1698 1699 TagDecl::TagKind Kind; 1700 switch (TagType) { 1701 default: assert(0 && "Unknown tag type!"); 1702 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 1703 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 1704 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 1705 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break; 1706 } 1707 1708 // If this is a named struct, check to see if there was a previous forward 1709 // declaration or definition. 1710 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up. 1711 if (ScopedDecl *PrevDecl = 1712 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S))) { 1713 1714 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) && 1715 "unexpected Decl type"); 1716 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 1717 // If this is a use of a previous tag, or if the tag is already declared 1718 // in the same scope (so that the definition/declaration completes or 1719 // rementions the tag), reuse the decl. 1720 if (TK == TK_Reference || 1721 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) { 1722 // Make sure that this wasn't declared as an enum and now used as a 1723 // struct or something similar. 1724 if (PrevTagDecl->getTagKind() != Kind) { 1725 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName()); 1726 Diag(PrevDecl->getLocation(), diag::err_previous_use); 1727 // Recover by making this an anonymous redefinition. 1728 Name = 0; 1729 PrevDecl = 0; 1730 } else { 1731 // If this is a use or a forward declaration, we're good. 1732 if (TK != TK_Definition) 1733 return PrevDecl; 1734 1735 // Diagnose attempts to redefine a tag. 1736 if (PrevTagDecl->isDefinition()) { 1737 Diag(NameLoc, diag::err_redefinition, Name->getName()); 1738 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 1739 // If this is a redefinition, recover by making this struct be 1740 // anonymous, which will make any later references get the previous 1741 // definition. 1742 Name = 0; 1743 } else { 1744 // Okay, this is definition of a previously declared or referenced 1745 // tag. Move the location of the decl to be the definition site. 1746 PrevDecl->setLocation(NameLoc); 1747 return PrevDecl; 1748 } 1749 } 1750 } 1751 // If we get here, this is a definition of a new struct type in a nested 1752 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new 1753 // type. 1754 } else { 1755 // PrevDecl is a namespace. 1756 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) { 1757 // The tag name clashes with a namespace name, issue an error and recover 1758 // by making this tag be anonymous. 1759 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName()); 1760 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 1761 Name = 0; 1762 } 1763 } 1764 } 1765 1766 // If there is an identifier, use the location of the identifier as the 1767 // location of the decl, otherwise use the location of the struct/union 1768 // keyword. 1769 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 1770 1771 // Otherwise, if this is the first time we've seen this tag, create the decl. 1772 TagDecl *New; 1773 if (Kind == TagDecl::TK_enum) { 1774 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 1775 // enum X { A, B, C } D; D should chain to X. 1776 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0); 1777 // If this is an undefined enum, warn. 1778 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum); 1779 } else { 1780 // struct/union/class 1781 1782 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 1783 // struct X { int A; } D; D should chain to X. 1784 if (getLangOptions().CPlusPlus) 1785 // FIXME: Look for a way to use RecordDecl for simple structs. 1786 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0); 1787 else 1788 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 0); 1789 } 1790 1791 // If this has an identifier, add it to the scope stack. 1792 if (Name) { 1793 // The scope passed in may not be a decl scope. Zip up the scope tree until 1794 // we find one that is. 1795 while ((S->getFlags() & Scope::DeclScope) == 0) 1796 S = S->getParent(); 1797 1798 // Add it to the decl chain. 1799 PushOnScopeChains(New, S); 1800 } 1801 1802 if (Attr) 1803 ProcessDeclAttributeList(New, Attr); 1804 return New; 1805} 1806 1807/// Collect the instance variables declared in an Objective-C object. Used in 1808/// the creation of structures from objects using the @defs directive. 1809static void CollectIvars(ObjCInterfaceDecl *Class, 1810 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) { 1811 if (Class->getSuperClass()) 1812 CollectIvars(Class->getSuperClass(), ivars); 1813 ivars.append(Class->ivar_begin(), Class->ivar_end()); 1814} 1815 1816/// Called whenever @defs(ClassName) is encountered in the source. Inserts the 1817/// instance variables of ClassName into Decls. 1818void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart, 1819 IdentifierInfo *ClassName, 1820 llvm::SmallVectorImpl<DeclTy*> &Decls) { 1821 // Check that ClassName is a valid class 1822 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName); 1823 if (!Class) { 1824 Diag(DeclStart, diag::err_undef_interface, ClassName->getName()); 1825 return; 1826 } 1827 // Collect the instance variables 1828 CollectIvars(Class, Decls); 1829} 1830 1831QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) { 1832 // This method tries to turn a variable array into a constant 1833 // array even when the size isn't an ICE. This is necessary 1834 // for compatibility with code that depends on gcc's buggy 1835 // constant expression folding, like struct {char x[(int)(char*)2];} 1836 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) { 1837 APValue Result; 1838 if (VLATy->getSizeExpr() && 1839 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) { 1840 llvm::APSInt &Res = Result.getInt(); 1841 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) 1842 return Context.getConstantArrayType(VLATy->getElementType(), 1843 Res, ArrayType::Normal, 0); 1844 } 1845 } 1846 return QualType(); 1847} 1848 1849/// ActOnField - Each field of a struct/union/class is passed into this in order 1850/// to create a FieldDecl object for it. 1851Sema::DeclTy *Sema::ActOnField(Scope *S, 1852 SourceLocation DeclStart, 1853 Declarator &D, ExprTy *BitfieldWidth) { 1854 IdentifierInfo *II = D.getIdentifier(); 1855 Expr *BitWidth = (Expr*)BitfieldWidth; 1856 SourceLocation Loc = DeclStart; 1857 if (II) Loc = D.getIdentifierLoc(); 1858 1859 // FIXME: Unnamed fields can be handled in various different ways, for 1860 // example, unnamed unions inject all members into the struct namespace! 1861 1862 1863 if (BitWidth) { 1864 // TODO: Validate. 1865 //printf("WARNING: BITFIELDS IGNORED!\n"); 1866 1867 // 6.7.2.1p3 1868 // 6.7.2.1p4 1869 1870 } else { 1871 // Not a bitfield. 1872 1873 // validate II. 1874 1875 } 1876 1877 QualType T = GetTypeForDeclarator(D, S); 1878 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 1879 bool InvalidDecl = false; 1880 1881 // C99 6.7.2.1p8: A member of a structure or union may have any type other 1882 // than a variably modified type. 1883 if (T->isVariablyModifiedType()) { 1884 QualType FixedTy = TryFixInvalidVariablyModifiedType(T); 1885 if (!FixedTy.isNull()) { 1886 Diag(Loc, diag::warn_illegal_constant_array_size, Loc); 1887 T = FixedTy; 1888 } else { 1889 // FIXME: This diagnostic needs work 1890 Diag(Loc, diag::err_typecheck_illegal_vla, Loc); 1891 InvalidDecl = true; 1892 } 1893 } 1894 // FIXME: Chain fielddecls together. 1895 FieldDecl *NewFD; 1896 1897 if (getLangOptions().CPlusPlus) { 1898 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs. 1899 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext), 1900 Loc, II, T, BitWidth); 1901 if (II) 1902 PushOnScopeChains(NewFD, S); 1903 } 1904 else 1905 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth); 1906 1907 ProcessDeclAttributes(NewFD, D); 1908 1909 if (D.getInvalidType() || InvalidDecl) 1910 NewFD->setInvalidDecl(); 1911 return NewFD; 1912} 1913 1914/// TranslateIvarVisibility - Translate visibility from a token ID to an 1915/// AST enum value. 1916static ObjCIvarDecl::AccessControl 1917TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 1918 switch (ivarVisibility) { 1919 case tok::objc_private: return ObjCIvarDecl::Private; 1920 case tok::objc_public: return ObjCIvarDecl::Public; 1921 case tok::objc_protected: return ObjCIvarDecl::Protected; 1922 case tok::objc_package: return ObjCIvarDecl::Package; 1923 default: assert(false && "Unknown visitibility kind"); 1924 } 1925} 1926 1927/// ActOnIvar - Each ivar field of an objective-c class is passed into this 1928/// in order to create an IvarDecl object for it. 1929Sema::DeclTy *Sema::ActOnIvar(Scope *S, 1930 SourceLocation DeclStart, 1931 Declarator &D, ExprTy *BitfieldWidth, 1932 tok::ObjCKeywordKind Visibility) { 1933 IdentifierInfo *II = D.getIdentifier(); 1934 Expr *BitWidth = (Expr*)BitfieldWidth; 1935 SourceLocation Loc = DeclStart; 1936 if (II) Loc = D.getIdentifierLoc(); 1937 1938 // FIXME: Unnamed fields can be handled in various different ways, for 1939 // example, unnamed unions inject all members into the struct namespace! 1940 1941 1942 if (BitWidth) { 1943 // TODO: Validate. 1944 //printf("WARNING: BITFIELDS IGNORED!\n"); 1945 1946 // 6.7.2.1p3 1947 // 6.7.2.1p4 1948 1949 } else { 1950 // Not a bitfield. 1951 1952 // validate II. 1953 1954 } 1955 1956 QualType T = GetTypeForDeclarator(D, S); 1957 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 1958 bool InvalidDecl = false; 1959 1960 // C99 6.7.2.1p8: A member of a structure or union may have any type other 1961 // than a variably modified type. 1962 if (T->isVariablyModifiedType()) { 1963 // FIXME: This diagnostic needs work 1964 Diag(Loc, diag::err_typecheck_illegal_vla, Loc); 1965 InvalidDecl = true; 1966 } 1967 1968 // Get the visibility (access control) for this ivar. 1969 ObjCIvarDecl::AccessControl ac = 1970 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 1971 : ObjCIvarDecl::None; 1972 1973 // Construct the decl. 1974 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac, 1975 (Expr *)BitfieldWidth); 1976 1977 // Process attributes attached to the ivar. 1978 ProcessDeclAttributes(NewID, D); 1979 1980 if (D.getInvalidType() || InvalidDecl) 1981 NewID->setInvalidDecl(); 1982 1983 return NewID; 1984} 1985 1986void Sema::ActOnFields(Scope* S, 1987 SourceLocation RecLoc, DeclTy *RecDecl, 1988 DeclTy **Fields, unsigned NumFields, 1989 SourceLocation LBrac, SourceLocation RBrac) { 1990 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl); 1991 assert(EnclosingDecl && "missing record or interface decl"); 1992 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 1993 1994 if (Record && Record->isDefinition()) { 1995 // Diagnose code like: 1996 // struct S { struct S {} X; }; 1997 // We discover this when we complete the outer S. Reject and ignore the 1998 // outer S. 1999 Diag(Record->getLocation(), diag::err_nested_redefinition, 2000 Record->getKindName()); 2001 Diag(RecLoc, diag::err_previous_definition); 2002 Record->setInvalidDecl(); 2003 return; 2004 } 2005 // Verify that all the fields are okay. 2006 unsigned NumNamedMembers = 0; 2007 llvm::SmallVector<FieldDecl*, 32> RecFields; 2008 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs; 2009 2010 for (unsigned i = 0; i != NumFields; ++i) { 2011 2012 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i])); 2013 assert(FD && "missing field decl"); 2014 2015 // Remember all fields. 2016 RecFields.push_back(FD); 2017 2018 // Get the type for the field. 2019 Type *FDTy = FD->getType().getTypePtr(); 2020 2021 // C99 6.7.2.1p2 - A field may not be a function type. 2022 if (FDTy->isFunctionType()) { 2023 Diag(FD->getLocation(), diag::err_field_declared_as_function, 2024 FD->getName()); 2025 FD->setInvalidDecl(); 2026 EnclosingDecl->setInvalidDecl(); 2027 continue; 2028 } 2029 // C99 6.7.2.1p2 - A field may not be an incomplete type except... 2030 if (FDTy->isIncompleteType()) { 2031 if (!Record) { // Incomplete ivar type is always an error. 2032 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName()); 2033 FD->setInvalidDecl(); 2034 EnclosingDecl->setInvalidDecl(); 2035 continue; 2036 } 2037 if (i != NumFields-1 || // ... that the last member ... 2038 !Record->isStruct() || // ... of a structure ... 2039 !FDTy->isArrayType()) { //... may have incomplete array type. 2040 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName()); 2041 FD->setInvalidDecl(); 2042 EnclosingDecl->setInvalidDecl(); 2043 continue; 2044 } 2045 if (NumNamedMembers < 1) { //... must have more than named member ... 2046 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct, 2047 FD->getName()); 2048 FD->setInvalidDecl(); 2049 EnclosingDecl->setInvalidDecl(); 2050 continue; 2051 } 2052 // Okay, we have a legal flexible array member at the end of the struct. 2053 if (Record) 2054 Record->setHasFlexibleArrayMember(true); 2055 } 2056 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the 2057 /// field of another structure or the element of an array. 2058 if (const RecordType *FDTTy = FDTy->getAsRecordType()) { 2059 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 2060 // If this is a member of a union, then entire union becomes "flexible". 2061 if (Record && Record->isUnion()) { 2062 Record->setHasFlexibleArrayMember(true); 2063 } else { 2064 // If this is a struct/class and this is not the last element, reject 2065 // it. Note that GCC supports variable sized arrays in the middle of 2066 // structures. 2067 if (i != NumFields-1) { 2068 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct, 2069 FD->getName()); 2070 FD->setInvalidDecl(); 2071 EnclosingDecl->setInvalidDecl(); 2072 continue; 2073 } 2074 // We support flexible arrays at the end of structs in other structs 2075 // as an extension. 2076 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct, 2077 FD->getName()); 2078 if (Record) 2079 Record->setHasFlexibleArrayMember(true); 2080 } 2081 } 2082 } 2083 /// A field cannot be an Objective-c object 2084 if (FDTy->isObjCInterfaceType()) { 2085 Diag(FD->getLocation(), diag::err_statically_allocated_object, 2086 FD->getName()); 2087 FD->setInvalidDecl(); 2088 EnclosingDecl->setInvalidDecl(); 2089 continue; 2090 } 2091 // Keep track of the number of named members. 2092 if (IdentifierInfo *II = FD->getIdentifier()) { 2093 // Detect duplicate member names. 2094 if (!FieldIDs.insert(II)) { 2095 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName()); 2096 // Find the previous decl. 2097 SourceLocation PrevLoc; 2098 for (unsigned i = 0, e = RecFields.size(); ; ++i) { 2099 assert(i != e && "Didn't find previous def!"); 2100 if (RecFields[i]->getIdentifier() == II) { 2101 PrevLoc = RecFields[i]->getLocation(); 2102 break; 2103 } 2104 } 2105 Diag(PrevLoc, diag::err_previous_definition); 2106 FD->setInvalidDecl(); 2107 EnclosingDecl->setInvalidDecl(); 2108 continue; 2109 } 2110 ++NumNamedMembers; 2111 } 2112 } 2113 2114 // Okay, we successfully defined 'Record'. 2115 if (Record) { 2116 Record->defineBody(&RecFields[0], RecFields.size()); 2117 Consumer.HandleTagDeclDefinition(Record); 2118 } else { 2119 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]); 2120 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) 2121 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac); 2122 else if (ObjCImplementationDecl *IMPDecl = 2123 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 2124 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 2125 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size()); 2126 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 2127 } 2128 } 2129} 2130 2131Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl, 2132 DeclTy *lastEnumConst, 2133 SourceLocation IdLoc, IdentifierInfo *Id, 2134 SourceLocation EqualLoc, ExprTy *val) { 2135 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl)); 2136 EnumConstantDecl *LastEnumConst = 2137 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst)); 2138 Expr *Val = static_cast<Expr*>(val); 2139 2140 // The scope passed in may not be a decl scope. Zip up the scope tree until 2141 // we find one that is. 2142 while ((S->getFlags() & Scope::DeclScope) == 0) 2143 S = S->getParent(); 2144 2145 // Verify that there isn't already something declared with this name in this 2146 // scope. 2147 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) { 2148 // When in C++, we may get a TagDecl with the same name; in this case the 2149 // enum constant will 'hide' the tag. 2150 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 2151 "Received TagDecl when not in C++!"); 2152 if (!isa<TagDecl>(PrevDecl) && 2153 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) { 2154 if (isa<EnumConstantDecl>(PrevDecl)) 2155 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName()); 2156 else 2157 Diag(IdLoc, diag::err_redefinition, Id->getName()); 2158 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 2159 delete Val; 2160 return 0; 2161 } 2162 } 2163 2164 llvm::APSInt EnumVal(32); 2165 QualType EltTy; 2166 if (Val) { 2167 // Make sure to promote the operand type to int. 2168 UsualUnaryConversions(Val); 2169 2170 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 2171 SourceLocation ExpLoc; 2172 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) { 2173 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr, 2174 Id->getName()); 2175 delete Val; 2176 Val = 0; // Just forget about it. 2177 } else { 2178 EltTy = Val->getType(); 2179 } 2180 } 2181 2182 if (!Val) { 2183 if (LastEnumConst) { 2184 // Assign the last value + 1. 2185 EnumVal = LastEnumConst->getInitVal(); 2186 ++EnumVal; 2187 2188 // Check for overflow on increment. 2189 if (EnumVal < LastEnumConst->getInitVal()) 2190 Diag(IdLoc, diag::warn_enum_value_overflow); 2191 2192 EltTy = LastEnumConst->getType(); 2193 } else { 2194 // First value, set to zero. 2195 EltTy = Context.IntTy; 2196 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy))); 2197 } 2198 } 2199 2200 EnumConstantDecl *New = 2201 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy, 2202 Val, EnumVal, 2203 LastEnumConst); 2204 2205 // Register this decl in the current scope stack. 2206 PushOnScopeChains(New, S); 2207 return New; 2208} 2209 2210void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX, 2211 DeclTy **Elements, unsigned NumElements) { 2212 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX)); 2213 assert(!Enum->isDefinition() && "Enum redefinitions can't reach here"); 2214 2215 // TODO: If the result value doesn't fit in an int, it must be a long or long 2216 // long value. ISO C does not support this, but GCC does as an extension, 2217 // emit a warning. 2218 unsigned IntWidth = Context.Target.getIntWidth(); 2219 2220 // Verify that all the values are okay, compute the size of the values, and 2221 // reverse the list. 2222 unsigned NumNegativeBits = 0; 2223 unsigned NumPositiveBits = 0; 2224 2225 // Keep track of whether all elements have type int. 2226 bool AllElementsInt = true; 2227 2228 EnumConstantDecl *EltList = 0; 2229 for (unsigned i = 0; i != NumElements; ++i) { 2230 EnumConstantDecl *ECD = 2231 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 2232 if (!ECD) continue; // Already issued a diagnostic. 2233 2234 // If the enum value doesn't fit in an int, emit an extension warning. 2235 const llvm::APSInt &InitVal = ECD->getInitVal(); 2236 assert(InitVal.getBitWidth() >= IntWidth && 2237 "Should have promoted value to int"); 2238 if (InitVal.getBitWidth() > IntWidth) { 2239 llvm::APSInt V(InitVal); 2240 V.trunc(IntWidth); 2241 V.extend(InitVal.getBitWidth()); 2242 if (V != InitVal) 2243 Diag(ECD->getLocation(), diag::ext_enum_value_not_int, 2244 InitVal.toString()); 2245 } 2246 2247 // Keep track of the size of positive and negative values. 2248 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 2249 NumPositiveBits = std::max(NumPositiveBits, 2250 (unsigned)InitVal.getActiveBits()); 2251 else 2252 NumNegativeBits = std::max(NumNegativeBits, 2253 (unsigned)InitVal.getMinSignedBits()); 2254 2255 // Keep track of whether every enum element has type int (very commmon). 2256 if (AllElementsInt) 2257 AllElementsInt = ECD->getType() == Context.IntTy; 2258 2259 ECD->setNextDeclarator(EltList); 2260 EltList = ECD; 2261 } 2262 2263 // Figure out the type that should be used for this enum. 2264 // FIXME: Support attribute(packed) on enums and -fshort-enums. 2265 QualType BestType; 2266 unsigned BestWidth; 2267 2268 if (NumNegativeBits) { 2269 // If there is a negative value, figure out the smallest integer type (of 2270 // int/long/longlong) that fits. 2271 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 2272 BestType = Context.IntTy; 2273 BestWidth = IntWidth; 2274 } else { 2275 BestWidth = Context.Target.getLongWidth(); 2276 2277 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) 2278 BestType = Context.LongTy; 2279 else { 2280 BestWidth = Context.Target.getLongLongWidth(); 2281 2282 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 2283 Diag(Enum->getLocation(), diag::warn_enum_too_large); 2284 BestType = Context.LongLongTy; 2285 } 2286 } 2287 } else { 2288 // If there is no negative value, figure out which of uint, ulong, ulonglong 2289 // fits. 2290 if (NumPositiveBits <= IntWidth) { 2291 BestType = Context.UnsignedIntTy; 2292 BestWidth = IntWidth; 2293 } else if (NumPositiveBits <= 2294 (BestWidth = Context.Target.getLongWidth())) { 2295 BestType = Context.UnsignedLongTy; 2296 } else { 2297 BestWidth = Context.Target.getLongLongWidth(); 2298 assert(NumPositiveBits <= BestWidth && 2299 "How could an initializer get larger than ULL?"); 2300 BestType = Context.UnsignedLongLongTy; 2301 } 2302 } 2303 2304 // Loop over all of the enumerator constants, changing their types to match 2305 // the type of the enum if needed. 2306 for (unsigned i = 0; i != NumElements; ++i) { 2307 EnumConstantDecl *ECD = 2308 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 2309 if (!ECD) continue; // Already issued a diagnostic. 2310 2311 // Standard C says the enumerators have int type, but we allow, as an 2312 // extension, the enumerators to be larger than int size. If each 2313 // enumerator value fits in an int, type it as an int, otherwise type it the 2314 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 2315 // that X has type 'int', not 'unsigned'. 2316 if (ECD->getType() == Context.IntTy) { 2317 // Make sure the init value is signed. 2318 llvm::APSInt IV = ECD->getInitVal(); 2319 IV.setIsSigned(true); 2320 ECD->setInitVal(IV); 2321 continue; // Already int type. 2322 } 2323 2324 // Determine whether the value fits into an int. 2325 llvm::APSInt InitVal = ECD->getInitVal(); 2326 bool FitsInInt; 2327 if (InitVal.isUnsigned() || !InitVal.isNegative()) 2328 FitsInInt = InitVal.getActiveBits() < IntWidth; 2329 else 2330 FitsInInt = InitVal.getMinSignedBits() <= IntWidth; 2331 2332 // If it fits into an integer type, force it. Otherwise force it to match 2333 // the enum decl type. 2334 QualType NewTy; 2335 unsigned NewWidth; 2336 bool NewSign; 2337 if (FitsInInt) { 2338 NewTy = Context.IntTy; 2339 NewWidth = IntWidth; 2340 NewSign = true; 2341 } else if (ECD->getType() == BestType) { 2342 // Already the right type! 2343 continue; 2344 } else { 2345 NewTy = BestType; 2346 NewWidth = BestWidth; 2347 NewSign = BestType->isSignedIntegerType(); 2348 } 2349 2350 // Adjust the APSInt value. 2351 InitVal.extOrTrunc(NewWidth); 2352 InitVal.setIsSigned(NewSign); 2353 ECD->setInitVal(InitVal); 2354 2355 // Adjust the Expr initializer and type. 2356 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr())); 2357 ECD->setType(NewTy); 2358 } 2359 2360 Enum->defineElements(EltList, BestType); 2361 Consumer.HandleTagDeclDefinition(Enum); 2362} 2363 2364Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, 2365 ExprTy *expr) { 2366 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr); 2367 2368 return FileScopeAsmDecl::Create(Context, Loc, AsmString); 2369} 2370 2371Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc, 2372 SourceLocation LBrace, 2373 SourceLocation RBrace, 2374 const char *Lang, 2375 unsigned StrSize, 2376 DeclTy *D) { 2377 LinkageSpecDecl::LanguageIDs Language; 2378 Decl *dcl = static_cast<Decl *>(D); 2379 if (strncmp(Lang, "\"C\"", StrSize) == 0) 2380 Language = LinkageSpecDecl::lang_c; 2381 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 2382 Language = LinkageSpecDecl::lang_cxx; 2383 else { 2384 Diag(Loc, diag::err_bad_language); 2385 return 0; 2386 } 2387 2388 // FIXME: Add all the various semantics of linkage specifications 2389 return LinkageSpecDecl::Create(Context, Loc, Language, dcl); 2390} 2391