SemaDecl.cpp revision 27c8dc06f65d7abcf6a7e7f64a7960c9a150ca01
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 // C++ [dcl.init.ref]p1: 632 // A variable declared to be a T&, that is “reference to type T” 633 // (8.3.2), shall be initialized by an object, or function, of 634 // type T or by an object that can be converted into a T. 635 if (DeclType->isReferenceType()) 636 return CheckReferenceInit(Init, DeclType); 637 638 // C99 6.7.8p3: The type of the entity to be initialized shall be an array 639 // of unknown size ("[]") or an object type that is not a variable array type. 640 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType)) 641 return Diag(VAT->getSizeExpr()->getLocStart(), 642 diag::err_variable_object_no_init, 643 VAT->getSizeExpr()->getSourceRange()); 644 645 InitListExpr *InitList = dyn_cast<InitListExpr>(Init); 646 if (!InitList) { 647 // FIXME: Handle wide strings 648 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType)) 649 return CheckStringLiteralInit(strLiteral, DeclType); 650 651 // C99 6.7.8p16. 652 if (DeclType->isArrayType()) 653 return Diag(Init->getLocStart(), 654 diag::err_array_init_list_required, 655 Init->getSourceRange()); 656 657 return CheckSingleInitializer(Init, DeclType); 658 } 659 660 InitListChecker CheckInitList(this, InitList, DeclType); 661 return CheckInitList.HadError(); 662} 663 664Sema::DeclTy * 665Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) { 666 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl); 667 IdentifierInfo *II = D.getIdentifier(); 668 669 // All of these full declarators require an identifier. If it doesn't have 670 // one, the ParsedFreeStandingDeclSpec action should be used. 671 if (II == 0) { 672 Diag(D.getDeclSpec().getSourceRange().getBegin(), 673 diag::err_declarator_need_ident, 674 D.getDeclSpec().getSourceRange(), D.getSourceRange()); 675 return 0; 676 } 677 678 // The scope passed in may not be a decl scope. Zip up the scope tree until 679 // we find one that is. 680 while ((S->getFlags() & Scope::DeclScope) == 0) 681 S = S->getParent(); 682 683 // See if this is a redefinition of a variable in the same scope. 684 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S); 685 ScopedDecl *New; 686 bool InvalidDecl = false; 687 688 // In C++, the previous declaration we find might be a tag type 689 // (class or enum). In this case, the new declaration will hide the 690 // tag type. 691 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag) 692 PrevDecl = 0; 693 694 QualType R = GetTypeForDeclarator(D, S); 695 assert(!R.isNull() && "GetTypeForDeclarator() returned null type"); 696 697 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 698 // Check that there are no default arguments (C++ only). 699 if (getLangOptions().CPlusPlus) 700 CheckExtraCXXDefaultArguments(D); 701 702 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator); 703 if (!NewTD) return 0; 704 705 // Handle attributes prior to checking for duplicates in MergeVarDecl 706 ProcessDeclAttributes(NewTD, D); 707 // Merge the decl with the existing one if appropriate. If the decl is 708 // in an outer scope, it isn't the same thing. 709 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) { 710 NewTD = MergeTypeDefDecl(NewTD, PrevDecl); 711 if (NewTD == 0) return 0; 712 } 713 New = NewTD; 714 if (S->getFnParent() == 0) { 715 // C99 6.7.7p2: If a typedef name specifies a variably modified type 716 // then it shall have block scope. 717 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) { 718 // FIXME: Diagnostic needs to be fixed. 719 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla); 720 InvalidDecl = true; 721 } 722 } 723 } else if (R.getTypePtr()->isFunctionType()) { 724 FunctionDecl::StorageClass SC = FunctionDecl::None; 725 switch (D.getDeclSpec().getStorageClassSpec()) { 726 default: assert(0 && "Unknown storage class!"); 727 case DeclSpec::SCS_auto: 728 case DeclSpec::SCS_register: 729 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func, 730 R.getAsString()); 731 InvalidDecl = true; 732 break; 733 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break; 734 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break; 735 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break; 736 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break; 737 } 738 739 bool isInline = D.getDeclSpec().isInlineSpecified(); 740 FunctionDecl *NewFD; 741 if (D.getContext() == Declarator::MemberContext) { 742 // This is a C++ method declaration. 743 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext), 744 D.getIdentifierLoc(), II, R, 745 (SC == FunctionDecl::Static), isInline, 746 LastDeclarator); 747 } else { 748 NewFD = FunctionDecl::Create(Context, CurContext, 749 D.getIdentifierLoc(), 750 II, R, SC, isInline, LastDeclarator, 751 // FIXME: Move to DeclGroup... 752 D.getDeclSpec().getSourceRange().getBegin()); 753 } 754 // Handle attributes. 755 ProcessDeclAttributes(NewFD, D); 756 757 // Handle GNU asm-label extension (encoded as an attribute). 758 if (Expr *E = (Expr*) D.getAsmLabel()) { 759 // The parser guarantees this is a string. 760 StringLiteral *SE = cast<StringLiteral>(E); 761 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(), 762 SE->getByteLength()))); 763 } 764 765 // Copy the parameter declarations from the declarator D to 766 // the function declaration NewFD, if they are available. 767 if (D.getNumTypeObjects() > 0) { 768 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 769 770 // Create Decl objects for each parameter, adding them to the 771 // FunctionDecl. 772 llvm::SmallVector<ParmVarDecl*, 16> Params; 773 774 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 775 // function that takes no arguments, not a function that takes a 776 // single void argument. 777 // We let through "const void" here because Sema::GetTypeForDeclarator 778 // already checks for that case. 779 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 780 FTI.ArgInfo[0].Param && 781 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 782 // empty arg list, don't push any params. 783 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param; 784 785 // In C++, the empty parameter-type-list must be spelled "void"; a 786 // typedef of void is not permitted. 787 if (getLangOptions().CPlusPlus && 788 Param->getType().getUnqualifiedType() != Context.VoidTy) { 789 Diag(Param->getLocation(), diag::ext_param_typedef_of_void); 790 } 791 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 792 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) 793 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param); 794 } 795 796 NewFD->setParams(&Params[0], Params.size()); 797 } else if (R->getAsTypedefType()) { 798 // When we're declaring a function with a typedef, as in the 799 // following example, we'll need to synthesize (unnamed) 800 // parameters for use in the declaration. 801 // 802 // @code 803 // typedef void fn(int); 804 // fn f; 805 // @endcode 806 const FunctionTypeProto *FT = R->getAsFunctionTypeProto(); 807 if (!FT) { 808 // This is a typedef of a function with no prototype, so we 809 // don't need to do anything. 810 } else if ((FT->getNumArgs() == 0) || 811 (FT->getNumArgs() == 1 && !FT->isVariadic() && 812 FT->getArgType(0)->isVoidType())) { 813 // This is a zero-argument function. We don't need to do anything. 814 } else { 815 // Synthesize a parameter for each argument type. 816 llvm::SmallVector<ParmVarDecl*, 16> Params; 817 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin(); 818 ArgType != FT->arg_type_end(); ++ArgType) { 819 Params.push_back(ParmVarDecl::Create(Context, CurContext, 820 SourceLocation(), 0, 821 *ArgType, VarDecl::None, 822 0, 0)); 823 } 824 825 NewFD->setParams(&Params[0], Params.size()); 826 } 827 } 828 829 // Merge the decl with the existing one if appropriate. Since C functions 830 // are in a flat namespace, make sure we consider decls in outer scopes. 831 if (PrevDecl && 832 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, CurContext, S))) { 833 bool Redeclaration = false; 834 835 // If C++, determine whether NewFD is an overload of PrevDecl or 836 // a declaration that requires merging. If it's an overload, 837 // there's no more work to do here; we'll just add the new 838 // function to the scope. 839 OverloadedFunctionDecl::function_iterator MatchedDecl; 840 if (!getLangOptions().CPlusPlus || 841 !IsOverload(NewFD, PrevDecl, MatchedDecl)) { 842 Decl *OldDecl = PrevDecl; 843 844 // If PrevDecl was an overloaded function, extract the 845 // FunctionDecl that matched. 846 if (isa<OverloadedFunctionDecl>(PrevDecl)) 847 OldDecl = *MatchedDecl; 848 849 // NewFD and PrevDecl represent declarations that need to be 850 // merged. 851 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration); 852 853 if (NewFD == 0) return 0; 854 if (Redeclaration) { 855 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 856 857 if (OldDecl == PrevDecl) { 858 // Remove the name binding for the previous 859 // declaration. We'll add the binding back later, but then 860 // it will refer to the new declaration (which will 861 // contain more information). 862 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl)); 863 } else { 864 // We need to update the OverloadedFunctionDecl with the 865 // latest declaration of this function, so that name 866 // lookup will always refer to the latest declaration of 867 // this function. 868 *MatchedDecl = NewFD; 869 870 // Add the redeclaration to the current scope, since we'll 871 // be skipping PushOnScopeChains. 872 S->AddDecl(NewFD); 873 874 return NewFD; 875 } 876 } 877 } 878 } 879 New = NewFD; 880 881 // In C++, check default arguments now that we have merged decls. 882 if (getLangOptions().CPlusPlus) 883 CheckCXXDefaultArguments(NewFD); 884 } else { 885 // Check that there are no default arguments (C++ only). 886 if (getLangOptions().CPlusPlus) 887 CheckExtraCXXDefaultArguments(D); 888 889 if (R.getTypePtr()->isObjCInterfaceType()) { 890 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object, 891 D.getIdentifier()->getName()); 892 InvalidDecl = true; 893 } 894 895 VarDecl *NewVD; 896 VarDecl::StorageClass SC; 897 switch (D.getDeclSpec().getStorageClassSpec()) { 898 default: assert(0 && "Unknown storage class!"); 899 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break; 900 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break; 901 case DeclSpec::SCS_static: SC = VarDecl::Static; break; 902 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break; 903 case DeclSpec::SCS_register: SC = VarDecl::Register; break; 904 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break; 905 } 906 if (D.getContext() == Declarator::MemberContext) { 907 assert(SC == VarDecl::Static && "Invalid storage class for member!"); 908 // This is a static data member for a C++ class. 909 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext), 910 D.getIdentifierLoc(), II, 911 R, LastDeclarator); 912 } else { 913 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified(); 914 if (S->getFnParent() == 0) { 915 // C99 6.9p2: The storage-class specifiers auto and register shall not 916 // appear in the declaration specifiers in an external declaration. 917 if (SC == VarDecl::Auto || SC == VarDecl::Register) { 918 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope, 919 R.getAsString()); 920 InvalidDecl = true; 921 } 922 } 923 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(), 924 II, R, SC, LastDeclarator, 925 // FIXME: Move to DeclGroup... 926 D.getDeclSpec().getSourceRange().getBegin()); 927 NewVD->setThreadSpecified(ThreadSpecified); 928 } 929 // Handle attributes prior to checking for duplicates in MergeVarDecl 930 ProcessDeclAttributes(NewVD, D); 931 932 // Handle GNU asm-label extension (encoded as an attribute). 933 if (Expr *E = (Expr*) D.getAsmLabel()) { 934 // The parser guarantees this is a string. 935 StringLiteral *SE = cast<StringLiteral>(E); 936 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(), 937 SE->getByteLength()))); 938 } 939 940 // Emit an error if an address space was applied to decl with local storage. 941 // This includes arrays of objects with address space qualifiers, but not 942 // automatic variables that point to other address spaces. 943 // ISO/IEC TR 18037 S5.1.2 944 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) { 945 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl); 946 InvalidDecl = true; 947 } 948 // Merge the decl with the existing one if appropriate. If the decl is 949 // in an outer scope, it isn't the same thing. 950 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) { 951 NewVD = MergeVarDecl(NewVD, PrevDecl); 952 if (NewVD == 0) return 0; 953 } 954 New = NewVD; 955 } 956 957 // If this has an identifier, add it to the scope stack. 958 if (II) 959 PushOnScopeChains(New, S); 960 // If any semantic error occurred, mark the decl as invalid. 961 if (D.getInvalidType() || InvalidDecl) 962 New->setInvalidDecl(); 963 964 return New; 965} 966 967void Sema::InitializerElementNotConstant(const Expr *Init) { 968 Diag(Init->getExprLoc(), 969 diag::err_init_element_not_constant, Init->getSourceRange()); 970} 971 972bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) { 973 switch (Init->getStmtClass()) { 974 default: 975 InitializerElementNotConstant(Init); 976 return true; 977 case Expr::ParenExprClass: { 978 const ParenExpr* PE = cast<ParenExpr>(Init); 979 return CheckAddressConstantExpressionLValue(PE->getSubExpr()); 980 } 981 case Expr::CompoundLiteralExprClass: 982 return cast<CompoundLiteralExpr>(Init)->isFileScope(); 983 case Expr::DeclRefExprClass: { 984 const Decl *D = cast<DeclRefExpr>(Init)->getDecl(); 985 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 986 if (VD->hasGlobalStorage()) 987 return false; 988 InitializerElementNotConstant(Init); 989 return true; 990 } 991 if (isa<FunctionDecl>(D)) 992 return false; 993 InitializerElementNotConstant(Init); 994 return true; 995 } 996 case Expr::MemberExprClass: { 997 const MemberExpr *M = cast<MemberExpr>(Init); 998 if (M->isArrow()) 999 return CheckAddressConstantExpression(M->getBase()); 1000 return CheckAddressConstantExpressionLValue(M->getBase()); 1001 } 1002 case Expr::ArraySubscriptExprClass: { 1003 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)? 1004 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init); 1005 return CheckAddressConstantExpression(ASE->getBase()) || 1006 CheckArithmeticConstantExpression(ASE->getIdx()); 1007 } 1008 case Expr::StringLiteralClass: 1009 case Expr::PredefinedExprClass: 1010 return false; 1011 case Expr::UnaryOperatorClass: { 1012 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1013 1014 // C99 6.6p9 1015 if (Exp->getOpcode() == UnaryOperator::Deref) 1016 return CheckAddressConstantExpression(Exp->getSubExpr()); 1017 1018 InitializerElementNotConstant(Init); 1019 return true; 1020 } 1021 } 1022} 1023 1024bool Sema::CheckAddressConstantExpression(const Expr* Init) { 1025 switch (Init->getStmtClass()) { 1026 default: 1027 InitializerElementNotConstant(Init); 1028 return true; 1029 case Expr::ParenExprClass: 1030 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr()); 1031 case Expr::StringLiteralClass: 1032 case Expr::ObjCStringLiteralClass: 1033 return false; 1034 case Expr::CallExprClass: 1035 // __builtin___CFStringMakeConstantString is a valid constant l-value. 1036 if (cast<CallExpr>(Init)->isBuiltinCall() == 1037 Builtin::BI__builtin___CFStringMakeConstantString) 1038 return false; 1039 1040 InitializerElementNotConstant(Init); 1041 return true; 1042 1043 case Expr::UnaryOperatorClass: { 1044 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1045 1046 // C99 6.6p9 1047 if (Exp->getOpcode() == UnaryOperator::AddrOf) 1048 return CheckAddressConstantExpressionLValue(Exp->getSubExpr()); 1049 1050 if (Exp->getOpcode() == UnaryOperator::Extension) 1051 return CheckAddressConstantExpression(Exp->getSubExpr()); 1052 1053 InitializerElementNotConstant(Init); 1054 return true; 1055 } 1056 case Expr::BinaryOperatorClass: { 1057 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"? 1058 const BinaryOperator *Exp = cast<BinaryOperator>(Init); 1059 1060 Expr *PExp = Exp->getLHS(); 1061 Expr *IExp = Exp->getRHS(); 1062 if (IExp->getType()->isPointerType()) 1063 std::swap(PExp, IExp); 1064 1065 // FIXME: Should we pedwarn if IExp isn't an integer constant expression? 1066 return CheckAddressConstantExpression(PExp) || 1067 CheckArithmeticConstantExpression(IExp); 1068 } 1069 case Expr::ImplicitCastExprClass: 1070 case Expr::CStyleCastExprClass: { 1071 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr(); 1072 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) { 1073 // Check for implicit promotion 1074 if (SubExpr->getType()->isFunctionType() || 1075 SubExpr->getType()->isArrayType()) 1076 return CheckAddressConstantExpressionLValue(SubExpr); 1077 } 1078 1079 // Check for pointer->pointer cast 1080 if (SubExpr->getType()->isPointerType()) 1081 return CheckAddressConstantExpression(SubExpr); 1082 1083 if (SubExpr->getType()->isIntegralType()) { 1084 // Check for the special-case of a pointer->int->pointer cast; 1085 // this isn't standard, but some code requires it. See 1086 // PR2720 for an example. 1087 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) { 1088 if (SubCast->getSubExpr()->getType()->isPointerType()) { 1089 unsigned IntWidth = Context.getIntWidth(SubCast->getType()); 1090 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy); 1091 if (IntWidth >= PointerWidth) { 1092 return CheckAddressConstantExpression(SubCast->getSubExpr()); 1093 } 1094 } 1095 } 1096 } 1097 if (SubExpr->getType()->isArithmeticType()) { 1098 return CheckArithmeticConstantExpression(SubExpr); 1099 } 1100 1101 InitializerElementNotConstant(Init); 1102 return true; 1103 } 1104 case Expr::ConditionalOperatorClass: { 1105 // FIXME: Should we pedwarn here? 1106 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init); 1107 if (!Exp->getCond()->getType()->isArithmeticType()) { 1108 InitializerElementNotConstant(Init); 1109 return true; 1110 } 1111 if (CheckArithmeticConstantExpression(Exp->getCond())) 1112 return true; 1113 if (Exp->getLHS() && 1114 CheckAddressConstantExpression(Exp->getLHS())) 1115 return true; 1116 return CheckAddressConstantExpression(Exp->getRHS()); 1117 } 1118 case Expr::AddrLabelExprClass: 1119 return false; 1120 } 1121} 1122 1123static const Expr* FindExpressionBaseAddress(const Expr* E); 1124 1125static const Expr* FindExpressionBaseAddressLValue(const Expr* E) { 1126 switch (E->getStmtClass()) { 1127 default: 1128 return E; 1129 case Expr::ParenExprClass: { 1130 const ParenExpr* PE = cast<ParenExpr>(E); 1131 return FindExpressionBaseAddressLValue(PE->getSubExpr()); 1132 } 1133 case Expr::MemberExprClass: { 1134 const MemberExpr *M = cast<MemberExpr>(E); 1135 if (M->isArrow()) 1136 return FindExpressionBaseAddress(M->getBase()); 1137 return FindExpressionBaseAddressLValue(M->getBase()); 1138 } 1139 case Expr::ArraySubscriptExprClass: { 1140 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E); 1141 return FindExpressionBaseAddress(ASE->getBase()); 1142 } 1143 case Expr::UnaryOperatorClass: { 1144 const UnaryOperator *Exp = cast<UnaryOperator>(E); 1145 1146 if (Exp->getOpcode() == UnaryOperator::Deref) 1147 return FindExpressionBaseAddress(Exp->getSubExpr()); 1148 1149 return E; 1150 } 1151 } 1152} 1153 1154static const Expr* FindExpressionBaseAddress(const Expr* E) { 1155 switch (E->getStmtClass()) { 1156 default: 1157 return E; 1158 case Expr::ParenExprClass: { 1159 const ParenExpr* PE = cast<ParenExpr>(E); 1160 return FindExpressionBaseAddress(PE->getSubExpr()); 1161 } 1162 case Expr::UnaryOperatorClass: { 1163 const UnaryOperator *Exp = cast<UnaryOperator>(E); 1164 1165 // C99 6.6p9 1166 if (Exp->getOpcode() == UnaryOperator::AddrOf) 1167 return FindExpressionBaseAddressLValue(Exp->getSubExpr()); 1168 1169 if (Exp->getOpcode() == UnaryOperator::Extension) 1170 return FindExpressionBaseAddress(Exp->getSubExpr()); 1171 1172 return E; 1173 } 1174 case Expr::BinaryOperatorClass: { 1175 const BinaryOperator *Exp = cast<BinaryOperator>(E); 1176 1177 Expr *PExp = Exp->getLHS(); 1178 Expr *IExp = Exp->getRHS(); 1179 if (IExp->getType()->isPointerType()) 1180 std::swap(PExp, IExp); 1181 1182 return FindExpressionBaseAddress(PExp); 1183 } 1184 case Expr::ImplicitCastExprClass: { 1185 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr(); 1186 1187 // Check for implicit promotion 1188 if (SubExpr->getType()->isFunctionType() || 1189 SubExpr->getType()->isArrayType()) 1190 return FindExpressionBaseAddressLValue(SubExpr); 1191 1192 // Check for pointer->pointer cast 1193 if (SubExpr->getType()->isPointerType()) 1194 return FindExpressionBaseAddress(SubExpr); 1195 1196 // We assume that we have an arithmetic expression here; 1197 // if we don't, we'll figure it out later 1198 return 0; 1199 } 1200 case Expr::CStyleCastExprClass: { 1201 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr(); 1202 1203 // Check for pointer->pointer cast 1204 if (SubExpr->getType()->isPointerType()) 1205 return FindExpressionBaseAddress(SubExpr); 1206 1207 // We assume that we have an arithmetic expression here; 1208 // if we don't, we'll figure it out later 1209 return 0; 1210 } 1211 } 1212} 1213 1214bool Sema::CheckArithmeticConstantExpression(const Expr* Init) { 1215 switch (Init->getStmtClass()) { 1216 default: 1217 InitializerElementNotConstant(Init); 1218 return true; 1219 case Expr::ParenExprClass: { 1220 const ParenExpr* PE = cast<ParenExpr>(Init); 1221 return CheckArithmeticConstantExpression(PE->getSubExpr()); 1222 } 1223 case Expr::FloatingLiteralClass: 1224 case Expr::IntegerLiteralClass: 1225 case Expr::CharacterLiteralClass: 1226 case Expr::ImaginaryLiteralClass: 1227 case Expr::TypesCompatibleExprClass: 1228 case Expr::CXXBoolLiteralExprClass: 1229 return false; 1230 case Expr::CallExprClass: { 1231 const CallExpr *CE = cast<CallExpr>(Init); 1232 1233 // Allow any constant foldable calls to builtins. 1234 if (CE->isBuiltinCall() && CE->isEvaluatable(Context)) 1235 return false; 1236 1237 InitializerElementNotConstant(Init); 1238 return true; 1239 } 1240 case Expr::DeclRefExprClass: { 1241 const Decl *D = cast<DeclRefExpr>(Init)->getDecl(); 1242 if (isa<EnumConstantDecl>(D)) 1243 return false; 1244 InitializerElementNotConstant(Init); 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 InitializerElementNotConstant(Init); 1253 return true; 1254 case Expr::UnaryOperatorClass: { 1255 const UnaryOperator *Exp = cast<UnaryOperator>(Init); 1256 1257 switch (Exp->getOpcode()) { 1258 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs. 1259 // See C99 6.6p3. 1260 default: 1261 InitializerElementNotConstant(Init); 1262 return true; 1263 case UnaryOperator::SizeOf: 1264 case UnaryOperator::AlignOf: 1265 case UnaryOperator::OffsetOf: 1266 // sizeof(E) is a constantexpr if and only if E is not evaluted. 1267 // See C99 6.5.3.4p2 and 6.6p3. 1268 if (Exp->getSubExpr()->getType()->isConstantSizeType()) 1269 return false; 1270 InitializerElementNotConstant(Init); 1271 return true; 1272 case UnaryOperator::Extension: 1273 case UnaryOperator::LNot: 1274 case UnaryOperator::Plus: 1275 case UnaryOperator::Minus: 1276 case UnaryOperator::Not: 1277 return CheckArithmeticConstantExpression(Exp->getSubExpr()); 1278 } 1279 } 1280 case Expr::SizeOfAlignOfTypeExprClass: { 1281 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init); 1282 // Special check for void types, which are allowed as an extension 1283 if (Exp->getArgumentType()->isVoidType()) 1284 return false; 1285 // alignof always evaluates to a constant. 1286 // FIXME: is sizeof(int[3.0]) a constant expression? 1287 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) { 1288 InitializerElementNotConstant(Init); 1289 return true; 1290 } 1291 return false; 1292 } 1293 case Expr::BinaryOperatorClass: { 1294 const BinaryOperator *Exp = cast<BinaryOperator>(Init); 1295 1296 if (Exp->getLHS()->getType()->isArithmeticType() && 1297 Exp->getRHS()->getType()->isArithmeticType()) { 1298 return CheckArithmeticConstantExpression(Exp->getLHS()) || 1299 CheckArithmeticConstantExpression(Exp->getRHS()); 1300 } 1301 1302 if (Exp->getLHS()->getType()->isPointerType() && 1303 Exp->getRHS()->getType()->isPointerType()) { 1304 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS()); 1305 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS()); 1306 1307 // Only allow a null (constant integer) base; we could 1308 // allow some additional cases if necessary, but this 1309 // is sufficient to cover offsetof-like constructs. 1310 if (!LHSBase && !RHSBase) { 1311 return CheckAddressConstantExpression(Exp->getLHS()) || 1312 CheckAddressConstantExpression(Exp->getRHS()); 1313 } 1314 } 1315 1316 InitializerElementNotConstant(Init); 1317 return true; 1318 } 1319 case Expr::ImplicitCastExprClass: 1320 case Expr::CStyleCastExprClass: { 1321 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr(); 1322 if (SubExpr->getType()->isArithmeticType()) 1323 return CheckArithmeticConstantExpression(SubExpr); 1324 1325 if (SubExpr->getType()->isPointerType()) { 1326 const Expr* Base = FindExpressionBaseAddress(SubExpr); 1327 // If the pointer has a null base, this is an offsetof-like construct 1328 if (!Base) 1329 return CheckAddressConstantExpression(SubExpr); 1330 } 1331 1332 InitializerElementNotConstant(Init); 1333 return true; 1334 } 1335 case Expr::ConditionalOperatorClass: { 1336 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init); 1337 1338 // If GNU extensions are disabled, we require all operands to be arithmetic 1339 // constant expressions. 1340 if (getLangOptions().NoExtensions) { 1341 return CheckArithmeticConstantExpression(Exp->getCond()) || 1342 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) || 1343 CheckArithmeticConstantExpression(Exp->getRHS()); 1344 } 1345 1346 // Otherwise, we have to emulate some of the behavior of fold here. 1347 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant 1348 // because it can constant fold things away. To retain compatibility with 1349 // GCC code, we see if we can fold the condition to a constant (which we 1350 // should always be able to do in theory). If so, we only require the 1351 // specified arm of the conditional to be a constant. This is a horrible 1352 // hack, but is require by real world code that uses __builtin_constant_p. 1353 APValue Val; 1354 if (!Exp->getCond()->tryEvaluate(Val, Context)) { 1355 // If the tryEvaluate couldn't fold it, CheckArithmeticConstantExpression 1356 // won't be able to either. Use it to emit the diagnostic though. 1357 bool Res = CheckArithmeticConstantExpression(Exp->getCond()); 1358 assert(Res && "tryEvaluate couldn't evaluate this constant?"); 1359 return Res; 1360 } 1361 1362 // Verify that the side following the condition is also a constant. 1363 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS(); 1364 if (Val.getInt() == 0) 1365 std::swap(TrueSide, FalseSide); 1366 1367 if (TrueSide && CheckArithmeticConstantExpression(TrueSide)) 1368 return true; 1369 1370 // Okay, the evaluated side evaluates to a constant, so we accept this. 1371 // Check to see if the other side is obviously not a constant. If so, 1372 // emit a warning that this is a GNU extension. 1373 if (FalseSide && !FalseSide->isEvaluatable(Context)) 1374 Diag(Init->getExprLoc(), 1375 diag::ext_typecheck_expression_not_constant_but_accepted, 1376 FalseSide->getSourceRange()); 1377 return false; 1378 } 1379 } 1380} 1381 1382bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 1383 Init = Init->IgnoreParens(); 1384 1385 // Look through CXXDefaultArgExprs; they have no meaning in this context. 1386 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init)) 1387 return CheckForConstantInitializer(DAE->getExpr(), DclT); 1388 1389 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init)) 1390 return CheckForConstantInitializer(e->getInitializer(), DclT); 1391 1392 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) { 1393 unsigned numInits = Exp->getNumInits(); 1394 for (unsigned i = 0; i < numInits; i++) { 1395 // FIXME: Need to get the type of the declaration for C++, 1396 // because it could be a reference? 1397 if (CheckForConstantInitializer(Exp->getInit(i), 1398 Exp->getInit(i)->getType())) 1399 return true; 1400 } 1401 return false; 1402 } 1403 1404 if (Init->isNullPointerConstant(Context)) 1405 return false; 1406 if (Init->getType()->isArithmeticType()) { 1407 QualType InitTy = Context.getCanonicalType(Init->getType()) 1408 .getUnqualifiedType(); 1409 if (InitTy == Context.BoolTy) { 1410 // Special handling for pointers implicitly cast to bool; 1411 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level. 1412 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) { 1413 Expr* SubE = ICE->getSubExpr(); 1414 if (SubE->getType()->isPointerType() || 1415 SubE->getType()->isArrayType() || 1416 SubE->getType()->isFunctionType()) { 1417 return CheckAddressConstantExpression(Init); 1418 } 1419 } 1420 } else if (InitTy->isIntegralType()) { 1421 Expr* SubE = 0; 1422 if (CastExpr* CE = dyn_cast<CastExpr>(Init)) 1423 SubE = CE->getSubExpr(); 1424 // Special check for pointer cast to int; we allow as an extension 1425 // an address constant cast to an integer if the integer 1426 // is of an appropriate width (this sort of code is apparently used 1427 // in some places). 1428 // FIXME: Add pedwarn? 1429 // FIXME: Don't allow bitfields here! Need the FieldDecl for that. 1430 if (SubE && (SubE->getType()->isPointerType() || 1431 SubE->getType()->isArrayType() || 1432 SubE->getType()->isFunctionType())) { 1433 unsigned IntWidth = Context.getTypeSize(Init->getType()); 1434 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy); 1435 if (IntWidth >= PointerWidth) 1436 return CheckAddressConstantExpression(Init); 1437 } 1438 } 1439 1440 return CheckArithmeticConstantExpression(Init); 1441 } 1442 1443 if (Init->getType()->isPointerType()) 1444 return CheckAddressConstantExpression(Init); 1445 1446 // An array type at the top level that isn't an init-list must 1447 // be a string literal 1448 if (Init->getType()->isArrayType()) 1449 return false; 1450 1451 if (Init->getType()->isFunctionType()) 1452 return false; 1453 1454 // Allow block exprs at top level. 1455 if (Init->getType()->isBlockPointerType()) 1456 return false; 1457 1458 InitializerElementNotConstant(Init); 1459 return true; 1460} 1461 1462void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) { 1463 Decl *RealDecl = static_cast<Decl *>(dcl); 1464 Expr *Init = static_cast<Expr *>(init); 1465 assert(Init && "missing initializer"); 1466 1467 // If there is no declaration, there was an error parsing it. Just ignore 1468 // the initializer. 1469 if (RealDecl == 0) { 1470 delete Init; 1471 return; 1472 } 1473 1474 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 1475 if (!VDecl) { 1476 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(), 1477 diag::err_illegal_initializer); 1478 RealDecl->setInvalidDecl(); 1479 return; 1480 } 1481 // Get the decls type and save a reference for later, since 1482 // CheckInitializerTypes may change it. 1483 QualType DclT = VDecl->getType(), SavT = DclT; 1484 if (VDecl->isBlockVarDecl()) { 1485 VarDecl::StorageClass SC = VDecl->getStorageClass(); 1486 if (SC == VarDecl::Extern) { // C99 6.7.8p5 1487 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 1488 VDecl->setInvalidDecl(); 1489 } else if (!VDecl->isInvalidDecl()) { 1490 if (CheckInitializerTypes(Init, DclT)) 1491 VDecl->setInvalidDecl(); 1492 1493 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 1494 if (!getLangOptions().CPlusPlus) { 1495 if (SC == VarDecl::Static) // C99 6.7.8p4. 1496 CheckForConstantInitializer(Init, DclT); 1497 } 1498 } 1499 } else if (VDecl->isFileVarDecl()) { 1500 if (VDecl->getStorageClass() == VarDecl::Extern) 1501 Diag(VDecl->getLocation(), diag::warn_extern_init); 1502 if (!VDecl->isInvalidDecl()) 1503 if (CheckInitializerTypes(Init, DclT)) 1504 VDecl->setInvalidDecl(); 1505 1506 // C++ 3.6.2p2, allow dynamic initialization of static initializers. 1507 if (!getLangOptions().CPlusPlus) { 1508 // C99 6.7.8p4. All file scoped initializers need to be constant. 1509 CheckForConstantInitializer(Init, DclT); 1510 } 1511 } 1512 // If the type changed, it means we had an incomplete type that was 1513 // completed by the initializer. For example: 1514 // int ary[] = { 1, 3, 5 }; 1515 // "ary" transitions from a VariableArrayType to a ConstantArrayType. 1516 if (!VDecl->isInvalidDecl() && (DclT != SavT)) { 1517 VDecl->setType(DclT); 1518 Init->setType(DclT); 1519 } 1520 1521 // Attach the initializer to the decl. 1522 VDecl->setInit(Init); 1523 return; 1524} 1525 1526void Sema::ActOnUninitializedDecl(DeclTy *dcl) { 1527 Decl *RealDecl = static_cast<Decl *>(dcl); 1528 1529 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 1530 QualType Type = Var->getType(); 1531 // C++ [dcl.init.ref]p3: 1532 // The initializer can be omitted for a reference only in a 1533 // parameter declaration (8.3.5), in the declaration of a 1534 // function return type, in the declaration of a class member 1535 // within its class declaration (9.2), and where the extern 1536 // specifier is explicitly used. 1537 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) 1538 Diag(Var->getLocation(), 1539 diag::err_reference_var_requires_init, 1540 Var->getName(), 1541 SourceRange(Var->getLocation(), Var->getLocation())); 1542 1543 // C++ [dcl.init]p9: 1544 // 1545 // If no initializer is specified for an object, and the 1546 // object is of (possibly cv-qualified) non-POD class type (or 1547 // array thereof), the object shall be default-initialized; if 1548 // the object is of const-qualified type, the underlying class 1549 // type shall have a user-declared default 1550 // constructor. Otherwise, if no initializer is specified for 1551 // an object, the object and its subobjects, if any, have an 1552 // indeterminate initial value; if the object or any of its 1553 // subobjects are of const-qualified type, the program is 1554 // ill-formed. 1555 // 1556 // This isn't technically an error in C, so we don't diagnose it. 1557 // 1558 // FIXME: Actually perform the POD/user-defined default 1559 // constructor check. 1560 if (getLangOptions().CPlusPlus && 1561 Context.getCanonicalType(Type).isConstQualified()) 1562 Diag(Var->getLocation(), 1563 diag::err_const_var_requires_init, 1564 Var->getName(), 1565 SourceRange(Var->getLocation(), Var->getLocation())); 1566 } 1567} 1568 1569/// The declarators are chained together backwards, reverse the list. 1570Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) { 1571 // Often we have single declarators, handle them quickly. 1572 Decl *GroupDecl = static_cast<Decl*>(group); 1573 if (GroupDecl == 0) 1574 return 0; 1575 1576 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl); 1577 ScopedDecl *NewGroup = 0; 1578 if (Group->getNextDeclarator() == 0) 1579 NewGroup = Group; 1580 else { // reverse the list. 1581 while (Group) { 1582 ScopedDecl *Next = Group->getNextDeclarator(); 1583 Group->setNextDeclarator(NewGroup); 1584 NewGroup = Group; 1585 Group = Next; 1586 } 1587 } 1588 // Perform semantic analysis that depends on having fully processed both 1589 // the declarator and initializer. 1590 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) { 1591 VarDecl *IDecl = dyn_cast<VarDecl>(ID); 1592 if (!IDecl) 1593 continue; 1594 QualType T = IDecl->getType(); 1595 1596 // C99 6.7.5.2p2: If an identifier is declared to be an object with 1597 // static storage duration, it shall not have a variable length array. 1598 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) && 1599 IDecl->getStorageClass() == VarDecl::Static) { 1600 if (T->isVariableArrayType()) { 1601 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla); 1602 IDecl->setInvalidDecl(); 1603 } 1604 } 1605 // Block scope. C99 6.7p7: If an identifier for an object is declared with 1606 // no linkage (C99 6.2.2p6), the type for the object shall be complete... 1607 if (IDecl->isBlockVarDecl() && 1608 IDecl->getStorageClass() != VarDecl::Extern) { 1609 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) { 1610 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type, 1611 T.getAsString()); 1612 IDecl->setInvalidDecl(); 1613 } 1614 } 1615 // File scope. C99 6.9.2p2: A declaration of an identifier for and 1616 // object that has file scope without an initializer, and without a 1617 // storage-class specifier or with the storage-class specifier "static", 1618 // constitutes a tentative definition. Note: A tentative definition with 1619 // external linkage is valid (C99 6.2.2p5). 1620 if (isTentativeDefinition(IDecl)) { 1621 if (T->isIncompleteArrayType()) { 1622 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete 1623 // array to be completed. Don't issue a diagnostic. 1624 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) { 1625 // C99 6.9.2p3: If the declaration of an identifier for an object is 1626 // a tentative definition and has internal linkage (C99 6.2.2p3), the 1627 // declared type shall not be an incomplete type. 1628 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type, 1629 T.getAsString()); 1630 IDecl->setInvalidDecl(); 1631 } 1632 } 1633 if (IDecl->isFileVarDecl()) 1634 CheckForFileScopedRedefinitions(S, IDecl); 1635 } 1636 return NewGroup; 1637} 1638 1639/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 1640/// to introduce parameters into function prototype scope. 1641Sema::DeclTy * 1642Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 1643 const DeclSpec &DS = D.getDeclSpec(); 1644 1645 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 1646 VarDecl::StorageClass StorageClass = VarDecl::None; 1647 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 1648 StorageClass = VarDecl::Register; 1649 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 1650 Diag(DS.getStorageClassSpecLoc(), 1651 diag::err_invalid_storage_class_in_func_decl); 1652 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1653 } 1654 if (DS.isThreadSpecified()) { 1655 Diag(DS.getThreadSpecLoc(), 1656 diag::err_invalid_storage_class_in_func_decl); 1657 D.getMutableDeclSpec().ClearStorageClassSpecs(); 1658 } 1659 1660 // Check that there are no default arguments inside the type of this 1661 // parameter (C++ only). 1662 if (getLangOptions().CPlusPlus) 1663 CheckExtraCXXDefaultArguments(D); 1664 1665 // In this context, we *do not* check D.getInvalidType(). If the declarator 1666 // type was invalid, GetTypeForDeclarator() still returns a "valid" type, 1667 // though it will not reflect the user specified type. 1668 QualType parmDeclType = GetTypeForDeclarator(D, S); 1669 1670 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type"); 1671 1672 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope. 1673 // Can this happen for params? We already checked that they don't conflict 1674 // among each other. Here they can only shadow globals, which is ok. 1675 IdentifierInfo *II = D.getIdentifier(); 1676 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) { 1677 if (S->isDeclScope(PrevDecl)) { 1678 Diag(D.getIdentifierLoc(), diag::err_param_redefinition, 1679 dyn_cast<NamedDecl>(PrevDecl)->getName()); 1680 1681 // Recover by removing the name 1682 II = 0; 1683 D.SetIdentifier(0, D.getIdentifierLoc()); 1684 } 1685 } 1686 1687 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]). 1688 // Doing the promotion here has a win and a loss. The win is the type for 1689 // both Decl's and DeclRefExpr's will match (a convenient invariant for the 1690 // code generator). The loss is the orginal type isn't preserved. For example: 1691 // 1692 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *" 1693 // int blockvardecl[5]; 1694 // sizeof(parmvardecl); // size == 4 1695 // sizeof(blockvardecl); // size == 20 1696 // } 1697 // 1698 // For expressions, all implicit conversions are captured using the 1699 // ImplicitCastExpr AST node (we have no such mechanism for Decl's). 1700 // 1701 // FIXME: If a source translation tool needs to see the original type, then 1702 // we need to consider storing both types (in ParmVarDecl)... 1703 // 1704 if (parmDeclType->isArrayType()) { 1705 // int x[restrict 4] -> int *restrict 1706 parmDeclType = Context.getArrayDecayedType(parmDeclType); 1707 } else if (parmDeclType->isFunctionType()) 1708 parmDeclType = Context.getPointerType(parmDeclType); 1709 1710 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext, 1711 D.getIdentifierLoc(), II, 1712 parmDeclType, StorageClass, 1713 0, 0); 1714 1715 if (D.getInvalidType()) 1716 New->setInvalidDecl(); 1717 1718 if (II) 1719 PushOnScopeChains(New, S); 1720 1721 ProcessDeclAttributes(New, D); 1722 return New; 1723 1724} 1725 1726Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 1727 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 1728 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function && 1729 "Not a function declarator!"); 1730 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun; 1731 1732 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 1733 // for a K&R function. 1734 if (!FTI.hasPrototype) { 1735 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 1736 if (FTI.ArgInfo[i].Param == 0) { 1737 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared, 1738 FTI.ArgInfo[i].Ident->getName()); 1739 // Implicitly declare the argument as type 'int' for lack of a better 1740 // type. 1741 DeclSpec DS; 1742 const char* PrevSpec; // unused 1743 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 1744 PrevSpec); 1745 Declarator ParamD(DS, Declarator::KNRTypeListContext); 1746 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 1747 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD); 1748 } 1749 } 1750 } else { 1751 // FIXME: Diagnose arguments without names in C. 1752 } 1753 1754 Scope *GlobalScope = FnBodyScope->getParent(); 1755 1756 // See if this is a redefinition. 1757 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary, 1758 GlobalScope); 1759 if (PrevDcl && isDeclInScope(PrevDcl, CurContext)) { 1760 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) { 1761 const FunctionDecl *Definition; 1762 if (FD->getBody(Definition)) { 1763 Diag(D.getIdentifierLoc(), diag::err_redefinition, 1764 D.getIdentifier()->getName()); 1765 Diag(Definition->getLocation(), diag::err_previous_definition); 1766 } 1767 } 1768 } 1769 1770 return ActOnStartOfFunctionDef(FnBodyScope, 1771 ActOnDeclarator(GlobalScope, D, 0)); 1772} 1773 1774Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) { 1775 Decl *decl = static_cast<Decl*>(D); 1776 FunctionDecl *FD = cast<FunctionDecl>(decl); 1777 PushDeclContext(FD); 1778 1779 // Check the validity of our function parameters 1780 CheckParmsForFunctionDef(FD); 1781 1782 // Introduce our parameters into the function scope 1783 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 1784 ParmVarDecl *Param = FD->getParamDecl(p); 1785 // If this has an identifier, add it to the scope stack. 1786 if (Param->getIdentifier()) 1787 PushOnScopeChains(Param, FnBodyScope); 1788 } 1789 1790 return FD; 1791} 1792 1793Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) { 1794 Decl *dcl = static_cast<Decl *>(D); 1795 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) { 1796 FD->setBody((Stmt*)Body); 1797 assert(FD == getCurFunctionDecl() && "Function parsing confused"); 1798 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 1799 MD->setBody((Stmt*)Body); 1800 } else 1801 return 0; 1802 PopDeclContext(); 1803 // Verify and clean out per-function state. 1804 1805 // Check goto/label use. 1806 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator 1807 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) { 1808 // Verify that we have no forward references left. If so, there was a goto 1809 // or address of a label taken, but no definition of it. Label fwd 1810 // definitions are indicated with a null substmt. 1811 if (I->second->getSubStmt() == 0) { 1812 LabelStmt *L = I->second; 1813 // Emit error. 1814 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName()); 1815 1816 // At this point, we have gotos that use the bogus label. Stitch it into 1817 // the function body so that they aren't leaked and that the AST is well 1818 // formed. 1819 if (Body) { 1820 L->setSubStmt(new NullStmt(L->getIdentLoc())); 1821 cast<CompoundStmt>((Stmt*)Body)->push_back(L); 1822 } else { 1823 // The whole function wasn't parsed correctly, just delete this. 1824 delete L; 1825 } 1826 } 1827 } 1828 LabelMap.clear(); 1829 1830 return D; 1831} 1832 1833/// ImplicitlyDefineFunction - An undeclared identifier was used in a function 1834/// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 1835ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 1836 IdentifierInfo &II, Scope *S) { 1837 // Extension in C99. Legal in C90, but warn about it. 1838 if (getLangOptions().C99) 1839 Diag(Loc, diag::ext_implicit_function_decl, II.getName()); 1840 else 1841 Diag(Loc, diag::warn_implicit_function_decl, II.getName()); 1842 1843 // FIXME: handle stuff like: 1844 // void foo() { extern float X(); } 1845 // void bar() { X(); } <-- implicit decl for X in another scope. 1846 1847 // Set a Declarator for the implicit definition: int foo(); 1848 const char *Dummy; 1849 DeclSpec DS; 1850 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy); 1851 Error = Error; // Silence warning. 1852 assert(!Error && "Error setting up implicit decl!"); 1853 Declarator D(DS, Declarator::BlockContext); 1854 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc)); 1855 D.SetIdentifier(&II, Loc); 1856 1857 // Insert this function into translation-unit scope. 1858 1859 DeclContext *PrevDC = CurContext; 1860 CurContext = Context.getTranslationUnitDecl(); 1861 1862 FunctionDecl *FD = 1863 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0))); 1864 FD->setImplicit(); 1865 1866 CurContext = PrevDC; 1867 1868 return FD; 1869} 1870 1871 1872TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 1873 ScopedDecl *LastDeclarator) { 1874 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 1875 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 1876 1877 // Scope manipulation handled by caller. 1878 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 1879 D.getIdentifierLoc(), 1880 D.getIdentifier(), 1881 T, LastDeclarator); 1882 if (D.getInvalidType()) 1883 NewTD->setInvalidDecl(); 1884 return NewTD; 1885} 1886 1887/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 1888/// former case, Name will be non-null. In the later case, Name will be null. 1889/// TagType indicates what kind of tag this is. TK indicates whether this is a 1890/// reference/declaration/definition of a tag. 1891Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK, 1892 SourceLocation KWLoc, IdentifierInfo *Name, 1893 SourceLocation NameLoc, AttributeList *Attr) { 1894 // If this is a use of an existing tag, it must have a name. 1895 assert((Name != 0 || TK == TK_Definition) && 1896 "Nameless record must be a definition!"); 1897 1898 TagDecl::TagKind Kind; 1899 switch (TagType) { 1900 default: assert(0 && "Unknown tag type!"); 1901 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break; 1902 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break; 1903 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break; 1904 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break; 1905 } 1906 1907 // Two code paths: a new one for structs/unions/classes where we create 1908 // separate decls for forward declarations, and an old (eventually to 1909 // be removed) code path for enums. 1910 if (Kind != TagDecl::TK_enum) 1911 return ActOnTagStruct(S, Kind, TK, KWLoc, Name, NameLoc, Attr); 1912 1913 // If this is a named struct, check to see if there was a previous forward 1914 // declaration or definition. 1915 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up. 1916 ScopedDecl *PrevDecl = 1917 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S)); 1918 1919 if (PrevDecl) { 1920 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) && 1921 "unexpected Decl type"); 1922 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 1923 // If this is a use of a previous tag, or if the tag is already declared 1924 // in the same scope (so that the definition/declaration completes or 1925 // rementions the tag), reuse the decl. 1926 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) { 1927 // Make sure that this wasn't declared as an enum and now used as a 1928 // struct or something similar. 1929 if (PrevTagDecl->getTagKind() != Kind) { 1930 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName()); 1931 Diag(PrevDecl->getLocation(), diag::err_previous_use); 1932 // Recover by making this an anonymous redefinition. 1933 Name = 0; 1934 PrevDecl = 0; 1935 } else { 1936 // If this is a use or a forward declaration, we're good. 1937 if (TK != TK_Definition) 1938 return PrevDecl; 1939 1940 // Diagnose attempts to redefine a tag. 1941 if (PrevTagDecl->isDefinition()) { 1942 Diag(NameLoc, diag::err_redefinition, Name->getName()); 1943 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 1944 // If this is a redefinition, recover by making this struct be 1945 // anonymous, which will make any later references get the previous 1946 // definition. 1947 Name = 0; 1948 } else { 1949 // Okay, this is definition of a previously declared or referenced 1950 // tag. Move the location of the decl to be the definition site. 1951 PrevDecl->setLocation(NameLoc); 1952 return PrevDecl; 1953 } 1954 } 1955 } 1956 // If we get here, this is a definition of a new struct type in a nested 1957 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new 1958 // type. 1959 } else { 1960 // PrevDecl is a namespace. 1961 if (isDeclInScope(PrevDecl, CurContext, S)) { 1962 // The tag name clashes with a namespace name, issue an error and 1963 // recover by making this tag be anonymous. 1964 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName()); 1965 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 1966 Name = 0; 1967 } 1968 } 1969 } 1970 1971 // If there is an identifier, use the location of the identifier as the 1972 // location of the decl, otherwise use the location of the struct/union 1973 // keyword. 1974 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 1975 1976 // Otherwise, if this is the first time we've seen this tag, create the decl. 1977 TagDecl *New; 1978 if (Kind == TagDecl::TK_enum) { 1979 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 1980 // enum X { A, B, C } D; D should chain to X. 1981 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0); 1982 // If this is an undefined enum, warn. 1983 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum); 1984 } else { 1985 // struct/union/class 1986 1987 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 1988 // struct X { int A; } D; D should chain to X. 1989 if (getLangOptions().CPlusPlus) 1990 // FIXME: Look for a way to use RecordDecl for simple structs. 1991 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name); 1992 else 1993 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name); 1994 } 1995 1996 // If this has an identifier, add it to the scope stack. 1997 if (Name) { 1998 // The scope passed in may not be a decl scope. Zip up the scope tree until 1999 // we find one that is. 2000 while ((S->getFlags() & Scope::DeclScope) == 0) 2001 S = S->getParent(); 2002 2003 // Add it to the decl chain. 2004 PushOnScopeChains(New, S); 2005 } 2006 2007 if (Attr) 2008 ProcessDeclAttributeList(New, Attr); 2009 return New; 2010} 2011 2012/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike 2013/// the logic for enums, we create separate decls for forward declarations. 2014/// This is called by ActOnTag, but eventually will replace its logic. 2015Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK, 2016 SourceLocation KWLoc, IdentifierInfo *Name, 2017 SourceLocation NameLoc, AttributeList *Attr) { 2018 2019 // If this is a named struct, check to see if there was a previous forward 2020 // declaration or definition. 2021 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up. 2022 ScopedDecl *PrevDecl = 2023 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S)); 2024 2025 if (PrevDecl) { 2026 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) && 2027 "unexpected Decl type"); 2028 2029 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 2030 // If this is a use of a previous tag, or if the tag is already declared 2031 // in the same scope (so that the definition/declaration completes or 2032 // rementions the tag), reuse the decl. 2033 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) { 2034 // Make sure that this wasn't declared as an enum and now used as a 2035 // struct or something similar. 2036 if (PrevTagDecl->getTagKind() != Kind) { 2037 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName()); 2038 Diag(PrevDecl->getLocation(), diag::err_previous_use); 2039 // Recover by making this an anonymous redefinition. 2040 Name = 0; 2041 PrevDecl = 0; 2042 } else { 2043 // If this is a use, return the original decl. 2044 2045 // FIXME: In the future, return a variant or some other clue 2046 // for the consumer of this Decl to know it doesn't own it. 2047 // For our current ASTs this shouldn't be a problem, but will 2048 // need to be changed with DeclGroups. 2049 if (TK == TK_Reference) 2050 return PrevDecl; 2051 2052 // The new decl is a definition? 2053 if (TK == TK_Definition) { 2054 // Diagnose attempts to redefine a tag. 2055 if (RecordDecl* DefRecord = 2056 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) { 2057 Diag(NameLoc, diag::err_redefinition, Name->getName()); 2058 Diag(DefRecord->getLocation(), diag::err_previous_definition); 2059 // If this is a redefinition, recover by making this struct be 2060 // anonymous, which will make any later references get the previous 2061 // definition. 2062 Name = 0; 2063 PrevDecl = 0; 2064 } 2065 // Okay, this is definition of a previously declared or referenced 2066 // tag. We're going to create a new Decl. 2067 } 2068 } 2069 // If we get here we have (another) forward declaration. Just create 2070 // a new decl. 2071 } 2072 else { 2073 // If we get here, this is a definition of a new struct type in a nested 2074 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 2075 // new decl/type. We set PrevDecl to NULL so that the Records 2076 // have distinct types. 2077 PrevDecl = 0; 2078 } 2079 } else { 2080 // PrevDecl is a namespace. 2081 if (isDeclInScope(PrevDecl, CurContext, S)) { 2082 // The tag name clashes with a namespace name, issue an error and 2083 // recover by making this tag be anonymous. 2084 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName()); 2085 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 2086 Name = 0; 2087 } 2088 } 2089 } 2090 2091 // If there is an identifier, use the location of the identifier as the 2092 // location of the decl, otherwise use the location of the struct/union 2093 // keyword. 2094 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 2095 2096 // Otherwise, if this is the first time we've seen this tag, create the decl. 2097 TagDecl *New; 2098 2099 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 2100 // struct X { int A; } D; D should chain to X. 2101 if (getLangOptions().CPlusPlus) 2102 // FIXME: Look for a way to use RecordDecl for simple structs. 2103 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name, 2104 dyn_cast_or_null<CXXRecordDecl>(PrevDecl)); 2105 else 2106 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name, 2107 dyn_cast_or_null<RecordDecl>(PrevDecl)); 2108 2109 // If this has an identifier, add it to the scope stack. 2110 if ((TK == TK_Definition || !PrevDecl) && Name) { 2111 // The scope passed in may not be a decl scope. Zip up the scope tree until 2112 // we find one that is. 2113 while ((S->getFlags() & Scope::DeclScope) == 0) 2114 S = S->getParent(); 2115 2116 // Add it to the decl chain. 2117 PushOnScopeChains(New, S); 2118 } 2119 2120 // Handle #pragma pack: if the #pragma pack stack has non-default 2121 // alignment, make up a packed attribute for this decl. These 2122 // attributes are checked when the ASTContext lays out the 2123 // structure. 2124 // 2125 // It is important for implementing the correct semantics that this 2126 // happen here (in act on tag decl). The #pragma pack stack is 2127 // maintained as a result of parser callbacks which can occur at 2128 // many points during the parsing of a struct declaration (because 2129 // the #pragma tokens are effectively skipped over during the 2130 // parsing of the struct). 2131 if (unsigned Alignment = PackContext.getAlignment()) 2132 New->addAttr(new PackedAttr(Alignment * 8)); 2133 2134 if (Attr) 2135 ProcessDeclAttributeList(New, Attr); 2136 2137 return New; 2138} 2139 2140 2141/// Collect the instance variables declared in an Objective-C object. Used in 2142/// the creation of structures from objects using the @defs directive. 2143static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx, 2144 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) { 2145 if (Class->getSuperClass()) 2146 CollectIvars(Class->getSuperClass(), Ctx, ivars); 2147 2148 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 2149 for (ObjCInterfaceDecl::ivar_iterator 2150 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) { 2151 2152 ObjCIvarDecl* ID = *I; 2153 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(), 2154 ID->getIdentifier(), 2155 ID->getType(), 2156 ID->getBitWidth())); 2157 } 2158} 2159 2160/// Called whenever @defs(ClassName) is encountered in the source. Inserts the 2161/// instance variables of ClassName into Decls. 2162void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart, 2163 IdentifierInfo *ClassName, 2164 llvm::SmallVectorImpl<DeclTy*> &Decls) { 2165 // Check that ClassName is a valid class 2166 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName); 2167 if (!Class) { 2168 Diag(DeclStart, diag::err_undef_interface, ClassName->getName()); 2169 return; 2170 } 2171 // Collect the instance variables 2172 CollectIvars(Class, Context, Decls); 2173} 2174 2175QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) { 2176 // This method tries to turn a variable array into a constant 2177 // array even when the size isn't an ICE. This is necessary 2178 // for compatibility with code that depends on gcc's buggy 2179 // constant expression folding, like struct {char x[(int)(char*)2];} 2180 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) { 2181 APValue Result; 2182 if (VLATy->getSizeExpr() && 2183 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) { 2184 llvm::APSInt &Res = Result.getInt(); 2185 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned())) 2186 return Context.getConstantArrayType(VLATy->getElementType(), 2187 Res, ArrayType::Normal, 0); 2188 } 2189 } 2190 return QualType(); 2191} 2192 2193/// ActOnField - Each field of a struct/union/class is passed into this in order 2194/// to create a FieldDecl object for it. 2195Sema::DeclTy *Sema::ActOnField(Scope *S, 2196 SourceLocation DeclStart, 2197 Declarator &D, ExprTy *BitfieldWidth) { 2198 IdentifierInfo *II = D.getIdentifier(); 2199 Expr *BitWidth = (Expr*)BitfieldWidth; 2200 SourceLocation Loc = DeclStart; 2201 if (II) Loc = D.getIdentifierLoc(); 2202 2203 // FIXME: Unnamed fields can be handled in various different ways, for 2204 // example, unnamed unions inject all members into the struct namespace! 2205 2206 if (BitWidth) { 2207 // TODO: Validate. 2208 //printf("WARNING: BITFIELDS IGNORED!\n"); 2209 2210 // 6.7.2.1p3 2211 // 6.7.2.1p4 2212 2213 } else { 2214 // Not a bitfield. 2215 2216 // validate II. 2217 2218 } 2219 2220 QualType T = GetTypeForDeclarator(D, S); 2221 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 2222 bool InvalidDecl = false; 2223 2224 // C99 6.7.2.1p8: A member of a structure or union may have any type other 2225 // than a variably modified type. 2226 if (T->isVariablyModifiedType()) { 2227 QualType FixedTy = TryFixInvalidVariablyModifiedType(T); 2228 if (!FixedTy.isNull()) { 2229 Diag(Loc, diag::warn_illegal_constant_array_size, Loc); 2230 T = FixedTy; 2231 } else { 2232 // FIXME: This diagnostic needs work 2233 Diag(Loc, diag::err_typecheck_illegal_vla, Loc); 2234 InvalidDecl = true; 2235 } 2236 } 2237 // FIXME: Chain fielddecls together. 2238 FieldDecl *NewFD; 2239 2240 if (getLangOptions().CPlusPlus) { 2241 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs. 2242 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext), 2243 Loc, II, T, BitWidth); 2244 if (II) 2245 PushOnScopeChains(NewFD, S); 2246 } 2247 else 2248 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth); 2249 2250 ProcessDeclAttributes(NewFD, D); 2251 2252 if (D.getInvalidType() || InvalidDecl) 2253 NewFD->setInvalidDecl(); 2254 return NewFD; 2255} 2256 2257/// TranslateIvarVisibility - Translate visibility from a token ID to an 2258/// AST enum value. 2259static ObjCIvarDecl::AccessControl 2260TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 2261 switch (ivarVisibility) { 2262 default: assert(0 && "Unknown visitibility kind"); 2263 case tok::objc_private: return ObjCIvarDecl::Private; 2264 case tok::objc_public: return ObjCIvarDecl::Public; 2265 case tok::objc_protected: return ObjCIvarDecl::Protected; 2266 case tok::objc_package: return ObjCIvarDecl::Package; 2267 } 2268} 2269 2270/// ActOnIvar - Each ivar field of an objective-c class is passed into this 2271/// in order to create an IvarDecl object for it. 2272Sema::DeclTy *Sema::ActOnIvar(Scope *S, 2273 SourceLocation DeclStart, 2274 Declarator &D, ExprTy *BitfieldWidth, 2275 tok::ObjCKeywordKind Visibility) { 2276 IdentifierInfo *II = D.getIdentifier(); 2277 Expr *BitWidth = (Expr*)BitfieldWidth; 2278 SourceLocation Loc = DeclStart; 2279 if (II) Loc = D.getIdentifierLoc(); 2280 2281 // FIXME: Unnamed fields can be handled in various different ways, for 2282 // example, unnamed unions inject all members into the struct namespace! 2283 2284 2285 if (BitWidth) { 2286 // TODO: Validate. 2287 //printf("WARNING: BITFIELDS IGNORED!\n"); 2288 2289 // 6.7.2.1p3 2290 // 6.7.2.1p4 2291 2292 } else { 2293 // Not a bitfield. 2294 2295 // validate II. 2296 2297 } 2298 2299 QualType T = GetTypeForDeclarator(D, S); 2300 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 2301 bool InvalidDecl = false; 2302 2303 // C99 6.7.2.1p8: A member of a structure or union may have any type other 2304 // than a variably modified type. 2305 if (T->isVariablyModifiedType()) { 2306 // FIXME: This diagnostic needs work 2307 Diag(Loc, diag::err_typecheck_illegal_vla, Loc); 2308 InvalidDecl = true; 2309 } 2310 2311 // Get the visibility (access control) for this ivar. 2312 ObjCIvarDecl::AccessControl ac = 2313 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 2314 : ObjCIvarDecl::None; 2315 2316 // Construct the decl. 2317 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac, 2318 (Expr *)BitfieldWidth); 2319 2320 // Process attributes attached to the ivar. 2321 ProcessDeclAttributes(NewID, D); 2322 2323 if (D.getInvalidType() || InvalidDecl) 2324 NewID->setInvalidDecl(); 2325 2326 return NewID; 2327} 2328 2329void Sema::ActOnFields(Scope* S, 2330 SourceLocation RecLoc, DeclTy *RecDecl, 2331 DeclTy **Fields, unsigned NumFields, 2332 SourceLocation LBrac, SourceLocation RBrac, 2333 AttributeList *Attr) { 2334 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl); 2335 assert(EnclosingDecl && "missing record or interface decl"); 2336 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 2337 2338 if (Record) 2339 if (RecordDecl* DefRecord = Record->getDefinition(Context)) { 2340 // Diagnose code like: 2341 // struct S { struct S {} X; }; 2342 // We discover this when we complete the outer S. Reject and ignore the 2343 // outer S. 2344 Diag(DefRecord->getLocation(), diag::err_nested_redefinition, 2345 DefRecord->getKindName()); 2346 Diag(RecLoc, diag::err_previous_definition); 2347 Record->setInvalidDecl(); 2348 return; 2349 } 2350 2351 // Verify that all the fields are okay. 2352 unsigned NumNamedMembers = 0; 2353 llvm::SmallVector<FieldDecl*, 32> RecFields; 2354 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs; 2355 2356 for (unsigned i = 0; i != NumFields; ++i) { 2357 2358 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i])); 2359 assert(FD && "missing field decl"); 2360 2361 // Remember all fields. 2362 RecFields.push_back(FD); 2363 2364 // Get the type for the field. 2365 Type *FDTy = FD->getType().getTypePtr(); 2366 2367 // C99 6.7.2.1p2 - A field may not be a function type. 2368 if (FDTy->isFunctionType()) { 2369 Diag(FD->getLocation(), diag::err_field_declared_as_function, 2370 FD->getName()); 2371 FD->setInvalidDecl(); 2372 EnclosingDecl->setInvalidDecl(); 2373 continue; 2374 } 2375 // C99 6.7.2.1p2 - A field may not be an incomplete type except... 2376 if (FDTy->isIncompleteType()) { 2377 if (!Record) { // Incomplete ivar type is always an error. 2378 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName()); 2379 FD->setInvalidDecl(); 2380 EnclosingDecl->setInvalidDecl(); 2381 continue; 2382 } 2383 if (i != NumFields-1 || // ... that the last member ... 2384 !Record->isStruct() || // ... of a structure ... 2385 !FDTy->isArrayType()) { //... may have incomplete array type. 2386 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName()); 2387 FD->setInvalidDecl(); 2388 EnclosingDecl->setInvalidDecl(); 2389 continue; 2390 } 2391 if (NumNamedMembers < 1) { //... must have more than named member ... 2392 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct, 2393 FD->getName()); 2394 FD->setInvalidDecl(); 2395 EnclosingDecl->setInvalidDecl(); 2396 continue; 2397 } 2398 // Okay, we have a legal flexible array member at the end of the struct. 2399 if (Record) 2400 Record->setHasFlexibleArrayMember(true); 2401 } 2402 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the 2403 /// field of another structure or the element of an array. 2404 if (const RecordType *FDTTy = FDTy->getAsRecordType()) { 2405 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 2406 // If this is a member of a union, then entire union becomes "flexible". 2407 if (Record && Record->isUnion()) { 2408 Record->setHasFlexibleArrayMember(true); 2409 } else { 2410 // If this is a struct/class and this is not the last element, reject 2411 // it. Note that GCC supports variable sized arrays in the middle of 2412 // structures. 2413 if (i != NumFields-1) { 2414 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct, 2415 FD->getName()); 2416 FD->setInvalidDecl(); 2417 EnclosingDecl->setInvalidDecl(); 2418 continue; 2419 } 2420 // We support flexible arrays at the end of structs in other structs 2421 // as an extension. 2422 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct, 2423 FD->getName()); 2424 if (Record) 2425 Record->setHasFlexibleArrayMember(true); 2426 } 2427 } 2428 } 2429 /// A field cannot be an Objective-c object 2430 if (FDTy->isObjCInterfaceType()) { 2431 Diag(FD->getLocation(), diag::err_statically_allocated_object, 2432 FD->getName()); 2433 FD->setInvalidDecl(); 2434 EnclosingDecl->setInvalidDecl(); 2435 continue; 2436 } 2437 // Keep track of the number of named members. 2438 if (IdentifierInfo *II = FD->getIdentifier()) { 2439 // Detect duplicate member names. 2440 if (!FieldIDs.insert(II)) { 2441 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName()); 2442 // Find the previous decl. 2443 SourceLocation PrevLoc; 2444 for (unsigned i = 0; ; ++i) { 2445 assert(i != RecFields.size() && "Didn't find previous def!"); 2446 if (RecFields[i]->getIdentifier() == II) { 2447 PrevLoc = RecFields[i]->getLocation(); 2448 break; 2449 } 2450 } 2451 Diag(PrevLoc, diag::err_previous_definition); 2452 FD->setInvalidDecl(); 2453 EnclosingDecl->setInvalidDecl(); 2454 continue; 2455 } 2456 ++NumNamedMembers; 2457 } 2458 } 2459 2460 // Okay, we successfully defined 'Record'. 2461 if (Record) { 2462 Record->defineBody(Context, &RecFields[0], RecFields.size()); 2463 // If this is a C++ record, HandleTagDeclDefinition will be invoked in 2464 // Sema::ActOnFinishCXXClassDef. 2465 if (!isa<CXXRecordDecl>(Record)) 2466 Consumer.HandleTagDeclDefinition(Record); 2467 } else { 2468 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]); 2469 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) 2470 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac); 2471 else if (ObjCImplementationDecl *IMPDecl = 2472 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 2473 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 2474 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size()); 2475 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 2476 } 2477 } 2478 2479 if (Attr) 2480 ProcessDeclAttributeList(Record, Attr); 2481} 2482 2483Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl, 2484 DeclTy *lastEnumConst, 2485 SourceLocation IdLoc, IdentifierInfo *Id, 2486 SourceLocation EqualLoc, ExprTy *val) { 2487 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl)); 2488 EnumConstantDecl *LastEnumConst = 2489 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst)); 2490 Expr *Val = static_cast<Expr*>(val); 2491 2492 // The scope passed in may not be a decl scope. Zip up the scope tree until 2493 // we find one that is. 2494 while ((S->getFlags() & Scope::DeclScope) == 0) 2495 S = S->getParent(); 2496 2497 // Verify that there isn't already something declared with this name in this 2498 // scope. 2499 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) { 2500 // When in C++, we may get a TagDecl with the same name; in this case the 2501 // enum constant will 'hide' the tag. 2502 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 2503 "Received TagDecl when not in C++!"); 2504 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 2505 if (isa<EnumConstantDecl>(PrevDecl)) 2506 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName()); 2507 else 2508 Diag(IdLoc, diag::err_redefinition, Id->getName()); 2509 Diag(PrevDecl->getLocation(), diag::err_previous_definition); 2510 delete Val; 2511 return 0; 2512 } 2513 } 2514 2515 llvm::APSInt EnumVal(32); 2516 QualType EltTy; 2517 if (Val) { 2518 // Make sure to promote the operand type to int. 2519 UsualUnaryConversions(Val); 2520 2521 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 2522 SourceLocation ExpLoc; 2523 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) { 2524 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr, 2525 Id->getName()); 2526 delete Val; 2527 Val = 0; // Just forget about it. 2528 } else { 2529 EltTy = Val->getType(); 2530 } 2531 } 2532 2533 if (!Val) { 2534 if (LastEnumConst) { 2535 // Assign the last value + 1. 2536 EnumVal = LastEnumConst->getInitVal(); 2537 ++EnumVal; 2538 2539 // Check for overflow on increment. 2540 if (EnumVal < LastEnumConst->getInitVal()) 2541 Diag(IdLoc, diag::warn_enum_value_overflow); 2542 2543 EltTy = LastEnumConst->getType(); 2544 } else { 2545 // First value, set to zero. 2546 EltTy = Context.IntTy; 2547 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy))); 2548 } 2549 } 2550 2551 EnumConstantDecl *New = 2552 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy, 2553 Val, EnumVal, 2554 LastEnumConst); 2555 2556 // Register this decl in the current scope stack. 2557 PushOnScopeChains(New, S); 2558 return New; 2559} 2560 2561// FIXME: For consistency with ActOnFields(), we should have the parser 2562// pass in the source location for the left/right braces. 2563void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX, 2564 DeclTy **Elements, unsigned NumElements) { 2565 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX)); 2566 2567 if (Enum && Enum->isDefinition()) { 2568 // Diagnose code like: 2569 // enum e0 { 2570 // E0 = sizeof(enum e0 { E1 }) 2571 // }; 2572 Diag(Enum->getLocation(), diag::err_nested_redefinition, 2573 Enum->getName()); 2574 Diag(EnumLoc, diag::err_previous_definition); 2575 Enum->setInvalidDecl(); 2576 return; 2577 } 2578 // TODO: If the result value doesn't fit in an int, it must be a long or long 2579 // long value. ISO C does not support this, but GCC does as an extension, 2580 // emit a warning. 2581 unsigned IntWidth = Context.Target.getIntWidth(); 2582 2583 // Verify that all the values are okay, compute the size of the values, and 2584 // reverse the list. 2585 unsigned NumNegativeBits = 0; 2586 unsigned NumPositiveBits = 0; 2587 2588 // Keep track of whether all elements have type int. 2589 bool AllElementsInt = true; 2590 2591 EnumConstantDecl *EltList = 0; 2592 for (unsigned i = 0; i != NumElements; ++i) { 2593 EnumConstantDecl *ECD = 2594 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 2595 if (!ECD) continue; // Already issued a diagnostic. 2596 2597 // If the enum value doesn't fit in an int, emit an extension warning. 2598 const llvm::APSInt &InitVal = ECD->getInitVal(); 2599 assert(InitVal.getBitWidth() >= IntWidth && 2600 "Should have promoted value to int"); 2601 if (InitVal.getBitWidth() > IntWidth) { 2602 llvm::APSInt V(InitVal); 2603 V.trunc(IntWidth); 2604 V.extend(InitVal.getBitWidth()); 2605 if (V != InitVal) 2606 Diag(ECD->getLocation(), diag::ext_enum_value_not_int, 2607 InitVal.toString(10)); 2608 } 2609 2610 // Keep track of the size of positive and negative values. 2611 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 2612 NumPositiveBits = std::max(NumPositiveBits, 2613 (unsigned)InitVal.getActiveBits()); 2614 else 2615 NumNegativeBits = std::max(NumNegativeBits, 2616 (unsigned)InitVal.getMinSignedBits()); 2617 2618 // Keep track of whether every enum element has type int (very commmon). 2619 if (AllElementsInt) 2620 AllElementsInt = ECD->getType() == Context.IntTy; 2621 2622 ECD->setNextDeclarator(EltList); 2623 EltList = ECD; 2624 } 2625 2626 // Figure out the type that should be used for this enum. 2627 // FIXME: Support attribute(packed) on enums and -fshort-enums. 2628 QualType BestType; 2629 unsigned BestWidth; 2630 2631 if (NumNegativeBits) { 2632 // If there is a negative value, figure out the smallest integer type (of 2633 // int/long/longlong) that fits. 2634 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 2635 BestType = Context.IntTy; 2636 BestWidth = IntWidth; 2637 } else { 2638 BestWidth = Context.Target.getLongWidth(); 2639 2640 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) 2641 BestType = Context.LongTy; 2642 else { 2643 BestWidth = Context.Target.getLongLongWidth(); 2644 2645 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 2646 Diag(Enum->getLocation(), diag::warn_enum_too_large); 2647 BestType = Context.LongLongTy; 2648 } 2649 } 2650 } else { 2651 // If there is no negative value, figure out which of uint, ulong, ulonglong 2652 // fits. 2653 if (NumPositiveBits <= IntWidth) { 2654 BestType = Context.UnsignedIntTy; 2655 BestWidth = IntWidth; 2656 } else if (NumPositiveBits <= 2657 (BestWidth = Context.Target.getLongWidth())) { 2658 BestType = Context.UnsignedLongTy; 2659 } else { 2660 BestWidth = Context.Target.getLongLongWidth(); 2661 assert(NumPositiveBits <= BestWidth && 2662 "How could an initializer get larger than ULL?"); 2663 BestType = Context.UnsignedLongLongTy; 2664 } 2665 } 2666 2667 // Loop over all of the enumerator constants, changing their types to match 2668 // the type of the enum if needed. 2669 for (unsigned i = 0; i != NumElements; ++i) { 2670 EnumConstantDecl *ECD = 2671 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i])); 2672 if (!ECD) continue; // Already issued a diagnostic. 2673 2674 // Standard C says the enumerators have int type, but we allow, as an 2675 // extension, the enumerators to be larger than int size. If each 2676 // enumerator value fits in an int, type it as an int, otherwise type it the 2677 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 2678 // that X has type 'int', not 'unsigned'. 2679 if (ECD->getType() == Context.IntTy) { 2680 // Make sure the init value is signed. 2681 llvm::APSInt IV = ECD->getInitVal(); 2682 IV.setIsSigned(true); 2683 ECD->setInitVal(IV); 2684 continue; // Already int type. 2685 } 2686 2687 // Determine whether the value fits into an int. 2688 llvm::APSInt InitVal = ECD->getInitVal(); 2689 bool FitsInInt; 2690 if (InitVal.isUnsigned() || !InitVal.isNegative()) 2691 FitsInInt = InitVal.getActiveBits() < IntWidth; 2692 else 2693 FitsInInt = InitVal.getMinSignedBits() <= IntWidth; 2694 2695 // If it fits into an integer type, force it. Otherwise force it to match 2696 // the enum decl type. 2697 QualType NewTy; 2698 unsigned NewWidth; 2699 bool NewSign; 2700 if (FitsInInt) { 2701 NewTy = Context.IntTy; 2702 NewWidth = IntWidth; 2703 NewSign = true; 2704 } else if (ECD->getType() == BestType) { 2705 // Already the right type! 2706 continue; 2707 } else { 2708 NewTy = BestType; 2709 NewWidth = BestWidth; 2710 NewSign = BestType->isSignedIntegerType(); 2711 } 2712 2713 // Adjust the APSInt value. 2714 InitVal.extOrTrunc(NewWidth); 2715 InitVal.setIsSigned(NewSign); 2716 ECD->setInitVal(InitVal); 2717 2718 // Adjust the Expr initializer and type. 2719 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr())); 2720 ECD->setType(NewTy); 2721 } 2722 2723 Enum->defineElements(EltList, BestType); 2724 Consumer.HandleTagDeclDefinition(Enum); 2725} 2726 2727Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc, 2728 ExprTy *expr) { 2729 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr); 2730 2731 return FileScopeAsmDecl::Create(Context, Loc, AsmString); 2732} 2733 2734Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc, 2735 SourceLocation LBrace, 2736 SourceLocation RBrace, 2737 const char *Lang, 2738 unsigned StrSize, 2739 DeclTy *D) { 2740 LinkageSpecDecl::LanguageIDs Language; 2741 Decl *dcl = static_cast<Decl *>(D); 2742 if (strncmp(Lang, "\"C\"", StrSize) == 0) 2743 Language = LinkageSpecDecl::lang_c; 2744 else if (strncmp(Lang, "\"C++\"", StrSize) == 0) 2745 Language = LinkageSpecDecl::lang_cxx; 2746 else { 2747 Diag(Loc, diag::err_bad_language); 2748 return 0; 2749 } 2750 2751 // FIXME: Add all the various semantics of linkage specifications 2752 return LinkageSpecDecl::Create(Context, Loc, Language, dcl); 2753} 2754 2755void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name, 2756 ExprTy *alignment, SourceLocation PragmaLoc, 2757 SourceLocation LParenLoc, SourceLocation RParenLoc) { 2758 Expr *Alignment = static_cast<Expr *>(alignment); 2759 2760 // If specified then alignment must be a "small" power of two. 2761 unsigned AlignmentVal = 0; 2762 if (Alignment) { 2763 llvm::APSInt Val; 2764 if (!Alignment->isIntegerConstantExpr(Val, Context) || 2765 !Val.isPowerOf2() || 2766 Val.getZExtValue() > 16) { 2767 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment); 2768 delete Alignment; 2769 return; // Ignore 2770 } 2771 2772 AlignmentVal = (unsigned) Val.getZExtValue(); 2773 } 2774 2775 switch (Kind) { 2776 case Action::PPK_Default: // pack([n]) 2777 PackContext.setAlignment(AlignmentVal); 2778 break; 2779 2780 case Action::PPK_Show: // pack(show) 2781 // Show the current alignment, making sure to show the right value 2782 // for the default. 2783 AlignmentVal = PackContext.getAlignment(); 2784 // FIXME: This should come from the target. 2785 if (AlignmentVal == 0) 2786 AlignmentVal = 8; 2787 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal)); 2788 break; 2789 2790 case Action::PPK_Push: // pack(push [, id] [, [n]) 2791 PackContext.push(Name); 2792 // Set the new alignment if specified. 2793 if (Alignment) 2794 PackContext.setAlignment(AlignmentVal); 2795 break; 2796 2797 case Action::PPK_Pop: // pack(pop [, id] [, n]) 2798 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack: 2799 // "#pragma pack(pop, identifier, n) is undefined" 2800 if (Alignment && Name) 2801 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment); 2802 2803 // Do the pop. 2804 if (!PackContext.pop(Name)) { 2805 // If a name was specified then failure indicates the name 2806 // wasn't found. Otherwise failure indicates the stack was 2807 // empty. 2808 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed, 2809 Name ? "no record matching name" : "stack empty"); 2810 2811 // FIXME: Warn about popping named records as MSVC does. 2812 } else { 2813 // Pop succeeded, set the new alignment if specified. 2814 if (Alignment) 2815 PackContext.setAlignment(AlignmentVal); 2816 } 2817 break; 2818 2819 default: 2820 assert(0 && "Invalid #pragma pack kind."); 2821 } 2822} 2823 2824bool PragmaPackStack::pop(IdentifierInfo *Name) { 2825 if (Stack.empty()) 2826 return false; 2827 2828 // If name is empty just pop top. 2829 if (!Name) { 2830 Alignment = Stack.back().first; 2831 Stack.pop_back(); 2832 return true; 2833 } 2834 2835 // Otherwise, find the named record. 2836 for (unsigned i = Stack.size(); i != 0; ) { 2837 --i; 2838 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) { 2839 // Found it, pop up to and including this record. 2840 Alignment = Stack[i].first; 2841 Stack.erase(Stack.begin() + i, Stack.end()); 2842 return true; 2843 } 2844 } 2845 2846 return false; 2847} 2848