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