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