SemaDecl.cpp revision ba3e8b753a3e2262877f0f10c2977be51aef7c65
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/APValue.h" 16#include "clang/AST/ASTConsumer.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/DeclObjC.h" 19#include "clang/AST/ExprCXX.h" 20#include "clang/Parse/DeclSpec.h" 21#include "clang/Basic/Diagnostic.h" 22#include "clang/Basic/TargetInfo.h" 23#include "clang/Basic/SourceManager.h" 24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's) 25#include "clang/Lex/Preprocessor.h" 26#include "clang/Lex/HeaderSearch.h" 27#include "llvm/ADT/SmallSet.h" 28#include "llvm/ADT/StringExtras.h" 29using namespace clang; 30 31Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) { 32 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false); 33 34 if (IIDecl && (isa<TypedefDecl>(IIDecl) || 35 isa<ObjCInterfaceDecl>(IIDecl) || 36 isa<TagDecl>(IIDecl))) 37 return IIDecl; 38 return 0; 39} 40 41DeclContext *Sema::getDCParent(DeclContext *DC) { 42 // If CurContext is a ObjC method, getParent() will return NULL. 43 if (isa<ObjCMethodDecl>(DC)) 44 return Context.getTranslationUnitDecl(); 45 46 // A C++ inline method is parsed *after* the topmost class it was declared in 47 // is fully parsed (it's "complete"). 48 // The parsing of a C++ inline method happens at the declaration context of 49 // the topmost (non-nested) class it is declared in. 50 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) { 51 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record."); 52 DC = MD->getParent(); 53 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 54 DC = RD; 55 56 // Return the declaration context of the topmost class the inline method is 57 // declared in. 58 return DC; 59 } 60 61 return DC->getParent(); 62} 63 64void Sema::PushDeclContext(DeclContext *DC) { 65 assert(getDCParent(DC) == CurContext && 66 "The next DeclContext should be directly contained in the current one."); 67 CurContext = DC; 68} 69 70void Sema::PopDeclContext() { 71 assert(CurContext && "DeclContext imbalance!"); 72 CurContext = getDCParent(CurContext); 73} 74 75/// Add this decl to the scope shadowed decl chains. 76void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) { 77 S->AddDecl(D); 78 79 // C++ [basic.scope]p4: 80 // -- exactly one declaration shall declare a class name or 81 // enumeration name that is not a typedef name and the other 82 // declarations shall all refer to the same object or 83 // enumerator, or all refer to functions and function templates; 84 // in this case the class name or enumeration name is hidden. 85 if (TagDecl *TD = dyn_cast<TagDecl>(D)) { 86 // We are pushing the name of a tag (enum or class). 87 IdentifierResolver::iterator 88 I = IdResolver.begin(TD->getIdentifier(), 89 TD->getDeclContext(), false/*LookInParentCtx*/); 90 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) { 91 // There is already a declaration with the same name in the same 92 // scope. It must be found before we find the new declaration, 93 // so swap the order on the shadowed declaration chain. 94 95 IdResolver.AddShadowedDecl(TD, *I); 96 return; 97 } 98 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) { 99 FunctionDecl *FD = cast<FunctionDecl>(D); 100 // We are pushing the name of a function, which might be an 101 // overloaded name. 102 IdentifierResolver::iterator 103 I = IdResolver.begin(FD->getIdentifier(), 104 FD->getDeclContext(), false/*LookInParentCtx*/); 105 if (I != IdResolver.end() && 106 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) && 107 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) { 108 // There is already a declaration with the same name in the same 109 // scope. It must be a function or an overloaded function. 110 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I); 111 if (!Ovl) { 112 // We haven't yet overloaded this function. Take the existing 113 // FunctionDecl and put it into an OverloadedFunctionDecl. 114 Ovl = OverloadedFunctionDecl::Create(Context, 115 FD->getDeclContext(), 116 FD->getIdentifier()); 117 Ovl->addOverload(dyn_cast<FunctionDecl>(*I)); 118 119 // Remove the name binding to the existing FunctionDecl... 120 IdResolver.RemoveDecl(*I); 121 122 // ... and put the OverloadedFunctionDecl in its place. 123 IdResolver.AddDecl(Ovl); 124 } 125 126 // We have an OverloadedFunctionDecl. Add the new FunctionDecl 127 // to its list of overloads. 128 Ovl->addOverload(FD); 129 130 return; 131 } 132 } 133 134 IdResolver.AddDecl(D); 135} 136 137void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 138 if (S->decl_empty()) return; 139 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!"); 140 141 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 142 I != E; ++I) { 143 Decl *TmpD = static_cast<Decl*>(*I); 144 assert(TmpD && "This decl didn't get pushed??"); 145 146 if (isa<CXXFieldDecl>(TmpD)) continue; 147 148 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?"); 149 ScopedDecl *D = cast<ScopedDecl>(TmpD); 150 151 IdentifierInfo *II = D->getIdentifier(); 152 if (!II) continue; 153 154 // We only want to remove the decls from the identifier decl chains for 155 // local scopes, when inside a function/method. 156 if (S->getFnParent() != 0) 157 IdResolver.RemoveDecl(D); 158 159 // Chain this decl to the containing DeclContext. 160 D->setNext(CurContext->getDeclChain()); 161 CurContext->setDeclChain(D); 162 } 163} 164 165/// getObjCInterfaceDecl - Look up a for a class declaration in the scope. 166/// return 0 if one not found. 167ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) { 168 // The third "scope" argument is 0 since we aren't enabling lazy built-in 169 // creation from this context. 170 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false); 171 172 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 173} 174 175/// LookupDecl - Look up the inner-most declaration in the specified 176/// namespace. 177Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI, 178 Scope *S, bool enableLazyBuiltinCreation) { 179 if (II == 0) return 0; 180 unsigned NS = NSI; 181 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary)) 182 NS |= Decl::IDNS_Tag; 183 184 // Scan up the scope chain looking for a decl that matches this identifier 185 // that is in the appropriate namespace. This search should not take long, as 186 // shadowing of names is uncommon, and deep shadowing is extremely uncommon. 187 for (IdentifierResolver::iterator 188 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I) 189 if ((*I)->getIdentifierNamespace() & NS) 190 return *I; 191 192 // If we didn't find a use of this identifier, and if the identifier 193 // corresponds to a compiler builtin, create the decl object for the builtin 194 // now, injecting it into translation unit scope, and return it. 195 if (NS & Decl::IDNS_Ordinary) { 196 if (enableLazyBuiltinCreation) { 197 // If this is a builtin on this (or all) targets, create the decl. 198 if (unsigned BuiltinID = II->getBuiltinID()) 199 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S); 200 } 201 if (getLangOptions().ObjC1) { 202 // @interface and @compatibility_alias introduce typedef-like names. 203 // Unlike typedef's, they can only be introduced at file-scope (and are 204 // therefore not scoped decls). They can, however, be shadowed by 205 // other names in IDNS_Ordinary. 206 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II); 207 if (IDI != ObjCInterfaceDecls.end()) 208 return IDI->second; 209 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II); 210 if (I != ObjCAliasDecls.end()) 211 return I->second->getClassInterface(); 212 } 213 } 214 return 0; 215} 216 217void Sema::InitBuiltinVaListType() { 218 if (!Context.getBuiltinVaListType().isNull()) 219 return; 220 221 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list"); 222 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope); 223 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl); 224 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef)); 225} 226 227/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope. 228/// lazily create a decl for it. 229ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 230 Scope *S) { 231 Builtin::ID BID = (Builtin::ID)bid; 232 233 if (Context.BuiltinInfo.hasVAListUse(BID)) 234 InitBuiltinVaListType(); 235 236 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context); 237 FunctionDecl *New = FunctionDecl::Create(Context, 238 Context.getTranslationUnitDecl(), 239 SourceLocation(), II, R, 240 FunctionDecl::Extern, false, 0); 241 242 // Create Decl objects for each parameter, adding them to the 243 // FunctionDecl. 244 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) { 245 llvm::SmallVector<ParmVarDecl*, 16> Params; 246 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) 247 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0, 248 FT->getArgType(i), VarDecl::None, 0, 249 0)); 250 New->setParams(&Params[0], Params.size()); 251 } 252 253 254 255 // TUScope is the translation-unit scope to insert this function into. 256 PushOnScopeChains(New, TUScope); 257 return New; 258} 259 260/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name 261/// and scope as a previous declaration 'Old'. Figure out how to resolve this 262/// situation, merging decls or emitting diagnostics as appropriate. 263/// 264TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) { 265 // Allow multiple definitions for ObjC built-in typedefs. 266 // FIXME: Verify the underlying types are equivalent! 267 if (getLangOptions().ObjC1) { 268 const IdentifierInfo *typeIdent = New->getIdentifier(); 269 if (typeIdent == Ident_id) { 270 Context.setObjCIdType(New); 271 return New; 272 } else if (typeIdent == Ident_Class) { 273 Context.setObjCClassType(New); 274 return New; 275 } else if (typeIdent == Ident_SEL) { 276 Context.setObjCSelType(New); 277 return New; 278 } else if (typeIdent == Ident_Protocol) { 279 Context.setObjCProtoType(New->getUnderlyingType()); 280 return New; 281 } 282 // Fall through - the typedef name was not a builtin type. 283 } 284 // Verify the old decl was also a typedef. 285 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD); 286 if (!Old) { 287 Diag(New->getLocation(), diag::err_redefinition_different_kind, 288 New->getName()); 289 Diag(OldD->getLocation(), diag::err_previous_definition); 290 return New; 291 } 292 293 // If the typedef types are not identical, reject them in all languages and 294 // with any extensions enabled. 295 if (Old->getUnderlyingType() != New->getUnderlyingType() && 296 Context.getCanonicalType(Old->getUnderlyingType()) != 297 Context.getCanonicalType(New->getUnderlyingType())) { 298 Diag(New->getLocation(), diag::err_redefinition_different_typedef, 299 New->getUnderlyingType().getAsString(), 300 Old->getUnderlyingType().getAsString()); 301 Diag(Old->getLocation(), diag::err_previous_definition); 302 return Old; 303 } 304 305 if (getLangOptions().Microsoft) return New; 306 307 // Redeclaration of a type is a constraint violation (6.7.2.3p1). 308 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if 309 // *either* declaration is in a system header. The code below implements 310 // this adhoc compatibility rule. FIXME: The following code will not 311 // work properly when compiling ".i" files (containing preprocessed output). 312 if (PP.getDiagnostics().getSuppressSystemWarnings()) { 313 SourceManager &SrcMgr = Context.getSourceManager(); 314 if (SrcMgr.isInSystemHeader(Old->getLocation())) 315 return New; 316 if (SrcMgr.isInSystemHeader(New->getLocation())) 317 return New; 318 } 319 320 Diag(New->getLocation(), diag::err_redefinition, New->getName()); 321 Diag(Old->getLocation(), diag::err_previous_definition); 322 return New; 323} 324 325/// DeclhasAttr - returns true if decl Declaration already has the target 326/// attribute. 327static bool DeclHasAttr(const Decl *decl, const Attr *target) { 328 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext()) 329 if (attr->getKind() == target->getKind()) 330 return true; 331 332 return false; 333} 334 335/// MergeAttributes - append attributes from the Old decl to the New one. 336static void MergeAttributes(Decl *New, Decl *Old) { 337 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp; 338 339 while (attr) { 340 tmp = attr; 341 attr = attr->getNext(); 342 343 if (!DeclHasAttr(New, tmp)) { 344 New->addAttr(tmp); 345 } else { 346 tmp->setNext(0); 347 delete(tmp); 348 } 349 } 350 351 Old->invalidateAttrs(); 352} 353 354/// MergeFunctionDecl - We just parsed a function 'New' from 355/// declarator D which has the same name and scope as a previous 356/// declaration 'Old'. Figure out how to resolve this situation, 357/// merging decls or emitting diagnostics as appropriate. 358/// Redeclaration will be set true if this New is a redeclaration OldD. 359/// 360/// In C++, New and Old must be declarations that are not 361/// overloaded. Use IsOverload to determine whether New and Old are 362/// overloaded, and to select the Old declaration that New should be 363/// merged with. 364FunctionDecl * 365Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) { 366 assert(!isa<OverloadedFunctionDecl>(OldD) && 367 "Cannot merge with an overloaded function declaration"); 368 369 Redeclaration = false; 370 // Verify the old decl was also a function. 371 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD); 372 if (!Old) { 373 Diag(New->getLocation(), diag::err_redefinition_different_kind, 374 New->getName()); 375 Diag(OldD->getLocation(), diag::err_previous_definition); 376 return New; 377 } 378 379 // Determine whether the previous declaration was a definition, 380 // implicit declaration, or a declaration. 381 diag::kind PrevDiag; 382 if (Old->isThisDeclarationADefinition()) 383 PrevDiag = diag::err_previous_definition; 384 else if (Old->isImplicit()) 385 PrevDiag = diag::err_previous_implicit_declaration; 386 else 387 PrevDiag = diag::err_previous_declaration; 388 389 QualType OldQType = Context.getCanonicalType(Old->getType()); 390 QualType NewQType = Context.getCanonicalType(New->getType()); 391 392 if (getLangOptions().CPlusPlus) { 393 // (C++98 13.1p2): 394 // Certain function declarations cannot be overloaded: 395 // -- Function declarations that differ only in the return type 396 // cannot be overloaded. 397 QualType OldReturnType 398 = cast<FunctionType>(OldQType.getTypePtr())->getResultType(); 399 QualType NewReturnType 400 = cast<FunctionType>(NewQType.getTypePtr())->getResultType(); 401 if (OldReturnType != NewReturnType) { 402 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 403 Diag(Old->getLocation(), PrevDiag); 404 return New; 405 } 406 407 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 408 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 409 if (OldMethod && NewMethod) { 410 // -- Member function declarations with the same name and the 411 // same parameter types cannot be overloaded if any of them 412 // is a static member function declaration. 413 if (OldMethod->isStatic() || NewMethod->isStatic()) { 414 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 415 Diag(Old->getLocation(), PrevDiag); 416 return New; 417 } 418 } 419 420 // (C++98 8.3.5p3): 421 // All declarations for a function shall agree exactly in both the 422 // return type and the parameter-type-list. 423 if (OldQType == NewQType) { 424 // We have a redeclaration. 425 MergeAttributes(New, Old); 426 Redeclaration = true; 427 return MergeCXXFunctionDecl(New, Old); 428 } 429 430 // Fall through for conflicting redeclarations and redefinitions. 431 } 432 433 // C: Function types need to be compatible, not identical. This handles 434 // duplicate function decls like "void f(int); void f(enum X);" properly. 435 if (!getLangOptions().CPlusPlus && 436 Context.typesAreCompatible(OldQType, NewQType)) { 437 MergeAttributes(New, Old); 438 Redeclaration = true; 439 return New; 440 } 441 442 // A function that has already been declared has been redeclared or defined 443 // with a different type- show appropriate diagnostic 444 445 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 446 // TODO: This is totally simplistic. It should handle merging functions 447 // together etc, merging extern int X; int X; ... 448 Diag(New->getLocation(), diag::err_conflicting_types, New->getName()); 449 Diag(Old->getLocation(), PrevDiag); 450 return New; 451} 452 453/// Predicate for C "tentative" external object definitions (C99 6.9.2). 454static bool isTentativeDefinition(VarDecl *VD) { 455 if (VD->isFileVarDecl()) 456 return (!VD->getInit() && 457 (VD->getStorageClass() == VarDecl::None || 458 VD->getStorageClass() == VarDecl::Static)); 459 return false; 460} 461 462/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors 463/// when dealing with C "tentative" external object definitions (C99 6.9.2). 464void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) { 465 bool VDIsTentative = isTentativeDefinition(VD); 466 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType(); 467 468 for (IdentifierResolver::iterator 469 I = IdResolver.begin(VD->getIdentifier(), 470 VD->getDeclContext(), false/*LookInParentCtx*/), 471 E = IdResolver.end(); I != E; ++I) { 472 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) { 473 VarDecl *OldDecl = dyn_cast<VarDecl>(*I); 474 475 // Handle the following case: 476 // int a[10]; 477 // int a[]; - the code below makes sure we set the correct type. 478 // int a[11]; - this is an error, size isn't 10. 479 if (OldDecl && VDIsTentative && VDIsIncompleteArray && 480 OldDecl->getType()->isConstantArrayType()) 481 VD->setType(OldDecl->getType()); 482 483 // Check for "tentative" definitions. We can't accomplish this in 484 // MergeVarDecl since the initializer hasn't been attached. 485 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative) 486 continue; 487 488 // Handle __private_extern__ just like extern. 489 if (OldDecl->getStorageClass() != VarDecl::Extern && 490 OldDecl->getStorageClass() != VarDecl::PrivateExtern && 491 VD->getStorageClass() != VarDecl::Extern && 492 VD->getStorageClass() != VarDecl::PrivateExtern) { 493 Diag(VD->getLocation(), diag::err_redefinition, VD->getName()); 494 Diag(OldDecl->getLocation(), diag::err_previous_definition); 495 } 496 } 497 } 498} 499 500/// MergeVarDecl - We just parsed a variable 'New' which has the same name 501/// and scope as a previous declaration 'Old'. Figure out how to resolve this 502/// situation, merging decls or emitting diagnostics as appropriate. 503/// 504/// Tentative definition rules (C99 6.9.2p2) are checked by 505/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 506/// definitions here, since the initializer hasn't been attached. 507/// 508VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) { 509 // Verify the old decl was also a variable. 510 VarDecl *Old = dyn_cast<VarDecl>(OldD); 511 if (!Old) { 512 Diag(New->getLocation(), diag::err_redefinition_different_kind, 513 New->getName()); 514 Diag(OldD->getLocation(), diag::err_previous_definition); 515 return New; 516 } 517 518 MergeAttributes(New, Old); 519 520 // Verify the types match. 521 QualType OldCType = Context.getCanonicalType(Old->getType()); 522 QualType NewCType = Context.getCanonicalType(New->getType()); 523 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) { 524 Diag(New->getLocation(), diag::err_redefinition, New->getName()); 525 Diag(Old->getLocation(), diag::err_previous_definition); 526 return New; 527 } 528 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 529 if (New->getStorageClass() == VarDecl::Static && 530 (Old->getStorageClass() == VarDecl::None || 531 Old->getStorageClass() == VarDecl::Extern)) { 532 Diag(New->getLocation(), diag::err_static_non_static, New->getName()); 533 Diag(Old->getLocation(), diag::err_previous_definition); 534 return New; 535 } 536 // C99 6.2.2p4: Check if we have a non-static decl followed by a static. 537 if (New->getStorageClass() != VarDecl::Static && 538 Old->getStorageClass() == VarDecl::Static) { 539 Diag(New->getLocation(), diag::err_non_static_static, New->getName()); 540 Diag(Old->getLocation(), diag::err_previous_definition); 541 return New; 542 } 543 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 544 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) { 545 Diag(New->getLocation(), diag::err_redefinition, New->getName()); 546 Diag(Old->getLocation(), diag::err_previous_definition); 547 } 548 return New; 549} 550 551/// CheckParmsForFunctionDef - Check that the parameters of the given 552/// function are appropriate for the definition of a function. This 553/// takes care of any checks that cannot be performed on the 554/// declaration itself, e.g., that the types of each of the function 555/// parameters are complete. 556bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) { 557 bool HasInvalidParm = false; 558 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 559 ParmVarDecl *Param = FD->getParamDecl(p); 560 561 // C99 6.7.5.3p4: the parameters in a parameter type list in a 562 // function declarator that is part of a function definition of 563 // that function shall not have incomplete type. 564 if (Param->getType()->isIncompleteType() && 565 !Param->isInvalidDecl()) { 566 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type, 567 Param->getType().getAsString()); 568 Param->setInvalidDecl(); 569 HasInvalidParm = true; 570 } 571 } 572 573 return HasInvalidParm; 574} 575 576/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 577/// no declarator (e.g. "struct foo;") is parsed. 578Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) { 579 // TODO: emit error on 'int;' or 'const enum foo;'. 580 // TODO: emit error on 'typedef int;' 581 // if (!DS.isMissingDeclaratorOk()) Diag(...); 582 583 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep())); 584} 585 586bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) { 587 // Get the type before calling CheckSingleAssignmentConstraints(), since 588 // it can promote the expression. 589 QualType InitType = Init->getType(); 590 591 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init); 592 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType, 593 InitType, Init, "initializing"); 594} 595 596bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) { 597 const ArrayType *AT = Context.getAsArrayType(DeclT); 598 599 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 600 // C99 6.7.8p14. We have an array of character type with unknown size 601 // being initialized to a string literal. 602 llvm::APSInt ConstVal(32); 603 ConstVal = strLiteral->getByteLength() + 1; 604 // Return a new array type (C99 6.7.8p22). 605 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal, 606 ArrayType::Normal, 0); 607 } else { 608 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT); 609 // C99 6.7.8p14. We have an array of character type with known size. 610 // FIXME: Avoid truncation for 64-bit length strings. 611 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue()) 612 Diag(strLiteral->getSourceRange().getBegin(), 613 diag::warn_initializer_string_for_char_array_too_long, 614 strLiteral->getSourceRange()); 615 } 616 // Set type from "char *" to "constant array of char". 617 strLiteral->setType(DeclT); 618 // For now, we always return false (meaning success). 619 return false; 620} 621 622StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) { 623 const ArrayType *AT = Context.getAsArrayType(DeclType); 624 if (AT && AT->getElementType()->isCharType()) { 625 return dyn_cast<StringLiteral>(Init); 626 } 627 return 0; 628} 629 630bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) { 631 // C99 6.7.8p3: The type of the entity to be initialized shall be an array 632 // of unknown size ("[]") or an object type that is not a variable array type. 633 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType)) 634 return Diag(VAT->getSizeExpr()->getLocStart(), 635 diag::err_variable_object_no_init, 636 VAT->getSizeExpr()->getSourceRange()); 637 638 InitListExpr *InitList = dyn_cast<InitListExpr>(Init); 639 if (!InitList) { 640 // FIXME: Handle wide strings 641 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType)) 642 return CheckStringLiteralInit(strLiteral, DeclType); 643 644 // C99 6.7.8p16. 645 if (DeclType->isArrayType()) 646 return Diag(Init->getLocStart(), 647 diag::err_array_init_list_required, 648 Init->getSourceRange()); 649 650 return CheckSingleInitializer(Init, DeclType); 651 } 652 653 InitListChecker CheckInitList(this, InitList, DeclType); 654 return CheckInitList.HadError(); 655} 656 657Sema::DeclTy * 658Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) { 659 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl); 660 IdentifierInfo *II = D.getIdentifier(); 661 662 // All of these full declarators require an identifier. If it doesn't have 663 // one, the ParsedFreeStandingDeclSpec action should be used. 664 if (II == 0) { 665 Diag(D.getDeclSpec().getSourceRange().getBegin(), 666 diag::err_declarator_need_ident, 667 D.getDeclSpec().getSourceRange(), D.getSourceRange()); 668 return 0; 669 } 670 671 // The scope passed in may not be a decl scope. Zip up the scope tree until 672 // we find one that is. 673 while ((S->getFlags() & Scope::DeclScope) == 0) 674 S = S->getParent(); 675 676 // See if this is a redefinition of a variable in the same scope. 677 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S); 678 ScopedDecl *New; 679 bool InvalidDecl = false; 680 681 // In C++, the previous declaration we find might be a tag type 682 // (class or enum). In this case, the new declaration will hide the 683 // tag type. 684 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 685 PrevDecl = 0; 686 687 QualType R = GetTypeForDeclarator(D, S); 688 assert(!R.isNull() && "GetTypeForDeclarator() returned null type"); 689 690 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 691 // Check that there are no default arguments (C++ only). 692 if (getLangOptions().CPlusPlus) 693 CheckExtraCXXDefaultArguments(D); 694 695 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator); 696 if (!NewTD) return 0; 697 698 // Handle attributes prior to checking for duplicates in MergeVarDecl 699 ProcessDeclAttributes(NewTD, D); 700 // Merge the decl with the existing one if appropriate. If the decl is 701 // in an outer scope, it isn't the same thing. 702 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) { 703 NewTD = MergeTypeDefDecl(NewTD, PrevDecl); 704 if (NewTD == 0) return 0; 705 } 706 New = NewTD; 707 if (S->getFnParent() == 0) { 708 // C99 6.7.7p2: If a typedef name specifies a variably modified type 709 // then it shall have block scope. 710 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) { 711 // FIXME: Diagnostic needs to be fixed. 712 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla); 713 InvalidDecl = true; 714 } 715 } 716 } else if (R.getTypePtr()->isFunctionType()) { 717 FunctionDecl::StorageClass SC = FunctionDecl::None; 718 switch (D.getDeclSpec().getStorageClassSpec()) { 719 default: assert(0 && "Unknown storage class!"); 720 case DeclSpec::SCS_auto: 721 case DeclSpec::SCS_register: 722 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func, 723 R.getAsString()); 724 InvalidDecl = true; 725 break; 726 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break; 727 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break; 728 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break; 729 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break; 730 } 731 732 bool isInline = D.getDeclSpec().isInlineSpecified(); 733 FunctionDecl *NewFD; 734 if (D.getContext() == Declarator::MemberContext) { 735 // This is a C++ method declaration. 736 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext), 737 D.getIdentifierLoc(), II, R, 738 (SC == FunctionDecl::Static), isInline, 739 LastDeclarator); 740 } else { 741 NewFD = FunctionDecl::Create(Context, CurContext, 742 D.getIdentifierLoc(), 743 II, R, SC, isInline, LastDeclarator, 744 // FIXME: Move to DeclGroup... 745 D.getDeclSpec().getSourceRange().getBegin()); 746 } 747 // Handle attributes. 748 ProcessDeclAttributes(NewFD, D); 749 750 // Handle GNU asm-label extension (encoded as an attribute). 751 if (Expr *E = (Expr*) D.getAsmLabel()) { 752 // The parser guarantees this is a string. 753 StringLiteral *SE = cast<StringLiteral>(E); 754 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(), 755 SE->getByteLength()))); 756 } 757 758 // Copy the parameter declarations from the declarator D to 759 // the function declaration NewFD, if they are available. 760 if (D.getNumTypeObjects() > 0) { 761 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 762 763 // Create Decl objects for each parameter, adding them to the 764 // FunctionDecl. 765 llvm::SmallVector<ParmVarDecl*, 16> Params; 766 767 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 768 // function that takes no arguments, not a function that takes a 769 // single void argument. 770 // We let through "const void" here because Sema::GetTypeForDeclarator 771 // already checks for that case. 772 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 773 FTI.ArgInfo[0].Param && 774 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 775 // empty arg list, don't push any params. 776 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param; 777 778 // In C++, the empty parameter-type-list must be spelled "void"; a 779 // typedef of void is not permitted. 780 if (getLangOptions().CPlusPlus && 781 Param->getType().getUnqualifiedType() != Context.VoidTy) { 782 Diag(Param->getLocation(), diag::ext_param_typedef_of_void); 783 } 784 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 785 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 786 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param); 787 } 788 789 NewFD->setParams(&Params[0], Params.size()); 790 } else if (R->getAsTypedefType()) { 791 // When we're declaring a function with a typedef, as in the 792 // following example, we'll need to synthesize (unnamed) 793 // parameters for use in the declaration. 794 // 795 // @code 796 // typedef void fn(int); 797 // fn f; 798 // @endcode 799 const FunctionTypeProto *FT = R->getAsFunctionTypeProto(); 800 if (!FT) { 801 // This is a typedef of a function with no prototype, so we 802 // don't need to do anything. 803 } else if ((FT->getNumArgs() == 0) || 804 (FT->getNumArgs() == 1 && !FT->isVariadic() && 805 FT->getArgType(0)->isVoidType())) { 806 // This is a zero-argument function. We don't need to do anything. 807 } else { 808 // Synthesize a parameter for each argument type. 809 llvm::SmallVector<ParmVarDecl*, 16> Params; 810 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin(); 811 ArgType != FT->arg_type_end(); ++ArgType) { 812 Params.push_back(ParmVarDecl::Create(Context, CurContext, 813 SourceLocation(), 0, 814 *ArgType, VarDecl::None, 815 0, 0)); 816 } 817 818 NewFD->setParams(&Params[0], Params.size()); 819 } 820 } 821 822 // Merge the decl with the existing one if appropriate. Since C functions 823 // are in a flat namespace, make sure we consider decls in outer scopes. 824 if (PrevDecl && 825 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, CurContext, S))) { 826 bool Redeclaration = false; 827 828 // If C++, determine whether NewFD is an overload of PrevDecl or 829 // a declaration that requires merging. If it's an overload, 830 // there's no more work to do here; we'll just add the new 831 // function to the scope. 832 OverloadedFunctionDecl::function_iterator MatchedDecl; 833 if (!getLangOptions().CPlusPlus || 834 !IsOverload(NewFD, PrevDecl, MatchedDecl)) { 835 Decl *OldDecl = PrevDecl; 836 837 // If PrevDecl was an overloaded function, extract the 838 // FunctionDecl that matched. 839 if (isa<OverloadedFunctionDecl>(PrevDecl)) 840 OldDecl = *MatchedDecl; 841 842 // NewFD and PrevDecl represent declarations that need to be 843 // merged. 844 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration); 845 846 if (NewFD == 0) return 0; 847 if (Redeclaration) { 848 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 849 850 if (OldDecl == PrevDecl) { 851 // Remove the name binding for the previous 852 // declaration. We'll add the binding back later, but then 853 // it will refer to the new declaration (which will 854 // contain more information). 855 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl)); 856 } else { 857 // We need to update the OverloadedFunctionDecl with the 858 // latest declaration of this function, so that name 859 // lookup will always refer to the latest declaration of 860 // this function. 861 *MatchedDecl = NewFD; 862 863 // Add the redeclaration to the current scope, since we'll 864 // be skipping PushOnScopeChains. 865 S->AddDecl(NewFD); 866 867 return NewFD; 868 } 869 } 870 } 871 } 872 New = NewFD; 873 874 // In C++, check default arguments now that we have merged decls. 875 if (getLangOptions().CPlusPlus) 876 CheckCXXDefaultArguments(NewFD); 877 } else { 878 // Check that there are no default arguments (C++ only). 879 if (getLangOptions().CPlusPlus) 880 CheckExtraCXXDefaultArguments(D); 881 882 if (R.getTypePtr()->isObjCInterfaceType()) { 883 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object, 884 D.getIdentifier()->getName()); 885 InvalidDecl = true; 886 } 887 888 VarDecl *NewVD; 889 VarDecl::StorageClass SC; 890 switch (D.getDeclSpec().getStorageClassSpec()) { 891 default: assert(0 && "Unknown storage class!"); 892 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 893 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 894 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 895 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 896 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 897 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 898 } 899 if (D.getContext() == Declarator::MemberContext) { 900 assert(SC == VarDecl::Static && "Invalid storage class for member!"); 901 // This is a static data member for a C++ class. 902 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext), 903 D.getIdentifierLoc(), II, 904 R, LastDeclarator); 905 } else { 906 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified(); 907 if (S->getFnParent() == 0) { 908 // C99 6.9p2: The storage-class specifiers auto and register shall not 909 // appear in the declaration specifiers in an external declaration. 910 if (SC == VarDecl::Auto || SC == VarDecl::Register) { 911 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope, 912 R.getAsString()); 913 InvalidDecl = true; 914 } 915 } 916 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(), 917 II, R, SC, LastDeclarator, 918 // FIXME: Move to DeclGroup... 919 D.getDeclSpec().getSourceRange().getBegin()); 920 NewVD->setThreadSpecified(ThreadSpecified); 921 } 922 // Handle attributes prior to checking for duplicates in MergeVarDecl 923 ProcessDeclAttributes(NewVD, D); 924 925 // Handle GNU asm-label extension (encoded as an attribute). 926 if (Expr *E = (Expr*) D.getAsmLabel()) { 927 // The parser guarantees this is a string. 928 StringLiteral *SE = cast<StringLiteral>(E); 929 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(), 930 SE->getByteLength()))); 931 } 932 933 // Emit an error if an address space was applied to decl with local storage. 934 // This includes arrays of objects with address space qualifiers, but not 935 // automatic variables that point to other address spaces. 936 // ISO/IEC TR 18037 S5.1.2 937 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) { 938 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl); 939 InvalidDecl = true; 940 } 941 // Merge the decl with the existing one if appropriate. If the decl is 942 // in an outer scope, it isn't the same thing. 943 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) { 944 NewVD = MergeVarDecl(NewVD, PrevDecl); 945 if (NewVD == 0) return 0; 946 } 947 New = NewVD; 948 } 949 950 // If this has an identifier, add it to the scope stack. 951 if (II) 952 PushOnScopeChains(New, S); 953 // If any semantic error occurred, mark the decl as invalid. 954 if (D.getInvalidType() || InvalidDecl) 955 New->setInvalidDecl(); 956 957 return New; 958} 959 960bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) { 961 switch (Init->getStmtClass()) { 962 default: 963 Diag(Init->getExprLoc(), 964 diag::err_init_element_not_constant, Init->getSourceRange()); 965 return true; 966 case Expr::ParenExprClass: { 967 const ParenExpr* PE = cast<ParenExpr>(Init); 968 return CheckAddressConstantExpressionLValue(PE->getSubExpr()); 969 } 970 case Expr::CompoundLiteralExprClass: 971 return cast<CompoundLiteralExpr>(Init)->isFileScope(); 972 case Expr::DeclRefExprClass: { 973 const Decl *D = cast<DeclRefExpr>(Init)->getDecl(); 974 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 975 if (VD->hasGlobalStorage()) 976 return false; 977 Diag(Init->getExprLoc(), 978 diag::err_init_element_not_constant, Init->getSourceRange()); 979 return true; 980 } 981 if (isa<FunctionDecl>(D)) 982 return false; 983 Diag(Init->getExprLoc(), 984 diag::err_init_element_not_constant, Init->getSourceRange()); 985 return true; 986 } 987 case Expr::MemberExprClass: { 988 const MemberExpr *M = cast<MemberExpr>(Init); 989 if (M->isArrow()) 990 return CheckAddressConstantExpression(M->getBase()); 991 return CheckAddressConstantExpressionLValue(M->getBase()); 992 } 993 case Expr::ArraySubscriptExprClass: { 994 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)? 995 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init); 996 return CheckAddressConstantExpression(ASE->getBase()) || 997 CheckArithmeticConstantExpression(ASE->getIdx()); 998 } 999 case Expr::StringLiteralClass: 1000 case Expr::PredefinedExprClass: 1001 return false; 1002 case Expr::UnaryOperatorClass: { 1003 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1004 1005 // C99 6.6p9 1006 if (Exp->getOpcode() == UnaryOperator::Deref) 1007 return CheckAddressConstantExpression(Exp->getSubExpr()); 1008 1009 Diag(Init->getExprLoc(), 1010 diag::err_init_element_not_constant, Init->getSourceRange()); 1011 return true; 1012 } 1013 } 1014} 1015 1016bool Sema::CheckAddressConstantExpression(const Expr* Init) { 1017 switch (Init->getStmtClass()) { 1018 default: 1019 Diag(Init->getExprLoc(), 1020 diag::err_init_element_not_constant, Init->getSourceRange()); 1021 return true; 1022 case Expr::ParenExprClass: 1023 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr()); 1024 case Expr::StringLiteralClass: 1025 case Expr::ObjCStringLiteralClass: 1026 return false; 1027 case Expr::CallExprClass: 1028 // __builtin___CFStringMakeConstantString is a valid constant l-value. 1029 if (cast<CallExpr>(Init)->isBuiltinCall() == 1030 Builtin::BI__builtin___CFStringMakeConstantString) 1031 return false; 1032 1033 Diag(Init->getExprLoc(), 1034 diag::err_init_element_not_constant, Init->getSourceRange()); 1035 return true; 1036 1037 case Expr::UnaryOperatorClass: { 1038 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1039 1040 // C99 6.6p9 1041 if (Exp->getOpcode() == UnaryOperator::AddrOf) 1042 return CheckAddressConstantExpressionLValue(Exp->getSubExpr()); 1043 1044 if (Exp->getOpcode() == UnaryOperator::Extension) 1045 return CheckAddressConstantExpression(Exp->getSubExpr()); 1046 1047 Diag(Init->getExprLoc(), 1048 diag::err_init_element_not_constant, Init->getSourceRange()); 1049 return true; 1050 } 1051 case Expr::BinaryOperatorClass: { 1052 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"? 1053 const BinaryOperator *Exp = cast<BinaryOperator>(Init); 1054 1055 Expr *PExp = Exp->getLHS(); 1056 Expr *IExp = Exp->getRHS(); 1057 if (IExp->getType()->isPointerType()) 1058 std::swap(PExp, IExp); 1059 1060 // FIXME: Should we pedwarn if IExp isn't an integer constant expression? 1061 return CheckAddressConstantExpression(PExp) || 1062 CheckArithmeticConstantExpression(IExp); 1063 } 1064 case Expr::ImplicitCastExprClass: 1065 case Expr::ExplicitCastExprClass: { 1066 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr(); 1067 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) { 1068 // Check for implicit promotion 1069 if (SubExpr->getType()->isFunctionType() || 1070 SubExpr->getType()->isArrayType()) 1071 return CheckAddressConstantExpressionLValue(SubExpr); 1072 } 1073 1074 // Check for pointer->pointer cast 1075 if (SubExpr->getType()->isPointerType()) 1076 return CheckAddressConstantExpression(SubExpr); 1077 1078 if (SubExpr->getType()->isIntegralType()) { 1079 // Check for the special-case of a pointer->int->pointer cast; 1080 // this isn't standard, but some code requires it. See 1081 // PR2720 for an example. 1082 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) { 1083 if (SubCast->getSubExpr()->getType()->isPointerType()) { 1084 unsigned IntWidth = Context.getIntWidth(SubCast->getType()); 1085 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy); 1086 if (IntWidth >= PointerWidth) { 1087 return CheckAddressConstantExpression(SubCast->getSubExpr()); 1088 } 1089 } 1090 } 1091 } 1092 if (SubExpr->getType()->isArithmeticType()) { 1093 return CheckArithmeticConstantExpression(SubExpr); 1094 } 1095 1096 Diag(Init->getExprLoc(), 1097 diag::err_init_element_not_constant, Init->getSourceRange()); 1098 return true; 1099 } 1100 case Expr::ConditionalOperatorClass: { 1101 // FIXME: Should we pedwarn here? 1102 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init); 1103 if (!Exp->getCond()->getType()->isArithmeticType()) { 1104 Diag(Init->getExprLoc(), 1105 diag::err_init_element_not_constant, Init->getSourceRange()); 1106 return true; 1107 } 1108 if (CheckArithmeticConstantExpression(Exp->getCond())) 1109 return true; 1110 if (Exp->getLHS() && 1111 CheckAddressConstantExpression(Exp->getLHS())) 1112 return true; 1113 return CheckAddressConstantExpression(Exp->getRHS()); 1114 } 1115 case Expr::AddrLabelExprClass: 1116 return false; 1117 } 1118} 1119 1120static const Expr* FindExpressionBaseAddress(const Expr* E); 1121 1122static const Expr* FindExpressionBaseAddressLValue(const Expr* E) { 1123 switch (E->getStmtClass()) { 1124 default: 1125 return E; 1126 case Expr::ParenExprClass: { 1127 const ParenExpr* PE = cast<ParenExpr>(E); 1128 return FindExpressionBaseAddressLValue(PE->getSubExpr()); 1129 } 1130 case Expr::MemberExprClass: { 1131 const MemberExpr *M = cast<MemberExpr>(E); 1132 if (M->isArrow()) 1133 return FindExpressionBaseAddress(M->getBase()); 1134 return FindExpressionBaseAddressLValue(M->getBase()); 1135 } 1136 case Expr::ArraySubscriptExprClass: { 1137 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E); 1138 return FindExpressionBaseAddress(ASE->getBase()); 1139 } 1140 case Expr::UnaryOperatorClass: { 1141 const UnaryOperator *Exp = cast<UnaryOperator>(E); 1142 1143 if (Exp->getOpcode() == UnaryOperator::Deref) 1144 return FindExpressionBaseAddress(Exp->getSubExpr()); 1145 1146 return E; 1147 } 1148 } 1149} 1150 1151static const Expr* FindExpressionBaseAddress(const Expr* E) { 1152 switch (E->getStmtClass()) { 1153 default: 1154 return E; 1155 case Expr::ParenExprClass: { 1156 const ParenExpr* PE = cast<ParenExpr>(E); 1157 return FindExpressionBaseAddress(PE->getSubExpr()); 1158 } 1159 case Expr::UnaryOperatorClass: { 1160 const UnaryOperator *Exp = cast<UnaryOperator>(E); 1161 1162 // C99 6.6p9 1163 if (Exp->getOpcode() == UnaryOperator::AddrOf) 1164 return FindExpressionBaseAddressLValue(Exp->getSubExpr()); 1165 1166 if (Exp->getOpcode() == UnaryOperator::Extension) 1167 return FindExpressionBaseAddress(Exp->getSubExpr()); 1168 1169 return E; 1170 } 1171 case Expr::BinaryOperatorClass: { 1172 const BinaryOperator *Exp = cast<BinaryOperator>(E); 1173 1174 Expr *PExp = Exp->getLHS(); 1175 Expr *IExp = Exp->getRHS(); 1176 if (IExp->getType()->isPointerType()) 1177 std::swap(PExp, IExp); 1178 1179 return FindExpressionBaseAddress(PExp); 1180 } 1181 case Expr::ImplicitCastExprClass: { 1182 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr(); 1183 1184 // Check for implicit promotion 1185 if (SubExpr->getType()->isFunctionType() || 1186 SubExpr->getType()->isArrayType()) 1187 return FindExpressionBaseAddressLValue(SubExpr); 1188 1189 // Check for pointer->pointer cast 1190 if (SubExpr->getType()->isPointerType()) 1191 return FindExpressionBaseAddress(SubExpr); 1192 1193 // We assume that we have an arithmetic expression here; 1194 // if we don't, we'll figure it out later 1195 return 0; 1196 } 1197 case Expr::ExplicitCastExprClass: { 1198 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 1199 1200 // Check for pointer->pointer cast 1201 if (SubExpr->getType()->isPointerType()) 1202 return FindExpressionBaseAddress(SubExpr); 1203 1204 // We assume that we have an arithmetic expression here; 1205 // if we don't, we'll figure it out later 1206 return 0; 1207 } 1208 } 1209} 1210 1211bool Sema::CheckArithmeticConstantExpression(const Expr* Init) { 1212 switch (Init->getStmtClass()) { 1213 default: 1214 Diag(Init->getExprLoc(), 1215 diag::err_init_element_not_constant, Init->getSourceRange()); 1216 return true; 1217 case Expr::ParenExprClass: { 1218 const ParenExpr* PE = cast<ParenExpr>(Init); 1219 return CheckArithmeticConstantExpression(PE->getSubExpr()); 1220 } 1221 case Expr::FloatingLiteralClass: 1222 case Expr::IntegerLiteralClass: 1223 case Expr::CharacterLiteralClass: 1224 case Expr::ImaginaryLiteralClass: 1225 case Expr::TypesCompatibleExprClass: 1226 case Expr::CXXBoolLiteralExprClass: 1227 return false; 1228 case Expr::CallExprClass: { 1229 const CallExpr *CE = cast<CallExpr>(Init); 1230 1231 // Allow any constant foldable calls to builtins. 1232 if (CE->isBuiltinCall() && CE->isEvaluatable(Context)) 1233 return false; 1234 1235 Diag(Init->getExprLoc(), 1236 diag::err_init_element_not_constant, Init->getSourceRange()); 1237 return true; 1238 } 1239 case Expr::DeclRefExprClass: { 1240 const Decl *D = cast<DeclRefExpr>(Init)->getDecl(); 1241 if (isa<EnumConstantDecl>(D)) 1242 return false; 1243 Diag(Init->getExprLoc(), 1244 diag::err_init_element_not_constant, Init->getSourceRange()); 1245 return true; 1246 } 1247 case Expr::CompoundLiteralExprClass: 1248 // Allow "(vector type){2,4}"; normal C constraints don't allow this, 1249 // but vectors are allowed to be magic. 1250 if (Init->getType()->isVectorType()) 1251 return false; 1252 Diag(Init->getExprLoc(), 1253 diag::err_init_element_not_constant, Init->getSourceRange()); 1254 return true; 1255 case Expr::UnaryOperatorClass: { 1256 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1257 1258 switch (Exp->getOpcode()) { 1259 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 1260 // See C99 6.6p3. 1261 default: 1262 Diag(Init->getExprLoc(), 1263 diag::err_init_element_not_constant, Init->getSourceRange()); 1264 return true; 1265 case UnaryOperator::SizeOf: 1266 case UnaryOperator::AlignOf: 1267 case UnaryOperator::OffsetOf: 1268 // sizeof(E) is a constantexpr if and only if E is not evaluted. 1269 // See C99 6.5.3.4p2 and 6.6p3. 1270 if (Exp->getSubExpr()->getType()->isConstantSizeType()) 1271 return false; 1272 Diag(Init->getExprLoc(), 1273 diag::err_init_element_not_constant, Init->getSourceRange()); 1274 return true; 1275 case UnaryOperator::Extension: 1276 case UnaryOperator::LNot: 1277 case UnaryOperator::Plus: 1278 case UnaryOperator::Minus: 1279 case UnaryOperator::Not: 1280 return CheckArithmeticConstantExpression(Exp->getSubExpr()); 1281 } 1282 } 1283 case Expr::SizeOfAlignOfTypeExprClass: { 1284 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init); 1285 // Special check for void types, which are allowed as an extension 1286 if (Exp->getArgumentType()->isVoidType()) 1287 return false; 1288 // alignof always evaluates to a constant. 1289 // FIXME: is sizeof(int[3.0]) a constant expression? 1290 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) { 1291 Diag(Init->getExprLoc(), 1292 diag::err_init_element_not_constant, Init->getSourceRange()); 1293 return true; 1294 } 1295 return false; 1296 } 1297 case Expr::BinaryOperatorClass: { 1298 const BinaryOperator *Exp = cast<BinaryOperator>(Init); 1299 1300 if (Exp->getLHS()->getType()->isArithmeticType() && 1301 Exp->getRHS()->getType()->isArithmeticType()) { 1302 return CheckArithmeticConstantExpression(Exp->getLHS()) || 1303 CheckArithmeticConstantExpression(Exp->getRHS()); 1304 } 1305 1306 if (Exp->getLHS()->getType()->isPointerType() && 1307 Exp->getRHS()->getType()->isPointerType()) { 1308 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS()); 1309 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS()); 1310 1311 // Only allow a null (constant integer) base; we could 1312 // allow some additional cases if necessary, but this 1313 // is sufficient to cover offsetof-like constructs. 1314 if (!LHSBase && !RHSBase) { 1315 return CheckAddressConstantExpression(Exp->getLHS()) || 1316 CheckAddressConstantExpression(Exp->getRHS()); 1317 } 1318 } 1319 1320 Diag(Init->getExprLoc(), 1321 diag::err_init_element_not_constant, Init->getSourceRange()); 1322 return true; 1323 } 1324 case Expr::ImplicitCastExprClass: 1325 case Expr::ExplicitCastExprClass: { 1326 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr(); 1327 if (SubExpr->getType()->isArithmeticType()) 1328 return CheckArithmeticConstantExpression(SubExpr); 1329 1330 if (SubExpr->getType()->isPointerType()) { 1331 const Expr* Base = FindExpressionBaseAddress(SubExpr); 1332 // If the pointer has a null base, this is an offsetof-like construct 1333 if (!Base) 1334 return CheckAddressConstantExpression(SubExpr); 1335 } 1336 1337 Diag(Init->getExprLoc(), 1338 diag::err_init_element_not_constant, Init->getSourceRange()); 1339 return true; 1340 } 1341 case Expr::ConditionalOperatorClass: { 1342 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init); 1343 1344 // If GNU extensions are disabled, we require all operands to be arithmetic 1345 // constant expressions. 1346 if (getLangOptions().NoExtensions) { 1347 return CheckArithmeticConstantExpression(Exp->getCond()) || 1348 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) || 1349 CheckArithmeticConstantExpression(Exp->getRHS()); 1350 } 1351 1352 // Otherwise, we have to emulate some of the behavior of fold here. 1353 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant 1354 // because it can constant fold things away. To retain compatibility with 1355 // GCC code, we see if we can fold the condition to a constant (which we 1356 // should always be able to do in theory). If so, we only require the 1357 // specified arm of the conditional to be a constant. This is a horrible 1358 // hack, but is require by real world code that uses __builtin_constant_p. 1359 APValue Val; 1360 if (!Exp->getCond()->tryEvaluate(Val, Context)) { 1361 // If the tryEvaluate couldn't fold it, CheckArithmeticConstantExpression 1362 // won't be able to either. Use it to emit the diagnostic though. 1363 bool Res = CheckArithmeticConstantExpression(Exp->getCond()); 1364 assert(Res && "tryEvaluate couldn't evaluate this constant?"); 1365 return Res; 1366 } 1367 1368 // Verify that the side following the condition is also a constant. 1369 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS(); 1370 if (Val.getInt() == 0) 1371 std::swap(TrueSide, FalseSide); 1372 1373 if (TrueSide && CheckArithmeticConstantExpression(TrueSide)) 1374 return true; 1375 1376 // Okay, the evaluated side evaluates to a constant, so we accept this. 1377 // Check to see if the other side is obviously not a constant. If so, 1378 // emit a warning that this is a GNU extension. 1379 if (FalseSide && !FalseSide->isEvaluatable(Context)) 1380 Diag(Init->getExprLoc(), 1381 diag::ext_typecheck_expression_not_constant_but_accepted, 1382 FalseSide->getSourceRange()); 1383 return false; 1384 } 1385 } 1386} 1387 1388bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 1389 Init = Init->IgnoreParens(); 1390 1391 // Look through CXXDefaultArgExprs; they have no meaning in this context. 1392 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init)) 1393 return CheckForConstantInitializer(DAE->getExpr(), DclT); 1394 1395 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init)) 1396 return CheckForConstantInitializer(e->getInitializer(), DclT); 1397 1398 if (Init->getType()->isReferenceType()) { 1399 // FIXME: Work out how the heck references work. 1400 return false; 1401 } 1402 1403 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) { 1404 unsigned numInits = Exp->getNumInits(); 1405 for (unsigned i = 0; i < numInits; i++) { 1406 // FIXME: Need to get the type of the declaration for C++, 1407 // because it could be a reference? 1408 if (CheckForConstantInitializer(Exp->getInit(i), 1409 Exp->getInit(i)->getType())) 1410 return true; 1411 } 1412 return false; 1413 } 1414 1415 if (Init->isNullPointerConstant(Context)) 1416 return false; 1417 if (Init->getType()->isArithmeticType()) { 1418 QualType InitTy = Context.getCanonicalType(Init->getType()) 1419 .getUnqualifiedType(); 1420 if (InitTy == Context.BoolTy) { 1421 // Special handling for pointers implicitly cast to bool; 1422 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level. 1423 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) { 1424 Expr* SubE = ICE->getSubExpr(); 1425 if (SubE->getType()->isPointerType() || 1426 SubE->getType()->isArrayType() || 1427 SubE->getType()->isFunctionType()) { 1428 return CheckAddressConstantExpression(Init); 1429 } 1430 } 1431 } else if (InitTy->isIntegralType()) { 1432 Expr* SubE = 0; 1433 if (CastExpr* CE = dyn_cast<CastExpr>(Init)) 1434 SubE = CE->getSubExpr(); 1435 // Special check for pointer cast to int; we allow as an extension 1436 // an address constant cast to an integer if the integer 1437 // is of an appropriate width (this sort of code is apparently used 1438 // in some places). 1439 // FIXME: Add pedwarn? 1440 // FIXME: Don't allow bitfields here! Need the FieldDecl for that. 1441 if (SubE && (SubE->getType()->isPointerType() || 1442 SubE->getType()->isArrayType() || 1443 SubE->getType()->isFunctionType())) { 1444 unsigned IntWidth = Context.getTypeSize(Init->getType()); 1445 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy); 1446 if (IntWidth >= PointerWidth) 1447 return CheckAddressConstantExpression(Init); 1448 } 1449 } 1450 1451 return CheckArithmeticConstantExpression(Init); 1452 } 1453 1454 if (Init->getType()->isPointerType()) 1455 return CheckAddressConstantExpression(Init); 1456 1457 // An array type at the top level that isn't an init-list must 1458 // be a string literal 1459 if (Init->getType()->isArrayType()) 1460 return false; 1461 1462 if (Init->getType()->isFunctionType()) 1463 return false; 1464 1465 // Allow block exprs at top level. 1466 if (Init->getType()->isBlockPointerType()) 1467 return false; 1468 1469 Diag(Init->getExprLoc(), diag::err_init_element_not_constant, 1470 Init->getSourceRange()); 1471 return true; 1472} 1473 1474void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) { 1475 Decl *RealDecl = static_cast<Decl *>(dcl); 1476 Expr *Init = static_cast<Expr *>(init); 1477 assert(Init && "missing initializer"); 1478 1479 // If there is no declaration, there was an error parsing it. Just ignore 1480 // the initializer. 1481 if (RealDecl == 0) { 1482 delete Init; 1483 return; 1484 } 1485 1486 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 1487 if (!VDecl) { 1488 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(), 1489 diag::err_illegal_initializer); 1490 RealDecl->setInvalidDecl(); 1491 return; 1492 } 1493 // Get the decls type and save a reference for later, since 1494 // CheckInitializerTypes may change it. 1495 QualType DclT = VDecl->getType(), SavT = DclT; 1496 if (VDecl->isBlockVarDecl()) { 1497 VarDecl::StorageClass SC = VDecl->getStorageClass(); 1498 if (SC == VarDecl::Extern) { // C99 6.7.8p5 1499 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 1500 VDecl->setInvalidDecl(); 1501 } else if (!VDecl->isInvalidDecl()) { 1502 if (CheckInitializerTypes(Init, DclT)) 1503 VDecl->setInvalidDecl(); 1504 1505 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 1506 if (!getLangOptions().CPlusPlus) { 1507 if (SC == VarDecl::Static) // C99 6.7.8p4. 1508 CheckForConstantInitializer(Init, DclT); 1509 } 1510 } 1511 } else if (VDecl->isFileVarDecl()) { 1512 if (VDecl->getStorageClass() == VarDecl::Extern) 1513 Diag(VDecl->getLocation(), diag::warn_extern_init); 1514 if (!VDecl->isInvalidDecl()) 1515 if (CheckInitializerTypes(Init, DclT)) 1516 VDecl->setInvalidDecl(); 1517 1518 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 1519 if (!getLangOptions().CPlusPlus) { 1520 // C99 6.7.8p4. All file scoped initializers need to be constant. 1521 CheckForConstantInitializer(Init, DclT); 1522 } 1523 } 1524 // If the type changed, it means we had an incomplete type that was 1525 // completed by the initializer. For example: 1526 // int ary[] = { 1, 3, 5 }; 1527 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 1528 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 1529 VDecl->setType(DclT); 1530 Init->setType(DclT); 1531 } 1532 1533 // Attach the initializer to the decl. 1534 VDecl->setInit(Init); 1535 return; 1536} 1537 1538/// The declarators are chained together backwards, reverse the list. 1539Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) { 1540 // Often we have single declarators, handle them quickly. 1541 Decl *GroupDecl = static_cast<Decl*>(group); 1542 if (GroupDecl == 0) 1543 return 0; 1544 1545 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl); 1546 ScopedDecl *NewGroup = 0; 1547 if (Group->getNextDeclarator() == 0) 1548 NewGroup = Group; 1549 else { // reverse the list. 1550 while (Group) { 1551 ScopedDecl *Next = Group->getNextDeclarator(); 1552 Group->setNextDeclarator(NewGroup); 1553 NewGroup = Group; 1554 Group = Next; 1555 } 1556 } 1557 // Perform semantic analysis that depends on having fully processed both 1558 // the declarator and initializer. 1559 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) { 1560 VarDecl *IDecl = dyn_cast<VarDecl>(ID); 1561 if (!IDecl) 1562 continue; 1563 QualType T = IDecl->getType(); 1564 1565 // C99 6.7.5.2p2: If an identifier is declared to be an object with 1566 // static storage duration, it shall not have a variable length array. 1567 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) && 1568 IDecl->getStorageClass() == VarDecl::Static) { 1569 if (T->isVariableArrayType()) { 1570 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla); 1571 IDecl->setInvalidDecl(); 1572 } 1573 } 1574 // Block scope. C99 6.7p7: If an identifier for an object is declared with 1575 // no linkage (C99 6.2.2p6), the type for the object shall be complete... 1576 if (IDecl->isBlockVarDecl() && 1577 IDecl->getStorageClass() != VarDecl::Extern) { 1578 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) { 1579 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type, 1580 T.getAsString()); 1581 IDecl->setInvalidDecl(); 1582 } 1583 } 1584 // File scope. C99 6.9.2p2: A declaration of an identifier for and 1585 // object that has file scope without an initializer, and without a 1586 // storage-class specifier or with the storage-class specifier "static", 1587 // constitutes a tentative definition. Note: A tentative definition with 1588 // external linkage is valid (C99 6.2.2p5). 1589 if (isTentativeDefinition(IDecl)) { 1590 if (T->isIncompleteArrayType()) { 1591 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete 1592 // array to be completed. Don't issue a diagnostic. 1593 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) { 1594 // C99 6.9.2p3: If the declaration of an identifier for an object is 1595 // a tentative definition and has internal linkage (C99 6.2.2p3), the 1596 // declared type shall not be an incomplete type. 1597 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type, 1598 T.getAsString()); 1599 IDecl->setInvalidDecl(); 1600 } 1601 } 1602 if (IDecl->isFileVarDecl()) 1603 CheckForFileScopedRedefinitions(S, IDecl); 1604 } 1605 return NewGroup; 1606} 1607 1608/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 1609/// to introduce parameters into function prototype scope. 1610Sema::DeclTy * 1611Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 1612 const DeclSpec &DS = D.getDeclSpec(); 1613 1614 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 1615 VarDecl::StorageClass StorageClass = VarDecl::None; 1616 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 1617 StorageClass = VarDecl::Register; 1618 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 1619 Diag(DS.getStorageClassSpecLoc(), 1620 diag::err_invalid_storage_class_in_func_decl); 1621 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1622 } 1623 if (DS.isThreadSpecified()) { 1624 Diag(DS.getThreadSpecLoc(), 1625 diag::err_invalid_storage_class_in_func_decl); 1626 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1627 } 1628 1629 // Check that there are no default arguments inside the type of this 1630 // parameter (C++ only). 1631 if (getLangOptions().CPlusPlus) 1632 CheckExtraCXXDefaultArguments(D); 1633 1634 // In this context, we *do not* check D.getInvalidType(). If the declarator 1635 // type was invalid, GetTypeForDeclarator() still returns a "valid" type, 1636 // though it will not reflect the user specified type. 1637 QualType parmDeclType = GetTypeForDeclarator(D, S); 1638 1639 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type"); 1640 1641 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 1642 // Can this happen for params? We already checked that they don't conflict 1643 // among each other. Here they can only shadow globals, which is ok. 1644 IdentifierInfo *II = D.getIdentifier(); 1645 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) { 1646 if (S->isDeclScope(PrevDecl)) { 1647 Diag(D.getIdentifierLoc(), diag::err_param_redefinition, 1648 dyn_cast<NamedDecl>(PrevDecl)->getName()); 1649 1650 // Recover by removing the name 1651 II = 0; 1652 D.SetIdentifier(0, D.getIdentifierLoc()); 1653 } 1654 } 1655 1656 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]). 1657 // Doing the promotion here has a win and a loss. The win is the type for 1658 // both Decl's and DeclRefExpr's will match (a convenient invariant for the 1659 // code generator). The loss is the orginal type isn't preserved. For example: 1660 // 1661 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *" 1662 // int blockvardecl[5]; 1663 // sizeof(parmvardecl); // size == 4 1664 // sizeof(blockvardecl); // size == 20 1665 // } 1666 // 1667 // For expressions, all implicit conversions are captured using the 1668 // ImplicitCastExpr AST node (we have no such mechanism for Decl's). 1669 // 1670 // FIXME: If a source translation tool needs to see the original type, then 1671 // we need to consider storing both types (in ParmVarDecl)... 1672 // 1673 if (parmDeclType->isArrayType()) { 1674 // int x[restrict 4] -> int *restrict 1675 parmDeclType = Context.getArrayDecayedType(parmDeclType); 1676 } else if (parmDeclType->isFunctionType()) 1677 parmDeclType = Context.getPointerType(parmDeclType); 1678 1679 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, 1680 D.getIdentifierLoc(), II, 1681 parmDeclType, StorageClass, 1682 0, 0); 1683 1684 if (D.getInvalidType()) 1685 New->setInvalidDecl(); 1686 1687 if (II) 1688 PushOnScopeChains(New, S); 1689 1690 ProcessDeclAttributes(New, D); 1691 return New; 1692 1693} 1694 1695Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 1696 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 1697 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 1698 "Not a function declarator!"); 1699 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1700 1701 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 1702 // for a K&R function. 1703 if (!FTI.hasPrototype) { 1704 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 1705 if (FTI.ArgInfo[i].Param == 0) { 1706 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared, 1707 FTI.ArgInfo[i].Ident->getName()); 1708 // Implicitly declare the argument as type 'int' for lack of a better 1709 // type. 1710 DeclSpec DS; 1711 const char* PrevSpec; // unused 1712 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 1713 PrevSpec); 1714 Declarator ParamD(DS, Declarator::KNRTypeListContext); 1715 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 1716 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD); 1717 } 1718 } 1719 } else { 1720 // FIXME: Diagnose arguments without names in C. 1721 } 1722 1723 Scope *GlobalScope = FnBodyScope->getParent(); 1724 1725 // See if this is a redefinition. 1726 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary, 1727 GlobalScope); 1728 if (PrevDcl && isDeclInScope(PrevDcl, CurContext)) { 1729 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) { 1730 const FunctionDecl *Definition; 1731 if (FD->getBody(Definition)) { 1732 Diag(D.getIdentifierLoc(), diag::err_redefinition, 1733 D.getIdentifier()->getName()); 1734 Diag(Definition->getLocation(), diag::err_previous_definition); 1735 } 1736 } 1737 } 1738 1739 return ActOnStartOfFunctionDef(FnBodyScope, 1740 ActOnDeclarator(GlobalScope, D, 0)); 1741} 1742 1743Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) { 1744 Decl *decl = static_cast<Decl*>(D); 1745 FunctionDecl *FD = cast<FunctionDecl>(decl); 1746 PushDeclContext(FD); 1747 1748 // Check the validity of our function parameters 1749 CheckParmsForFunctionDef(FD); 1750 1751 // Introduce our parameters into the function scope 1752 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 1753 ParmVarDecl *Param = FD->getParamDecl(p); 1754 // If this has an identifier, add it to the scope stack. 1755 if (Param->getIdentifier()) 1756 PushOnScopeChains(Param, FnBodyScope); 1757 } 1758 1759 return FD; 1760} 1761 1762Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) { 1763 Decl *dcl = static_cast<Decl *>(D); 1764 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) { 1765 FD->setBody((Stmt*)Body); 1766 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 1767 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 1768 MD->setBody((Stmt*)Body); 1769 } else 1770 return 0; 1771 PopDeclContext(); 1772 // Verify and clean out per-function state. 1773 1774 // Check goto/label use. 1775 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 1776 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) { 1777 // Verify that we have no forward references left. If so, there was a goto 1778 // or address of a label taken, but no definition of it. Label fwd 1779 // definitions are indicated with a null substmt. 1780 if (I->second->getSubStmt() == 0) { 1781 LabelStmt *L = I->second; 1782 // Emit error. 1783 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName()); 1784 1785 // At this point, we have gotos that use the bogus label. Stitch it into 1786 // the function body so that they aren't leaked and that the AST is well 1787 // formed. 1788 if (Body) { 1789 L->setSubStmt(new NullStmt(L->getIdentLoc())); 1790 cast<CompoundStmt>((Stmt*)Body)->push_back(L); 1791 } else { 1792 // The whole function wasn't parsed correctly, just delete this. 1793 delete L; 1794 } 1795 } 1796 } 1797 LabelMap.clear(); 1798 1799 return D; 1800} 1801 1802/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 1803/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 1804ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 1805 IdentifierInfo &II, Scope *S) { 1806 // Extension in C99. Legal in C90, but warn about it. 1807 if (getLangOptions().C99) 1808 Diag(Loc, diag::ext_implicit_function_decl, II.getName()); 1809 else 1810 Diag(Loc, diag::warn_implicit_function_decl, II.getName()); 1811 1812 // FIXME: handle stuff like: 1813 // void foo() { extern float X(); } 1814 // void bar() { X(); } <-- implicit decl for X in another scope. 1815 1816 // Set a Declarator for the implicit definition: int foo(); 1817 const char *Dummy; 1818 DeclSpec DS; 1819 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy); 1820 Error = Error; // Silence warning. 1821 assert(!Error && "Error setting up implicit decl!"); 1822 Declarator D(DS, Declarator::BlockContext); 1823 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc)); 1824 D.SetIdentifier(&II, Loc); 1825 1826 // Insert this function into translation-unit scope. 1827 1828 DeclContext *PrevDC = CurContext; 1829 CurContext = Context.getTranslationUnitDecl(); 1830 1831 FunctionDecl *FD = 1832 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0))); 1833 FD->setImplicit(); 1834 1835 CurContext = PrevDC; 1836 1837 return FD; 1838} 1839 1840 1841TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 1842 ScopedDecl *LastDeclarator) { 1843 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 1844 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 1845 1846 // Scope manipulation handled by caller. 1847 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 1848 D.getIdentifierLoc(), 1849 D.getIdentifier(), 1850 T, LastDeclarator); 1851 if (D.getInvalidType()) 1852 NewTD->setInvalidDecl(); 1853 return NewTD; 1854} 1855 1856/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 1857/// former case, Name will be non-null. In the later case, Name will be null. 1858/// TagType indicates what kind of tag this is. TK indicates whether this is a 1859/// reference/declaration/definition of a tag. 1860Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK, 1861 SourceLocation KWLoc, IdentifierInfo *Name, 1862 SourceLocation NameLoc, AttributeList *Attr) { 1863 // If this is a use of an existing tag, it must have a name. 1864 assert((Name != 0 || TK == TK_Definition) && 1865 "Nameless record must be a definition!"); 1866 1867 TagDecl::TagKind Kind; 1868 switch (TagType) { 1869 default: assert(0 && "Unknown tag type!"); 1870 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 1871 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 1872 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 1873 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break; 1874 } 1875 1876 // Two code paths: a new one for structs/unions/classes where we create 1877 // separate decls for forward declarations, and an old (eventually to 1878 // be removed) code path for enums. 1879 if (Kind != TagDecl::TK_enum) 1880 return ActOnTagStruct(S, Kind, TK, KWLoc, Name, NameLoc, Attr); 1881 1882 // If this is a named struct, check to see if there was a previous forward 1883 // declaration or definition. 1884 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up. 1885 ScopedDecl *PrevDecl = 1886 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S)); 1887 1888 if (PrevDecl) { 1889 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) && 1890 "unexpected Decl type"); 1891 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 1892 // If this is a use of a previous tag, or if the tag is already declared 1893 // in the same scope (so that the definition/declaration completes or 1894 // rementions the tag), reuse the decl. 1895 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) { 1896 // Make sure that this wasn't declared as an enum and now used as a 1897 // struct or something similar. 1898 if (PrevTagDecl->getTagKind() != Kind) { 1899 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName()); 1900 Diag(PrevDecl->getLocation(), diag::err_previous_use); 1901 // Recover by making this an anonymous redefinition. 1902 Name = 0; 1903 PrevDecl = 0; 1904 } else { 1905 // If this is a use or a forward declaration, we're good. 1906 if (TK != TK_Definition) 1907 return PrevDecl; 1908 1909 // Diagnose attempts to redefine a tag. 1910 if (PrevTagDecl->isDefinition()) { 1911 Diag(NameLoc, diag::err_redefinition, Name->getName()); 1912 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 1913 // If this is a redefinition, recover by making this struct be 1914 // anonymous, which will make any later references get the previous 1915 // definition. 1916 Name = 0; 1917 } else { 1918 // Okay, this is definition of a previously declared or referenced 1919 // tag. Move the location of the decl to be the definition site. 1920 PrevDecl->setLocation(NameLoc); 1921 return PrevDecl; 1922 } 1923 } 1924 } 1925 // If we get here, this is a definition of a new struct type in a nested 1926 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new 1927 // type. 1928 } else { 1929 // PrevDecl is a namespace. 1930 if (isDeclInScope(PrevDecl, CurContext, S)) { 1931 // The tag name clashes with a namespace name, issue an error and 1932 // recover by making this tag be anonymous. 1933 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName()); 1934 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 1935 Name = 0; 1936 } 1937 } 1938 } 1939 1940 // If there is an identifier, use the location of the identifier as the 1941 // location of the decl, otherwise use the location of the struct/union 1942 // keyword. 1943 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 1944 1945 // Otherwise, if this is the first time we've seen this tag, create the decl. 1946 TagDecl *New; 1947 if (Kind == TagDecl::TK_enum) { 1948 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 1949 // enum X { A, B, C } D; D should chain to X. 1950 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0); 1951 // If this is an undefined enum, warn. 1952 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum); 1953 } else { 1954 // struct/union/class 1955 1956 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 1957 // struct X { int A; } D; D should chain to X. 1958 if (getLangOptions().CPlusPlus) 1959 // FIXME: Look for a way to use RecordDecl for simple structs. 1960 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name); 1961 else 1962 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name); 1963 } 1964 1965 // If this has an identifier, add it to the scope stack. 1966 if (Name) { 1967 // The scope passed in may not be a decl scope. Zip up the scope tree until 1968 // we find one that is. 1969 while ((S->getFlags() & Scope::DeclScope) == 0) 1970 S = S->getParent(); 1971 1972 // Add it to the decl chain. 1973 PushOnScopeChains(New, S); 1974 } 1975 1976 if (Attr) 1977 ProcessDeclAttributeList(New, Attr); 1978 return New; 1979} 1980 1981/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike 1982/// the logic for enums, we create separate decls for forward declarations. 1983/// This is called by ActOnTag, but eventually will replace its logic. 1984Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK, 1985 SourceLocation KWLoc, IdentifierInfo *Name, 1986 SourceLocation NameLoc, AttributeList *Attr) { 1987 1988 // If this is a named struct, check to see if there was a previous forward 1989 // declaration or definition. 1990 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up. 1991 ScopedDecl *PrevDecl = 1992 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S)); 1993 1994 if (PrevDecl) { 1995 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) && 1996 "unexpected Decl type"); 1997 1998 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 1999 // If this is a use of a previous tag, or if the tag is already declared 2000 // in the same scope (so that the definition/declaration completes or 2001 // rementions the tag), reuse the decl. 2002 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) { 2003 // Make sure that this wasn't declared as an enum and now used as a 2004 // struct or something similar. 2005 if (PrevTagDecl->getTagKind() != Kind) { 2006 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName()); 2007 Diag(PrevDecl->getLocation(), diag::err_previous_use); 2008 // Recover by making this an anonymous redefinition. 2009 Name = 0; 2010 PrevDecl = 0; 2011 } else { 2012 // If this is a use, return the original decl. 2013 2014 // FIXME: In the future, return a variant or some other clue 2015 // for the consumer of this Decl to know it doesn't own it. 2016 // For our current ASTs this shouldn't be a problem, but will 2017 // need to be changed with DeclGroups. 2018 if (TK == TK_Reference) 2019 return PrevDecl; 2020 2021 // The new decl is a definition? 2022 if (TK == TK_Definition) { 2023 // Diagnose attempts to redefine a tag. 2024 if (RecordDecl* DefRecord = 2025 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) { 2026 Diag(NameLoc, diag::err_redefinition, Name->getName()); 2027 Diag(DefRecord->getLocation(), diag::err_previous_definition); 2028 // If this is a redefinition, recover by making this struct be 2029 // anonymous, which will make any later references get the previous 2030 // definition. 2031 Name = 0; 2032 PrevDecl = 0; 2033 } 2034 // Okay, this is definition of a previously declared or referenced 2035 // tag. We're going to create a new Decl. 2036 } 2037 } 2038 // If we get here we have (another) forward declaration. Just create 2039 // a new decl. 2040 } 2041 else { 2042 // If we get here, this is a definition of a new struct type in a nested 2043 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 2044 // new decl/type. We set PrevDecl to NULL so that the Records 2045 // have distinct types. 2046 PrevDecl = 0; 2047 } 2048 } else { 2049 // PrevDecl is a namespace. 2050 if (isDeclInScope(PrevDecl, CurContext, S)) { 2051 // The tag name clashes with a namespace name, issue an error and 2052 // recover by making this tag be anonymous. 2053 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName()); 2054 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 2055 Name = 0; 2056 } 2057 } 2058 } 2059 2060 // If there is an identifier, use the location of the identifier as the 2061 // location of the decl, otherwise use the location of the struct/union 2062 // keyword. 2063 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 2064 2065 // Otherwise, if this is the first time we've seen this tag, create the decl. 2066 TagDecl *New; 2067 2068 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 2069 // struct X { int A; } D; D should chain to X. 2070 if (getLangOptions().CPlusPlus) 2071 // FIXME: Look for a way to use RecordDecl for simple structs. 2072 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name, 2073 dyn_cast_or_null<CXXRecordDecl>(PrevDecl)); 2074 else 2075 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 2076 dyn_cast_or_null<RecordDecl>(PrevDecl)); 2077 2078 // If this has an identifier, add it to the scope stack. 2079 if ((TK == TK_Definition || !PrevDecl) && Name) { 2080 // The scope passed in may not be a decl scope. Zip up the scope tree until 2081 // we find one that is. 2082 while ((S->getFlags() & Scope::DeclScope) == 0) 2083 S = S->getParent(); 2084 2085 // Add it to the decl chain. 2086 PushOnScopeChains(New, S); 2087 } 2088 2089 // Handle #pragma pack: if the #pragma pack stack has non-default 2090 // alignment, make up a packed attribute for this decl. These 2091 // attributes are checked when the ASTContext lays out the 2092 // structure. 2093 // 2094 // It is important for implementing the correct semantics that this 2095 // happen here (in act on tag decl). The #pragma pack stack is 2096 // maintained as a result of parser callbacks which can occur at 2097 // many points during the parsing of a struct declaration (because 2098 // the #pragma tokens are effectively skipped over during the 2099 // parsing of the struct). 2100 if (unsigned Alignment = PackContext.getAlignment()) 2101 New->addAttr(new PackedAttr(Alignment * 8)); 2102 2103 if (Attr) 2104 ProcessDeclAttributeList(New, Attr); 2105 2106 return New; 2107} 2108 2109 2110/// Collect the instance variables declared in an Objective-C object. Used in 2111/// the creation of structures from objects using the @defs directive. 2112static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx, 2113 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) { 2114 if (Class->getSuperClass()) 2115 CollectIvars(Class->getSuperClass(), Ctx, ivars); 2116 2117 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 2118 for (ObjCInterfaceDecl::ivar_iterator 2119 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) { 2120 2121 ObjCIvarDecl* ID = *I; 2122 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(), 2123 ID->getIdentifier(), 2124 ID->getType(), 2125 ID->getBitWidth())); 2126 } 2127} 2128 2129/// Called whenever @defs(ClassName) is encountered in the source. Inserts the 2130/// instance variables of ClassName into Decls. 2131void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart, 2132 IdentifierInfo *ClassName, 2133 llvm::SmallVectorImpl<DeclTy*> &Decls) { 2134 // Check that ClassName is a valid class 2135 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName); 2136 if (!Class) { 2137 Diag(DeclStart, diag::err_undef_interface, ClassName->getName()); 2138 return; 2139 } 2140 // Collect the instance variables 2141 CollectIvars(Class, Context, Decls); 2142} 2143 2144QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) { 2145 // This method tries to turn a variable array into a constant 2146 // array even when the size isn't an ICE. This is necessary 2147 // for compatibility with code that depends on gcc's buggy 2148 // constant expression folding, like struct {char x[(int)(char*)2];} 2149 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) { 2150 APValue Result; 2151 if (VLATy->getSizeExpr() && 2152 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) { 2153 llvm::APSInt &Res = Result.getInt(); 2154 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) 2155 return Context.getConstantArrayType(VLATy->getElementType(), 2156 Res, ArrayType::Normal, 0); 2157 } 2158 } 2159 return QualType(); 2160} 2161 2162/// ActOnField - Each field of a struct/union/class is passed into this in order 2163/// to create a FieldDecl object for it. 2164Sema::DeclTy *Sema::ActOnField(Scope *S, 2165 SourceLocation DeclStart, 2166 Declarator &D, ExprTy *BitfieldWidth) { 2167 IdentifierInfo *II = D.getIdentifier(); 2168 Expr *BitWidth = (Expr*)BitfieldWidth; 2169 SourceLocation Loc = DeclStart; 2170 if (II) Loc = D.getIdentifierLoc(); 2171 2172 // FIXME: Unnamed fields can be handled in various different ways, for 2173 // example, unnamed unions inject all members into the struct namespace! 2174 2175 if (BitWidth) { 2176 // TODO: Validate. 2177 //printf("WARNING: BITFIELDS IGNORED!\n"); 2178 2179 // 6.7.2.1p3 2180 // 6.7.2.1p4 2181 2182 } else { 2183 // Not a bitfield. 2184 2185 // validate II. 2186 2187 } 2188 2189 QualType T = GetTypeForDeclarator(D, S); 2190 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 2191 bool InvalidDecl = false; 2192 2193 // C99 6.7.2.1p8: A member of a structure or union may have any type other 2194 // than a variably modified type. 2195 if (T->isVariablyModifiedType()) { 2196 QualType FixedTy = TryFixInvalidVariablyModifiedType(T); 2197 if (!FixedTy.isNull()) { 2198 Diag(Loc, diag::warn_illegal_constant_array_size, Loc); 2199 T = FixedTy; 2200 } else { 2201 // FIXME: This diagnostic needs work 2202 Diag(Loc, diag::err_typecheck_illegal_vla, Loc); 2203 InvalidDecl = true; 2204 } 2205 } 2206 // FIXME: Chain fielddecls together. 2207 FieldDecl *NewFD; 2208 2209 if (getLangOptions().CPlusPlus) { 2210 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs. 2211 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext), 2212 Loc, II, T, BitWidth); 2213 if (II) 2214 PushOnScopeChains(NewFD, S); 2215 } 2216 else 2217 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth); 2218 2219 ProcessDeclAttributes(NewFD, D); 2220 2221 if (D.getInvalidType() || InvalidDecl) 2222 NewFD->setInvalidDecl(); 2223 return NewFD; 2224} 2225 2226/// TranslateIvarVisibility - Translate visibility from a token ID to an 2227/// AST enum value. 2228static ObjCIvarDecl::AccessControl 2229TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 2230 switch (ivarVisibility) { 2231 default: assert(0 && "Unknown visitibility kind"); 2232 case tok::objc_private: return ObjCIvarDecl::Private; 2233 case tok::objc_public: return ObjCIvarDecl::Public; 2234 case tok::objc_protected: return ObjCIvarDecl::Protected; 2235 case tok::objc_package: return ObjCIvarDecl::Package; 2236 } 2237} 2238 2239/// ActOnIvar - Each ivar field of an objective-c class is passed into this 2240/// in order to create an IvarDecl object for it. 2241Sema::DeclTy *Sema::ActOnIvar(Scope *S, 2242 SourceLocation DeclStart, 2243 Declarator &D, ExprTy *BitfieldWidth, 2244 tok::ObjCKeywordKind Visibility) { 2245 IdentifierInfo *II = D.getIdentifier(); 2246 Expr *BitWidth = (Expr*)BitfieldWidth; 2247 SourceLocation Loc = DeclStart; 2248 if (II) Loc = D.getIdentifierLoc(); 2249 2250 // FIXME: Unnamed fields can be handled in various different ways, for 2251 // example, unnamed unions inject all members into the struct namespace! 2252 2253 2254 if (BitWidth) { 2255 // TODO: Validate. 2256 //printf("WARNING: BITFIELDS IGNORED!\n"); 2257 2258 // 6.7.2.1p3 2259 // 6.7.2.1p4 2260 2261 } else { 2262 // Not a bitfield. 2263 2264 // validate II. 2265 2266 } 2267 2268 QualType T = GetTypeForDeclarator(D, S); 2269 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 2270 bool InvalidDecl = false; 2271 2272 // C99 6.7.2.1p8: A member of a structure or union may have any type other 2273 // than a variably modified type. 2274 if (T->isVariablyModifiedType()) { 2275 // FIXME: This diagnostic needs work 2276 Diag(Loc, diag::err_typecheck_illegal_vla, Loc); 2277 InvalidDecl = true; 2278 } 2279 2280 // Get the visibility (access control) for this ivar. 2281 ObjCIvarDecl::AccessControl ac = 2282 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 2283 : ObjCIvarDecl::None; 2284 2285 // Construct the decl. 2286 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac, 2287 (Expr *)BitfieldWidth); 2288 2289 // Process attributes attached to the ivar. 2290 ProcessDeclAttributes(NewID, D); 2291 2292 if (D.getInvalidType() || InvalidDecl) 2293 NewID->setInvalidDecl(); 2294 2295 return NewID; 2296} 2297 2298void Sema::ActOnFields(Scope* S, 2299 SourceLocation RecLoc, DeclTy *RecDecl, 2300 DeclTy **Fields, unsigned NumFields, 2301 SourceLocation LBrac, SourceLocation RBrac, 2302 AttributeList *Attr) { 2303 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl); 2304 assert(EnclosingDecl && "missing record or interface decl"); 2305 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 2306 2307 if (Record) 2308 if (RecordDecl* DefRecord = Record->getDefinition(Context)) { 2309 // Diagnose code like: 2310 // struct S { struct S {} X; }; 2311 // We discover this when we complete the outer S. Reject and ignore the 2312 // outer S. 2313 Diag(DefRecord->getLocation(), diag::err_nested_redefinition, 2314 DefRecord->getKindName()); 2315 Diag(RecLoc, diag::err_previous_definition); 2316 Record->setInvalidDecl(); 2317 return; 2318 } 2319 2320 // Verify that all the fields are okay. 2321 unsigned NumNamedMembers = 0; 2322 llvm::SmallVector<FieldDecl*, 32> RecFields; 2323 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs; 2324 2325 for (unsigned i = 0; i != NumFields; ++i) { 2326 2327 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i])); 2328 assert(FD && "missing field decl"); 2329 2330 // Remember all fields. 2331 RecFields.push_back(FD); 2332 2333 // Get the type for the field. 2334 Type *FDTy = FD->getType().getTypePtr(); 2335 2336 // C99 6.7.2.1p2 - A field may not be a function type. 2337 if (FDTy->isFunctionType()) { 2338 Diag(FD->getLocation(), diag::err_field_declared_as_function, 2339 FD->getName()); 2340 FD->setInvalidDecl(); 2341 EnclosingDecl->setInvalidDecl(); 2342 continue; 2343 } 2344 // C99 6.7.2.1p2 - A field may not be an incomplete type except... 2345 if (FDTy->isIncompleteType()) { 2346 if (!Record) { // Incomplete ivar type is always an error. 2347 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName()); 2348 FD->setInvalidDecl(); 2349 EnclosingDecl->setInvalidDecl(); 2350 continue; 2351 } 2352 if (i != NumFields-1 || // ... that the last member ... 2353 !Record->isStruct() || // ... of a structure ... 2354 !FDTy->isArrayType()) { //... may have incomplete array type. 2355 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName()); 2356 FD->setInvalidDecl(); 2357 EnclosingDecl->setInvalidDecl(); 2358 continue; 2359 } 2360 if (NumNamedMembers < 1) { //... must have more than named member ... 2361 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct, 2362 FD->getName()); 2363 FD->setInvalidDecl(); 2364 EnclosingDecl->setInvalidDecl(); 2365 continue; 2366 } 2367 // Okay, we have a legal flexible array member at the end of the struct. 2368 if (Record) 2369 Record->setHasFlexibleArrayMember(true); 2370 } 2371 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the 2372 /// field of another structure or the element of an array. 2373 if (const RecordType *FDTTy = FDTy->getAsRecordType()) { 2374 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 2375 // If this is a member of a union, then entire union becomes "flexible". 2376 if (Record && Record->isUnion()) { 2377 Record->setHasFlexibleArrayMember(true); 2378 } else { 2379 // If this is a struct/class and this is not the last element, reject 2380 // it. Note that GCC supports variable sized arrays in the middle of 2381 // structures. 2382 if (i != NumFields-1) { 2383 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct, 2384 FD->getName()); 2385 FD->setInvalidDecl(); 2386 EnclosingDecl->setInvalidDecl(); 2387 continue; 2388 } 2389 // We support flexible arrays at the end of structs in other structs 2390 // as an extension. 2391 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct, 2392 FD->getName()); 2393 if (Record) 2394 Record->setHasFlexibleArrayMember(true); 2395 } 2396 } 2397 } 2398 /// A field cannot be an Objective-c object 2399 if (FDTy->isObjCInterfaceType()) { 2400 Diag(FD->getLocation(), diag::err_statically_allocated_object, 2401 FD->getName()); 2402 FD->setInvalidDecl(); 2403 EnclosingDecl->setInvalidDecl(); 2404 continue; 2405 } 2406 // Keep track of the number of named members. 2407 if (IdentifierInfo *II = FD->getIdentifier()) { 2408 // Detect duplicate member names. 2409 if (!FieldIDs.insert(II)) { 2410 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName()); 2411 // Find the previous decl. 2412 SourceLocation PrevLoc; 2413 for (unsigned i = 0; ; ++i) { 2414 assert(i != RecFields.size() && "Didn't find previous def!"); 2415 if (RecFields[i]->getIdentifier() == II) { 2416 PrevLoc = RecFields[i]->getLocation(); 2417 break; 2418 } 2419 } 2420 Diag(PrevLoc, diag::err_previous_definition); 2421 FD->setInvalidDecl(); 2422 EnclosingDecl->setInvalidDecl(); 2423 continue; 2424 } 2425 ++NumNamedMembers; 2426 } 2427 } 2428 2429 // Okay, we successfully defined 'Record'. 2430 if (Record) { 2431 Record->defineBody(Context, &RecFields[0], RecFields.size()); 2432 // If this is a C++ record, HandleTagDeclDefinition will be invoked in 2433 // Sema::ActOnFinishCXXClassDef. 2434 if (!isa<CXXRecordDecl>(Record)) 2435 Consumer.HandleTagDeclDefinition(Record); 2436 } else { 2437 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]); 2438 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) 2439 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac); 2440 else if (ObjCImplementationDecl *IMPDecl = 2441 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 2442 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 2443 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size()); 2444 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 2445 } 2446 } 2447 2448 if (Attr) 2449 ProcessDeclAttributeList(Record, Attr); 2450} 2451 2452Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl, 2453 DeclTy *lastEnumConst, 2454 SourceLocation IdLoc, IdentifierInfo *Id, 2455 SourceLocation EqualLoc, ExprTy *val) { 2456 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl)); 2457 EnumConstantDecl *LastEnumConst = 2458 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst)); 2459 Expr *Val = static_cast<Expr*>(val); 2460 2461 // The scope passed in may not be a decl scope. Zip up the scope tree until 2462 // we find one that is. 2463 while ((S->getFlags() & Scope::DeclScope) == 0) 2464 S = S->getParent(); 2465 2466 // Verify that there isn't already something declared with this name in this 2467 // scope. 2468 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) { 2469 // When in C++, we may get a TagDecl with the same name; in this case the 2470 // enum constant will 'hide' the tag. 2471 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 2472 "Received TagDecl when not in C++!"); 2473 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 2474 if (isa<EnumConstantDecl>(PrevDecl)) 2475 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName()); 2476 else 2477 Diag(IdLoc, diag::err_redefinition, Id->getName()); 2478 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 2479 delete Val; 2480 return 0; 2481 } 2482 } 2483 2484 llvm::APSInt EnumVal(32); 2485 QualType EltTy; 2486 if (Val) { 2487 // Make sure to promote the operand type to int. 2488 UsualUnaryConversions(Val); 2489 2490 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 2491 SourceLocation ExpLoc; 2492 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) { 2493 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr, 2494 Id->getName()); 2495 delete Val; 2496 Val = 0; // Just forget about it. 2497 } else { 2498 EltTy = Val->getType(); 2499 } 2500 } 2501 2502 if (!Val) { 2503 if (LastEnumConst) { 2504 // Assign the last value + 1. 2505 EnumVal = LastEnumConst->getInitVal(); 2506 ++EnumVal; 2507 2508 // Check for overflow on increment. 2509 if (EnumVal < LastEnumConst->getInitVal()) 2510 Diag(IdLoc, diag::warn_enum_value_overflow); 2511 2512 EltTy = LastEnumConst->getType(); 2513 } else { 2514 // First value, set to zero. 2515 EltTy = Context.IntTy; 2516 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy))); 2517 } 2518 } 2519 2520 EnumConstantDecl *New = 2521 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy, 2522 Val, EnumVal, 2523 LastEnumConst); 2524 2525 // Register this decl in the current scope stack. 2526 PushOnScopeChains(New, S); 2527 return New; 2528} 2529 2530// FIXME: For consistency with ActOnFields(), we should have the parser 2531// pass in the source location for the left/right braces. 2532void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX, 2533 DeclTy **Elements, unsigned NumElements) { 2534 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX)); 2535 2536 if (Enum && Enum->isDefinition()) { 2537 // Diagnose code like: 2538 // enum e0 { 2539 // E0 = sizeof(enum e0 { E1 }) 2540 // }; 2541 Diag(Enum->getLocation(), diag::err_nested_redefinition, 2542 Enum->getName()); 2543 Diag(EnumLoc, diag::err_previous_definition); 2544 Enum->setInvalidDecl(); 2545 return; 2546 } 2547 // TODO: If the result value doesn't fit in an int, it must be a long or long 2548 // long value. ISO C does not support this, but GCC does as an extension, 2549 // emit a warning. 2550 unsigned IntWidth = Context.Target.getIntWidth(); 2551 2552 // Verify that all the values are okay, compute the size of the values, and 2553 // reverse the list. 2554 unsigned NumNegativeBits = 0; 2555 unsigned NumPositiveBits = 0; 2556 2557 // Keep track of whether all elements have type int. 2558 bool AllElementsInt = true; 2559 2560 EnumConstantDecl *EltList = 0; 2561 for (unsigned i = 0; i != NumElements; ++i) { 2562 EnumConstantDecl *ECD = 2563 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 2564 if (!ECD) continue; // Already issued a diagnostic. 2565 2566 // If the enum value doesn't fit in an int, emit an extension warning. 2567 const llvm::APSInt &InitVal = ECD->getInitVal(); 2568 assert(InitVal.getBitWidth() >= IntWidth && 2569 "Should have promoted value to int"); 2570 if (InitVal.getBitWidth() > IntWidth) { 2571 llvm::APSInt V(InitVal); 2572 V.trunc(IntWidth); 2573 V.extend(InitVal.getBitWidth()); 2574 if (V != InitVal) 2575 Diag(ECD->getLocation(), diag::ext_enum_value_not_int, 2576 InitVal.toString(10)); 2577 } 2578 2579 // Keep track of the size of positive and negative values. 2580 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 2581 NumPositiveBits = std::max(NumPositiveBits, 2582 (unsigned)InitVal.getActiveBits()); 2583 else 2584 NumNegativeBits = std::max(NumNegativeBits, 2585 (unsigned)InitVal.getMinSignedBits()); 2586 2587 // Keep track of whether every enum element has type int (very commmon). 2588 if (AllElementsInt) 2589 AllElementsInt = ECD->getType() == Context.IntTy; 2590 2591 ECD->setNextDeclarator(EltList); 2592 EltList = ECD; 2593 } 2594 2595 // Figure out the type that should be used for this enum. 2596 // FIXME: Support attribute(packed) on enums and -fshort-enums. 2597 QualType BestType; 2598 unsigned BestWidth; 2599 2600 if (NumNegativeBits) { 2601 // If there is a negative value, figure out the smallest integer type (of 2602 // int/long/longlong) that fits. 2603 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 2604 BestType = Context.IntTy; 2605 BestWidth = IntWidth; 2606 } else { 2607 BestWidth = Context.Target.getLongWidth(); 2608 2609 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) 2610 BestType = Context.LongTy; 2611 else { 2612 BestWidth = Context.Target.getLongLongWidth(); 2613 2614 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 2615 Diag(Enum->getLocation(), diag::warn_enum_too_large); 2616 BestType = Context.LongLongTy; 2617 } 2618 } 2619 } else { 2620 // If there is no negative value, figure out which of uint, ulong, ulonglong 2621 // fits. 2622 if (NumPositiveBits <= IntWidth) { 2623 BestType = Context.UnsignedIntTy; 2624 BestWidth = IntWidth; 2625 } else if (NumPositiveBits <= 2626 (BestWidth = Context.Target.getLongWidth())) { 2627 BestType = Context.UnsignedLongTy; 2628 } else { 2629 BestWidth = Context.Target.getLongLongWidth(); 2630 assert(NumPositiveBits <= BestWidth && 2631 "How could an initializer get larger than ULL?"); 2632 BestType = Context.UnsignedLongLongTy; 2633 } 2634 } 2635 2636 // Loop over all of the enumerator constants, changing their types to match 2637 // the type of the enum if needed. 2638 for (unsigned i = 0; i != NumElements; ++i) { 2639 EnumConstantDecl *ECD = 2640 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 2641 if (!ECD) continue; // Already issued a diagnostic. 2642 2643 // Standard C says the enumerators have int type, but we allow, as an 2644 // extension, the enumerators to be larger than int size. If each 2645 // enumerator value fits in an int, type it as an int, otherwise type it the 2646 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 2647 // that X has type 'int', not 'unsigned'. 2648 if (ECD->getType() == Context.IntTy) { 2649 // Make sure the init value is signed. 2650 llvm::APSInt IV = ECD->getInitVal(); 2651 IV.setIsSigned(true); 2652 ECD->setInitVal(IV); 2653 continue; // Already int type. 2654 } 2655 2656 // Determine whether the value fits into an int. 2657 llvm::APSInt InitVal = ECD->getInitVal(); 2658 bool FitsInInt; 2659 if (InitVal.isUnsigned() || !InitVal.isNegative()) 2660 FitsInInt = InitVal.getActiveBits() < IntWidth; 2661 else 2662 FitsInInt = InitVal.getMinSignedBits() <= IntWidth; 2663 2664 // If it fits into an integer type, force it. Otherwise force it to match 2665 // the enum decl type. 2666 QualType NewTy; 2667 unsigned NewWidth; 2668 bool NewSign; 2669 if (FitsInInt) { 2670 NewTy = Context.IntTy; 2671 NewWidth = IntWidth; 2672 NewSign = true; 2673 } else if (ECD->getType() == BestType) { 2674 // Already the right type! 2675 continue; 2676 } else { 2677 NewTy = BestType; 2678 NewWidth = BestWidth; 2679 NewSign = BestType->isSignedIntegerType(); 2680 } 2681 2682 // Adjust the APSInt value. 2683 InitVal.extOrTrunc(NewWidth); 2684 InitVal.setIsSigned(NewSign); 2685 ECD->setInitVal(InitVal); 2686 2687 // Adjust the Expr initializer and type. 2688 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr())); 2689 ECD->setType(NewTy); 2690 } 2691 2692 Enum->defineElements(EltList, BestType); 2693 Consumer.HandleTagDeclDefinition(Enum); 2694} 2695 2696Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, 2697 ExprTy *expr) { 2698 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr); 2699 2700 return FileScopeAsmDecl::Create(Context, Loc, AsmString); 2701} 2702 2703Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc, 2704 SourceLocation LBrace, 2705 SourceLocation RBrace, 2706 const char *Lang, 2707 unsigned StrSize, 2708 DeclTy *D) { 2709 LinkageSpecDecl::LanguageIDs Language; 2710 Decl *dcl = static_cast<Decl *>(D); 2711 if (strncmp(Lang, "\"C\"", StrSize) == 0) 2712 Language = LinkageSpecDecl::lang_c; 2713 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 2714 Language = LinkageSpecDecl::lang_cxx; 2715 else { 2716 Diag(Loc, diag::err_bad_language); 2717 return 0; 2718 } 2719 2720 // FIXME: Add all the various semantics of linkage specifications 2721 return LinkageSpecDecl::Create(Context, Loc, Language, dcl); 2722} 2723 2724void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name, 2725 ExprTy *alignment, SourceLocation PragmaLoc, 2726 SourceLocation LParenLoc, SourceLocation RParenLoc) { 2727 Expr *Alignment = static_cast<Expr *>(alignment); 2728 2729 // If specified then alignment must be a "small" power of two. 2730 unsigned AlignmentVal = 0; 2731 if (Alignment) { 2732 llvm::APSInt Val; 2733 if (!Alignment->isIntegerConstantExpr(Val, Context) || 2734 !Val.isPowerOf2() || 2735 Val.getZExtValue() > 16) { 2736 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment); 2737 delete Alignment; 2738 return; // Ignore 2739 } 2740 2741 AlignmentVal = (unsigned) Val.getZExtValue(); 2742 } 2743 2744 switch (Kind) { 2745 case Action::PPK_Default: // pack([n]) 2746 PackContext.setAlignment(AlignmentVal); 2747 break; 2748 2749 case Action::PPK_Show: // pack(show) 2750 // Show the current alignment, making sure to show the right value 2751 // for the default. 2752 AlignmentVal = PackContext.getAlignment(); 2753 // FIXME: This should come from the target. 2754 if (AlignmentVal == 0) 2755 AlignmentVal = 8; 2756 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal)); 2757 break; 2758 2759 case Action::PPK_Push: // pack(push [, id] [, [n]) 2760 PackContext.push(Name); 2761 // Set the new alignment if specified. 2762 if (Alignment) 2763 PackContext.setAlignment(AlignmentVal); 2764 break; 2765 2766 case Action::PPK_Pop: // pack(pop [, id] [, n]) 2767 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack: 2768 // "#pragma pack(pop, identifier, n) is undefined" 2769 if (Alignment && Name) 2770 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment); 2771 2772 // Do the pop. 2773 if (!PackContext.pop(Name)) { 2774 // If a name was specified then failure indicates the name 2775 // wasn't found. Otherwise failure indicates the stack was 2776 // empty. 2777 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed, 2778 Name ? "no record matching name" : "stack empty"); 2779 2780 // FIXME: Warn about popping named records as MSVC does. 2781 } else { 2782 // Pop succeeded, set the new alignment if specified. 2783 if (Alignment) 2784 PackContext.setAlignment(AlignmentVal); 2785 } 2786 break; 2787 2788 default: 2789 assert(0 && "Invalid #pragma pack kind."); 2790 } 2791} 2792 2793bool PragmaPackStack::pop(IdentifierInfo *Name) { 2794 if (Stack.empty()) 2795 return false; 2796 2797 // If name is empty just pop top. 2798 if (!Name) { 2799 Alignment = Stack.back().first; 2800 Stack.pop_back(); 2801 return true; 2802 } 2803 2804 // Otherwise, find the named record. 2805 for (unsigned i = Stack.size(); i != 0; ) { 2806 --i; 2807 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) { 2808 // Found it, pop up to and including this record. 2809 Alignment = Stack[i].first; 2810 Stack.erase(Stack.begin() + i, Stack.end()); 2811 return true; 2812 } 2813 } 2814 2815 return false; 2816} 2817