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