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