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