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