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