clang API Documentation
00001 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements semantic analysis for declarations. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/Sema/SemaInternal.h" 00015 #include "clang/Sema/Initialization.h" 00016 #include "clang/Sema/Lookup.h" 00017 #include "clang/Sema/CXXFieldCollector.h" 00018 #include "clang/Sema/Scope.h" 00019 #include "clang/Sema/ScopeInfo.h" 00020 #include "TypeLocBuilder.h" 00021 #include "clang/AST/ASTConsumer.h" 00022 #include "clang/AST/ASTContext.h" 00023 #include "clang/AST/CXXInheritance.h" 00024 #include "clang/AST/DeclCXX.h" 00025 #include "clang/AST/DeclObjC.h" 00026 #include "clang/AST/DeclTemplate.h" 00027 #include "clang/AST/EvaluatedExprVisitor.h" 00028 #include "clang/AST/ExprCXX.h" 00029 #include "clang/AST/StmtCXX.h" 00030 #include "clang/AST/CharUnits.h" 00031 #include "clang/Sema/DeclSpec.h" 00032 #include "clang/Sema/ParsedTemplate.h" 00033 #include "clang/Parse/ParseDiagnostic.h" 00034 #include "clang/Basic/PartialDiagnostic.h" 00035 #include "clang/Sema/DelayedDiagnostic.h" 00036 #include "clang/Basic/SourceManager.h" 00037 #include "clang/Basic/TargetInfo.h" 00038 // FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's) 00039 #include "clang/Lex/Preprocessor.h" 00040 #include "clang/Lex/HeaderSearch.h" 00041 #include "clang/Lex/ModuleLoader.h" 00042 #include "llvm/ADT/SmallString.h" 00043 #include "llvm/ADT/Triple.h" 00044 #include <algorithm> 00045 #include <cstring> 00046 #include <functional> 00047 using namespace clang; 00048 using namespace sema; 00049 00050 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 00051 if (OwnedType) { 00052 Decl *Group[2] = { OwnedType, Ptr }; 00053 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 00054 } 00055 00056 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 00057 } 00058 00059 namespace { 00060 00061 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 00062 public: 00063 TypeNameValidatorCCC(bool AllowInvalid) : AllowInvalidDecl(AllowInvalid) { 00064 WantExpressionKeywords = false; 00065 WantCXXNamedCasts = false; 00066 WantRemainingKeywords = false; 00067 } 00068 00069 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 00070 if (NamedDecl *ND = candidate.getCorrectionDecl()) 00071 return (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) && 00072 (AllowInvalidDecl || !ND->isInvalidDecl()); 00073 else 00074 return candidate.isKeyword(); 00075 } 00076 00077 private: 00078 bool AllowInvalidDecl; 00079 }; 00080 00081 } 00082 00083 /// \brief If the identifier refers to a type name within this scope, 00084 /// return the declaration of that type. 00085 /// 00086 /// This routine performs ordinary name lookup of the identifier II 00087 /// within the given scope, with optional C++ scope specifier SS, to 00088 /// determine whether the name refers to a type. If so, returns an 00089 /// opaque pointer (actually a QualType) corresponding to that 00090 /// type. Otherwise, returns NULL. 00091 /// 00092 /// If name lookup results in an ambiguity, this routine will complain 00093 /// and then return NULL. 00094 ParsedType Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 00095 Scope *S, CXXScopeSpec *SS, 00096 bool isClassName, bool HasTrailingDot, 00097 ParsedType ObjectTypePtr, 00098 bool IsCtorOrDtorName, 00099 bool WantNontrivialTypeSourceInfo, 00100 IdentifierInfo **CorrectedII) { 00101 // Determine where we will perform name lookup. 00102 DeclContext *LookupCtx = 0; 00103 if (ObjectTypePtr) { 00104 QualType ObjectType = ObjectTypePtr.get(); 00105 if (ObjectType->isRecordType()) 00106 LookupCtx = computeDeclContext(ObjectType); 00107 } else if (SS && SS->isNotEmpty()) { 00108 LookupCtx = computeDeclContext(*SS, false); 00109 00110 if (!LookupCtx) { 00111 if (isDependentScopeSpecifier(*SS)) { 00112 // C++ [temp.res]p3: 00113 // A qualified-id that refers to a type and in which the 00114 // nested-name-specifier depends on a template-parameter (14.6.2) 00115 // shall be prefixed by the keyword typename to indicate that the 00116 // qualified-id denotes a type, forming an 00117 // elaborated-type-specifier (7.1.5.3). 00118 // 00119 // We therefore do not perform any name lookup if the result would 00120 // refer to a member of an unknown specialization. 00121 if (!isClassName && !IsCtorOrDtorName) 00122 return ParsedType(); 00123 00124 // We know from the grammar that this name refers to a type, 00125 // so build a dependent node to describe the type. 00126 if (WantNontrivialTypeSourceInfo) 00127 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 00128 00129 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 00130 QualType T = 00131 CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 00132 II, NameLoc); 00133 00134 return ParsedType::make(T); 00135 } 00136 00137 return ParsedType(); 00138 } 00139 00140 if (!LookupCtx->isDependentContext() && 00141 RequireCompleteDeclContext(*SS, LookupCtx)) 00142 return ParsedType(); 00143 } 00144 00145 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 00146 // lookup for class-names. 00147 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 00148 LookupOrdinaryName; 00149 LookupResult Result(*this, &II, NameLoc, Kind); 00150 if (LookupCtx) { 00151 // Perform "qualified" name lookup into the declaration context we 00152 // computed, which is either the type of the base of a member access 00153 // expression or the declaration context associated with a prior 00154 // nested-name-specifier. 00155 LookupQualifiedName(Result, LookupCtx); 00156 00157 if (ObjectTypePtr && Result.empty()) { 00158 // C++ [basic.lookup.classref]p3: 00159 // If the unqualified-id is ~type-name, the type-name is looked up 00160 // in the context of the entire postfix-expression. If the type T of 00161 // the object expression is of a class type C, the type-name is also 00162 // looked up in the scope of class C. At least one of the lookups shall 00163 // find a name that refers to (possibly cv-qualified) T. 00164 LookupName(Result, S); 00165 } 00166 } else { 00167 // Perform unqualified name lookup. 00168 LookupName(Result, S); 00169 } 00170 00171 NamedDecl *IIDecl = 0; 00172 switch (Result.getResultKind()) { 00173 case LookupResult::NotFound: 00174 case LookupResult::NotFoundInCurrentInstantiation: 00175 if (CorrectedII) { 00176 TypeNameValidatorCCC Validator(true); 00177 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), 00178 Kind, S, SS, Validator); 00179 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 00180 TemplateTy Template; 00181 bool MemberOfUnknownSpecialization; 00182 UnqualifiedId TemplateName; 00183 TemplateName.setIdentifier(NewII, NameLoc); 00184 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 00185 CXXScopeSpec NewSS, *NewSSPtr = SS; 00186 if (SS && NNS) { 00187 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 00188 NewSSPtr = &NewSS; 00189 } 00190 if (Correction && (NNS || NewII != &II) && 00191 // Ignore a correction to a template type as the to-be-corrected 00192 // identifier is not a template (typo correction for template names 00193 // is handled elsewhere). 00194 !(getLangOpts().CPlusPlus && NewSSPtr && 00195 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 00196 false, Template, MemberOfUnknownSpecialization))) { 00197 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 00198 isClassName, HasTrailingDot, ObjectTypePtr, 00199 IsCtorOrDtorName, 00200 WantNontrivialTypeSourceInfo); 00201 if (Ty) { 00202 std::string CorrectedStr(Correction.getAsString(getLangOpts())); 00203 std::string CorrectedQuotedStr( 00204 Correction.getQuoted(getLangOpts())); 00205 Diag(NameLoc, diag::err_unknown_typename_suggest) 00206 << Result.getLookupName() << CorrectedQuotedStr 00207 << FixItHint::CreateReplacement(SourceRange(NameLoc), 00208 CorrectedStr); 00209 if (NamedDecl *FirstDecl = Correction.getCorrectionDecl()) 00210 Diag(FirstDecl->getLocation(), diag::note_previous_decl) 00211 << CorrectedQuotedStr; 00212 00213 if (SS && NNS) 00214 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 00215 *CorrectedII = NewII; 00216 return Ty; 00217 } 00218 } 00219 } 00220 // If typo correction failed or was not performed, fall through 00221 case LookupResult::FoundOverloaded: 00222 case LookupResult::FoundUnresolvedValue: 00223 Result.suppressDiagnostics(); 00224 return ParsedType(); 00225 00226 case LookupResult::Ambiguous: 00227 // Recover from type-hiding ambiguities by hiding the type. We'll 00228 // do the lookup again when looking for an object, and we can 00229 // diagnose the error then. If we don't do this, then the error 00230 // about hiding the type will be immediately followed by an error 00231 // that only makes sense if the identifier was treated like a type. 00232 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 00233 Result.suppressDiagnostics(); 00234 return ParsedType(); 00235 } 00236 00237 // Look to see if we have a type anywhere in the list of results. 00238 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 00239 Res != ResEnd; ++Res) { 00240 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 00241 if (!IIDecl || 00242 (*Res)->getLocation().getRawEncoding() < 00243 IIDecl->getLocation().getRawEncoding()) 00244 IIDecl = *Res; 00245 } 00246 } 00247 00248 if (!IIDecl) { 00249 // None of the entities we found is a type, so there is no way 00250 // to even assume that the result is a type. In this case, don't 00251 // complain about the ambiguity. The parser will either try to 00252 // perform this lookup again (e.g., as an object name), which 00253 // will produce the ambiguity, or will complain that it expected 00254 // a type name. 00255 Result.suppressDiagnostics(); 00256 return ParsedType(); 00257 } 00258 00259 // We found a type within the ambiguous lookup; diagnose the 00260 // ambiguity and then return that type. This might be the right 00261 // answer, or it might not be, but it suppresses any attempt to 00262 // perform the name lookup again. 00263 break; 00264 00265 case LookupResult::Found: 00266 IIDecl = Result.getFoundDecl(); 00267 break; 00268 } 00269 00270 assert(IIDecl && "Didn't find decl"); 00271 00272 QualType T; 00273 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 00274 DiagnoseUseOfDecl(IIDecl, NameLoc); 00275 00276 if (T.isNull()) 00277 T = Context.getTypeDeclType(TD); 00278 00279 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 00280 // constructor or destructor name (in such a case, the scope specifier 00281 // will be attached to the enclosing Expr or Decl node). 00282 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 00283 if (WantNontrivialTypeSourceInfo) { 00284 // Construct a type with type-source information. 00285 TypeLocBuilder Builder; 00286 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 00287 00288 T = getElaboratedType(ETK_None, *SS, T); 00289 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 00290 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 00291 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 00292 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 00293 } else { 00294 T = getElaboratedType(ETK_None, *SS, T); 00295 } 00296 } 00297 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 00298 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 00299 if (!HasTrailingDot) 00300 T = Context.getObjCInterfaceType(IDecl); 00301 } 00302 00303 if (T.isNull()) { 00304 // If it's not plausibly a type, suppress diagnostics. 00305 Result.suppressDiagnostics(); 00306 return ParsedType(); 00307 } 00308 return ParsedType::make(T); 00309 } 00310 00311 /// isTagName() - This method is called *for error recovery purposes only* 00312 /// to determine if the specified name is a valid tag name ("struct foo"). If 00313 /// so, this returns the TST for the tag corresponding to it (TST_enum, 00314 /// TST_union, TST_struct, TST_class). This is used to diagnose cases in C 00315 /// where the user forgot to specify the tag. 00316 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 00317 // Do a tag name lookup in this scope. 00318 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 00319 LookupName(R, S, false); 00320 R.suppressDiagnostics(); 00321 if (R.getResultKind() == LookupResult::Found) 00322 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 00323 switch (TD->getTagKind()) { 00324 case TTK_Struct: return DeclSpec::TST_struct; 00325 case TTK_Union: return DeclSpec::TST_union; 00326 case TTK_Class: return DeclSpec::TST_class; 00327 case TTK_Enum: return DeclSpec::TST_enum; 00328 } 00329 } 00330 00331 return DeclSpec::TST_unspecified; 00332 } 00333 00334 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 00335 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 00336 /// then downgrade the missing typename error to a warning. 00337 /// This is needed for MSVC compatibility; Example: 00338 /// @code 00339 /// template<class T> class A { 00340 /// public: 00341 /// typedef int TYPE; 00342 /// }; 00343 /// template<class T> class B : public A<T> { 00344 /// public: 00345 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 00346 /// }; 00347 /// @endcode 00348 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 00349 if (CurContext->isRecord()) { 00350 const Type *Ty = SS->getScopeRep()->getAsType(); 00351 00352 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 00353 for (CXXRecordDecl::base_class_const_iterator Base = RD->bases_begin(), 00354 BaseEnd = RD->bases_end(); Base != BaseEnd; ++Base) 00355 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base->getType())) 00356 return true; 00357 return S->isFunctionPrototypeScope(); 00358 } 00359 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 00360 } 00361 00362 bool Sema::DiagnoseUnknownTypeName(const IdentifierInfo &II, 00363 SourceLocation IILoc, 00364 Scope *S, 00365 CXXScopeSpec *SS, 00366 ParsedType &SuggestedType) { 00367 // We don't have anything to suggest (yet). 00368 SuggestedType = ParsedType(); 00369 00370 // There may have been a typo in the name of the type. Look up typo 00371 // results, in case we have something that we can suggest. 00372 TypeNameValidatorCCC Validator(false); 00373 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(&II, IILoc), 00374 LookupOrdinaryName, S, SS, 00375 Validator)) { 00376 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 00377 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 00378 00379 if (Corrected.isKeyword()) { 00380 // We corrected to a keyword. 00381 // FIXME: Actually recover with the keyword we suggest, and emit a fix-it. 00382 Diag(IILoc, diag::err_unknown_typename_suggest) 00383 << &II << CorrectedQuotedStr; 00384 } else { 00385 NamedDecl *Result = Corrected.getCorrectionDecl(); 00386 // We found a similarly-named type or interface; suggest that. 00387 if (!SS || !SS->isSet()) 00388 Diag(IILoc, diag::err_unknown_typename_suggest) 00389 << &II << CorrectedQuotedStr 00390 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 00391 else if (DeclContext *DC = computeDeclContext(*SS, false)) 00392 Diag(IILoc, diag::err_unknown_nested_typename_suggest) 00393 << &II << DC << CorrectedQuotedStr << SS->getRange() 00394 << FixItHint::CreateReplacement(SourceRange(IILoc), CorrectedStr); 00395 else 00396 llvm_unreachable("could not have corrected a typo here"); 00397 00398 Diag(Result->getLocation(), diag::note_previous_decl) 00399 << CorrectedQuotedStr; 00400 00401 SuggestedType = getTypeName(*Result->getIdentifier(), IILoc, S, SS, 00402 false, false, ParsedType(), 00403 /*IsCtorOrDtorName=*/false, 00404 /*NonTrivialTypeSourceInfo=*/true); 00405 } 00406 return true; 00407 } 00408 00409 if (getLangOpts().CPlusPlus) { 00410 // See if II is a class template that the user forgot to pass arguments to. 00411 UnqualifiedId Name; 00412 Name.setIdentifier(&II, IILoc); 00413 CXXScopeSpec EmptySS; 00414 TemplateTy TemplateResult; 00415 bool MemberOfUnknownSpecialization; 00416 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 00417 Name, ParsedType(), true, TemplateResult, 00418 MemberOfUnknownSpecialization) == TNK_Type_template) { 00419 TemplateName TplName = TemplateResult.getAsVal<TemplateName>(); 00420 Diag(IILoc, diag::err_template_missing_args) << TplName; 00421 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 00422 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 00423 << TplDecl->getTemplateParameters()->getSourceRange(); 00424 } 00425 return true; 00426 } 00427 } 00428 00429 // FIXME: Should we move the logic that tries to recover from a missing tag 00430 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 00431 00432 if (!SS || (!SS->isSet() && !SS->isInvalid())) 00433 Diag(IILoc, diag::err_unknown_typename) << &II; 00434 else if (DeclContext *DC = computeDeclContext(*SS, false)) 00435 Diag(IILoc, diag::err_typename_nested_not_found) 00436 << &II << DC << SS->getRange(); 00437 else if (isDependentScopeSpecifier(*SS)) { 00438 unsigned DiagID = diag::err_typename_missing; 00439 if (getLangOpts().MicrosoftMode && isMicrosoftMissingTypename(SS, S)) 00440 DiagID = diag::warn_typename_missing; 00441 00442 Diag(SS->getRange().getBegin(), DiagID) 00443 << (NestedNameSpecifier *)SS->getScopeRep() << II.getName() 00444 << SourceRange(SS->getRange().getBegin(), IILoc) 00445 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 00446 SuggestedType = ActOnTypenameType(S, SourceLocation(), *SS, II, IILoc) 00447 .get(); 00448 } else { 00449 assert(SS && SS->isInvalid() && 00450 "Invalid scope specifier has already been diagnosed"); 00451 } 00452 00453 return true; 00454 } 00455 00456 /// \brief Determine whether the given result set contains either a type name 00457 /// or 00458 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 00459 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 00460 NextToken.is(tok::less); 00461 00462 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 00463 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 00464 return true; 00465 00466 if (CheckTemplate && isa<TemplateDecl>(*I)) 00467 return true; 00468 } 00469 00470 return false; 00471 } 00472 00473 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 00474 Scope *S, CXXScopeSpec &SS, 00475 IdentifierInfo *&Name, 00476 SourceLocation NameLoc) { 00477 Result.clear(Sema::LookupTagName); 00478 SemaRef.LookupParsedName(Result, S, &SS); 00479 if (TagDecl *Tag = Result.getAsSingle<TagDecl>()) { 00480 const char *TagName = 0; 00481 const char *FixItTagName = 0; 00482 switch (Tag->getTagKind()) { 00483 case TTK_Class: 00484 TagName = "class"; 00485 FixItTagName = "class "; 00486 break; 00487 00488 case TTK_Enum: 00489 TagName = "enum"; 00490 FixItTagName = "enum "; 00491 break; 00492 00493 case TTK_Struct: 00494 TagName = "struct"; 00495 FixItTagName = "struct "; 00496 break; 00497 00498 case TTK_Union: 00499 TagName = "union"; 00500 FixItTagName = "union "; 00501 break; 00502 } 00503 00504 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 00505 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 00506 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 00507 00508 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupOrdinaryName); 00509 if (SemaRef.LookupParsedName(R, S, &SS)) { 00510 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); 00511 I != IEnd; ++I) 00512 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 00513 << Name << TagName; 00514 } 00515 return true; 00516 } 00517 00518 Result.clear(Sema::LookupOrdinaryName); 00519 return false; 00520 } 00521 00522 Sema::NameClassification Sema::ClassifyName(Scope *S, 00523 CXXScopeSpec &SS, 00524 IdentifierInfo *&Name, 00525 SourceLocation NameLoc, 00526 const Token &NextToken) { 00527 DeclarationNameInfo NameInfo(Name, NameLoc); 00528 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 00529 00530 if (NextToken.is(tok::coloncolon)) { 00531 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 00532 QualType(), false, SS, 0, false); 00533 00534 } 00535 00536 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 00537 LookupParsedName(Result, S, &SS, !CurMethod); 00538 00539 // Perform lookup for Objective-C instance variables (including automatically 00540 // synthesized instance variables), if we're in an Objective-C method. 00541 // FIXME: This lookup really, really needs to be folded in to the normal 00542 // unqualified lookup mechanism. 00543 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 00544 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 00545 if (E.get() || E.isInvalid()) 00546 return E; 00547 } 00548 00549 bool SecondTry = false; 00550 bool IsFilteredTemplateName = false; 00551 00552 Corrected: 00553 switch (Result.getResultKind()) { 00554 case LookupResult::NotFound: 00555 // If an unqualified-id is followed by a '(', then we have a function 00556 // call. 00557 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 00558 // In C++, this is an ADL-only call. 00559 // FIXME: Reference? 00560 if (getLangOpts().CPlusPlus) 00561 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 00562 00563 // C90 6.3.2.2: 00564 // If the expression that precedes the parenthesized argument list in a 00565 // function call consists solely of an identifier, and if no 00566 // declaration is visible for this identifier, the identifier is 00567 // implicitly declared exactly as if, in the innermost block containing 00568 // the function call, the declaration 00569 // 00570 // extern int identifier (); 00571 // 00572 // appeared. 00573 // 00574 // We also allow this in C99 as an extension. 00575 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 00576 Result.addDecl(D); 00577 Result.resolveKind(); 00578 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 00579 } 00580 } 00581 00582 // In C, we first see whether there is a tag type by the same name, in 00583 // which case it's likely that the user just forget to write "enum", 00584 // "struct", or "union". 00585 if (!getLangOpts().CPlusPlus && !SecondTry && 00586 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 00587 break; 00588 } 00589 00590 // Perform typo correction to determine if there is another name that is 00591 // close to this name. 00592 if (!SecondTry) { 00593 SecondTry = true; 00594 CorrectionCandidateCallback DefaultValidator; 00595 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 00596 Result.getLookupKind(), S, 00597 &SS, DefaultValidator)) { 00598 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 00599 unsigned QualifiedDiag = diag::err_no_member_suggest; 00600 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 00601 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts())); 00602 00603 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 00604 NamedDecl *UnderlyingFirstDecl 00605 = FirstDecl? FirstDecl->getUnderlyingDecl() : 0; 00606 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 00607 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 00608 UnqualifiedDiag = diag::err_no_template_suggest; 00609 QualifiedDiag = diag::err_no_member_template_suggest; 00610 } else if (UnderlyingFirstDecl && 00611 (isa<TypeDecl>(UnderlyingFirstDecl) || 00612 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 00613 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 00614 UnqualifiedDiag = diag::err_unknown_typename_suggest; 00615 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 00616 } 00617 00618 if (SS.isEmpty()) 00619 Diag(NameLoc, UnqualifiedDiag) 00620 << Name << CorrectedQuotedStr 00621 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 00622 else 00623 Diag(NameLoc, QualifiedDiag) 00624 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr 00625 << SS.getRange() 00626 << FixItHint::CreateReplacement(NameLoc, CorrectedStr); 00627 00628 // Update the name, so that the caller has the new name. 00629 Name = Corrected.getCorrectionAsIdentifierInfo(); 00630 00631 // Typo correction corrected to a keyword. 00632 if (Corrected.isKeyword()) 00633 return Corrected.getCorrectionAsIdentifierInfo(); 00634 00635 // Also update the LookupResult... 00636 // FIXME: This should probably go away at some point 00637 Result.clear(); 00638 Result.setLookupName(Corrected.getCorrection()); 00639 if (FirstDecl) { 00640 Result.addDecl(FirstDecl); 00641 Diag(FirstDecl->getLocation(), diag::note_previous_decl) 00642 << CorrectedQuotedStr; 00643 } 00644 00645 // If we found an Objective-C instance variable, let 00646 // LookupInObjCMethod build the appropriate expression to 00647 // reference the ivar. 00648 // FIXME: This is a gross hack. 00649 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 00650 Result.clear(); 00651 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 00652 return move(E); 00653 } 00654 00655 goto Corrected; 00656 } 00657 } 00658 00659 // We failed to correct; just fall through and let the parser deal with it. 00660 Result.suppressDiagnostics(); 00661 return NameClassification::Unknown(); 00662 00663 case LookupResult::NotFoundInCurrentInstantiation: { 00664 // We performed name lookup into the current instantiation, and there were 00665 // dependent bases, so we treat this result the same way as any other 00666 // dependent nested-name-specifier. 00667 00668 // C++ [temp.res]p2: 00669 // A name used in a template declaration or definition and that is 00670 // dependent on a template-parameter is assumed not to name a type 00671 // unless the applicable name lookup finds a type name or the name is 00672 // qualified by the keyword typename. 00673 // 00674 // FIXME: If the next token is '<', we might want to ask the parser to 00675 // perform some heroics to see if we actually have a 00676 // template-argument-list, which would indicate a missing 'template' 00677 // keyword here. 00678 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(), 00679 NameInfo, /*TemplateArgs=*/0); 00680 } 00681 00682 case LookupResult::Found: 00683 case LookupResult::FoundOverloaded: 00684 case LookupResult::FoundUnresolvedValue: 00685 break; 00686 00687 case LookupResult::Ambiguous: 00688 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 00689 hasAnyAcceptableTemplateNames(Result)) { 00690 // C++ [temp.local]p3: 00691 // A lookup that finds an injected-class-name (10.2) can result in an 00692 // ambiguity in certain cases (for example, if it is found in more than 00693 // one base class). If all of the injected-class-names that are found 00694 // refer to specializations of the same class template, and if the name 00695 // is followed by a template-argument-list, the reference refers to the 00696 // class template itself and not a specialization thereof, and is not 00697 // ambiguous. 00698 // 00699 // This filtering can make an ambiguous result into an unambiguous one, 00700 // so try again after filtering out template names. 00701 FilterAcceptableTemplateNames(Result); 00702 if (!Result.isAmbiguous()) { 00703 IsFilteredTemplateName = true; 00704 break; 00705 } 00706 } 00707 00708 // Diagnose the ambiguity and return an error. 00709 return NameClassification::Error(); 00710 } 00711 00712 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 00713 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 00714 // C++ [temp.names]p3: 00715 // After name lookup (3.4) finds that a name is a template-name or that 00716 // an operator-function-id or a literal- operator-id refers to a set of 00717 // overloaded functions any member of which is a function template if 00718 // this is followed by a <, the < is always taken as the delimiter of a 00719 // template-argument-list and never as the less-than operator. 00720 if (!IsFilteredTemplateName) 00721 FilterAcceptableTemplateNames(Result); 00722 00723 if (!Result.empty()) { 00724 bool IsFunctionTemplate; 00725 TemplateName Template; 00726 if (Result.end() - Result.begin() > 1) { 00727 IsFunctionTemplate = true; 00728 Template = Context.getOverloadedTemplateName(Result.begin(), 00729 Result.end()); 00730 } else { 00731 TemplateDecl *TD 00732 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 00733 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 00734 00735 if (SS.isSet() && !SS.isInvalid()) 00736 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 00737 /*TemplateKeyword=*/false, 00738 TD); 00739 else 00740 Template = TemplateName(TD); 00741 } 00742 00743 if (IsFunctionTemplate) { 00744 // Function templates always go through overload resolution, at which 00745 // point we'll perform the various checks (e.g., accessibility) we need 00746 // to based on which function we selected. 00747 Result.suppressDiagnostics(); 00748 00749 return NameClassification::FunctionTemplate(Template); 00750 } 00751 00752 return NameClassification::TypeTemplate(Template); 00753 } 00754 } 00755 00756 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 00757 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 00758 DiagnoseUseOfDecl(Type, NameLoc); 00759 QualType T = Context.getTypeDeclType(Type); 00760 return ParsedType::make(T); 00761 } 00762 00763 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 00764 if (!Class) { 00765 // FIXME: It's unfortunate that we don't have a Type node for handling this. 00766 if (ObjCCompatibleAliasDecl *Alias 00767 = dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 00768 Class = Alias->getClassInterface(); 00769 } 00770 00771 if (Class) { 00772 DiagnoseUseOfDecl(Class, NameLoc); 00773 00774 if (NextToken.is(tok::period)) { 00775 // Interface. <something> is parsed as a property reference expression. 00776 // Just return "unknown" as a fall-through for now. 00777 Result.suppressDiagnostics(); 00778 return NameClassification::Unknown(); 00779 } 00780 00781 QualType T = Context.getObjCInterfaceType(Class); 00782 return ParsedType::make(T); 00783 } 00784 00785 // Check for a tag type hidden by a non-type decl in a few cases where it 00786 // seems likely a type is wanted instead of the non-type that was found. 00787 if (!getLangOpts().ObjC1 && FirstDecl && !isa<ClassTemplateDecl>(FirstDecl) && 00788 !isa<TypeAliasTemplateDecl>(FirstDecl)) { 00789 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 00790 if ((NextToken.is(tok::identifier) || 00791 (NextIsOp && FirstDecl->isFunctionOrFunctionTemplate())) && 00792 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 00793 FirstDecl = (*Result.begin())->getUnderlyingDecl(); 00794 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 00795 DiagnoseUseOfDecl(Type, NameLoc); 00796 QualType T = Context.getTypeDeclType(Type); 00797 return ParsedType::make(T); 00798 } 00799 } 00800 } 00801 00802 if (!Result.empty() && (*Result.begin())->isCXXClassMember()) 00803 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 0); 00804 00805 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 00806 return BuildDeclarationNameExpr(SS, Result, ADL); 00807 } 00808 00809 // Determines the context to return to after temporarily entering a 00810 // context. This depends in an unnecessarily complicated way on the 00811 // exact ordering of callbacks from the parser. 00812 DeclContext *Sema::getContainingDC(DeclContext *DC) { 00813 00814 // Functions defined inline within classes aren't parsed until we've 00815 // finished parsing the top-level class, so the top-level class is 00816 // the context we'll need to return to. 00817 if (isa<FunctionDecl>(DC)) { 00818 DC = DC->getLexicalParent(); 00819 00820 // A function not defined within a class will always return to its 00821 // lexical context. 00822 if (!isa<CXXRecordDecl>(DC)) 00823 return DC; 00824 00825 // A C++ inline method/friend is parsed *after* the topmost class 00826 // it was declared in is fully parsed ("complete"); the topmost 00827 // class is the context we need to return to. 00828 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 00829 DC = RD; 00830 00831 // Return the declaration context of the topmost class the inline method is 00832 // declared in. 00833 return DC; 00834 } 00835 00836 return DC->getLexicalParent(); 00837 } 00838 00839 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 00840 assert(getContainingDC(DC) == CurContext && 00841 "The next DeclContext should be lexically contained in the current one."); 00842 CurContext = DC; 00843 S->setEntity(DC); 00844 } 00845 00846 void Sema::PopDeclContext() { 00847 assert(CurContext && "DeclContext imbalance!"); 00848 00849 CurContext = getContainingDC(CurContext); 00850 assert(CurContext && "Popped translation unit!"); 00851 } 00852 00853 /// EnterDeclaratorContext - Used when we must lookup names in the context 00854 /// of a declarator's nested name specifier. 00855 /// 00856 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 00857 // C++0x [basic.lookup.unqual]p13: 00858 // A name used in the definition of a static data member of class 00859 // X (after the qualified-id of the static member) is looked up as 00860 // if the name was used in a member function of X. 00861 // C++0x [basic.lookup.unqual]p14: 00862 // If a variable member of a namespace is defined outside of the 00863 // scope of its namespace then any name used in the definition of 00864 // the variable member (after the declarator-id) is looked up as 00865 // if the definition of the variable member occurred in its 00866 // namespace. 00867 // Both of these imply that we should push a scope whose context 00868 // is the semantic context of the declaration. We can't use 00869 // PushDeclContext here because that context is not necessarily 00870 // lexically contained in the current context. Fortunately, 00871 // the containing scope should have the appropriate information. 00872 00873 assert(!S->getEntity() && "scope already has entity"); 00874 00875 #ifndef NDEBUG 00876 Scope *Ancestor = S->getParent(); 00877 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 00878 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 00879 #endif 00880 00881 CurContext = DC; 00882 S->setEntity(DC); 00883 } 00884 00885 void Sema::ExitDeclaratorContext(Scope *S) { 00886 assert(S->getEntity() == CurContext && "Context imbalance!"); 00887 00888 // Switch back to the lexical context. The safety of this is 00889 // enforced by an assert in EnterDeclaratorContext. 00890 Scope *Ancestor = S->getParent(); 00891 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 00892 CurContext = (DeclContext*) Ancestor->getEntity(); 00893 00894 // We don't need to do anything with the scope, which is going to 00895 // disappear. 00896 } 00897 00898 00899 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 00900 FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 00901 if (FunctionTemplateDecl *TFD = dyn_cast_or_null<FunctionTemplateDecl>(D)) { 00902 // We assume that the caller has already called 00903 // ActOnReenterTemplateScope 00904 FD = TFD->getTemplatedDecl(); 00905 } 00906 if (!FD) 00907 return; 00908 00909 // Same implementation as PushDeclContext, but enters the context 00910 // from the lexical parent, rather than the top-level class. 00911 assert(CurContext == FD->getLexicalParent() && 00912 "The next DeclContext should be lexically contained in the current one."); 00913 CurContext = FD; 00914 S->setEntity(CurContext); 00915 00916 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 00917 ParmVarDecl *Param = FD->getParamDecl(P); 00918 // If the parameter has an identifier, then add it to the scope 00919 if (Param->getIdentifier()) { 00920 S->AddDecl(Param); 00921 IdResolver.AddDecl(Param); 00922 } 00923 } 00924 } 00925 00926 00927 void Sema::ActOnExitFunctionContext() { 00928 // Same implementation as PopDeclContext, but returns to the lexical parent, 00929 // rather than the top-level class. 00930 assert(CurContext && "DeclContext imbalance!"); 00931 CurContext = CurContext->getLexicalParent(); 00932 assert(CurContext && "Popped translation unit!"); 00933 } 00934 00935 00936 /// \brief Determine whether we allow overloading of the function 00937 /// PrevDecl with another declaration. 00938 /// 00939 /// This routine determines whether overloading is possible, not 00940 /// whether some new function is actually an overload. It will return 00941 /// true in C++ (where we can always provide overloads) or, as an 00942 /// extension, in C when the previous function is already an 00943 /// overloaded function declaration or has the "overloadable" 00944 /// attribute. 00945 static bool AllowOverloadingOfFunction(LookupResult &Previous, 00946 ASTContext &Context) { 00947 if (Context.getLangOpts().CPlusPlus) 00948 return true; 00949 00950 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 00951 return true; 00952 00953 return (Previous.getResultKind() == LookupResult::Found 00954 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 00955 } 00956 00957 /// Add this decl to the scope shadowed decl chains. 00958 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 00959 // Move up the scope chain until we find the nearest enclosing 00960 // non-transparent context. The declaration will be introduced into this 00961 // scope. 00962 while (S->getEntity() && 00963 ((DeclContext *)S->getEntity())->isTransparentContext()) 00964 S = S->getParent(); 00965 00966 // Add scoped declarations into their context, so that they can be 00967 // found later. Declarations without a context won't be inserted 00968 // into any context. 00969 if (AddToContext) 00970 CurContext->addDecl(D); 00971 00972 // Out-of-line definitions shouldn't be pushed into scope in C++. 00973 // Out-of-line variable and function definitions shouldn't even in C. 00974 if ((getLangOpts().CPlusPlus || isa<VarDecl>(D) || isa<FunctionDecl>(D)) && 00975 D->isOutOfLine() && 00976 !D->getDeclContext()->getRedeclContext()->Equals( 00977 D->getLexicalDeclContext()->getRedeclContext())) 00978 return; 00979 00980 // Template instantiations should also not be pushed into scope. 00981 if (isa<FunctionDecl>(D) && 00982 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 00983 return; 00984 00985 // If this replaces anything in the current scope, 00986 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 00987 IEnd = IdResolver.end(); 00988 for (; I != IEnd; ++I) { 00989 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 00990 S->RemoveDecl(*I); 00991 IdResolver.RemoveDecl(*I); 00992 00993 // Should only need to replace one decl. 00994 break; 00995 } 00996 } 00997 00998 S->AddDecl(D); 00999 01000 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 01001 // Implicitly-generated labels may end up getting generated in an order that 01002 // isn't strictly lexical, which breaks name lookup. Be careful to insert 01003 // the label at the appropriate place in the identifier chain. 01004 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 01005 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 01006 if (IDC == CurContext) { 01007 if (!S->isDeclScope(*I)) 01008 continue; 01009 } else if (IDC->Encloses(CurContext)) 01010 break; 01011 } 01012 01013 IdResolver.InsertDeclAfter(I, D); 01014 } else { 01015 IdResolver.AddDecl(D); 01016 } 01017 } 01018 01019 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 01020 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 01021 TUScope->AddDecl(D); 01022 } 01023 01024 bool Sema::isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S, 01025 bool ExplicitInstantiationOrSpecialization) { 01026 return IdResolver.isDeclInScope(D, Ctx, Context, S, 01027 ExplicitInstantiationOrSpecialization); 01028 } 01029 01030 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 01031 DeclContext *TargetDC = DC->getPrimaryContext(); 01032 do { 01033 if (DeclContext *ScopeDC = (DeclContext*) S->getEntity()) 01034 if (ScopeDC->getPrimaryContext() == TargetDC) 01035 return S; 01036 } while ((S = S->getParent())); 01037 01038 return 0; 01039 } 01040 01041 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 01042 DeclContext*, 01043 ASTContext&); 01044 01045 /// Filters out lookup results that don't fall within the given scope 01046 /// as determined by isDeclInScope. 01047 void Sema::FilterLookupForScope(LookupResult &R, 01048 DeclContext *Ctx, Scope *S, 01049 bool ConsiderLinkage, 01050 bool ExplicitInstantiationOrSpecialization) { 01051 LookupResult::Filter F = R.makeFilter(); 01052 while (F.hasNext()) { 01053 NamedDecl *D = F.next(); 01054 01055 if (isDeclInScope(D, Ctx, S, ExplicitInstantiationOrSpecialization)) 01056 continue; 01057 01058 if (ConsiderLinkage && 01059 isOutOfScopePreviousDeclaration(D, Ctx, Context)) 01060 continue; 01061 01062 F.erase(); 01063 } 01064 01065 F.done(); 01066 } 01067 01068 static bool isUsingDecl(NamedDecl *D) { 01069 return isa<UsingShadowDecl>(D) || 01070 isa<UnresolvedUsingTypenameDecl>(D) || 01071 isa<UnresolvedUsingValueDecl>(D); 01072 } 01073 01074 /// Removes using shadow declarations from the lookup results. 01075 static void RemoveUsingDecls(LookupResult &R) { 01076 LookupResult::Filter F = R.makeFilter(); 01077 while (F.hasNext()) 01078 if (isUsingDecl(F.next())) 01079 F.erase(); 01080 01081 F.done(); 01082 } 01083 01084 /// \brief Check for this common pattern: 01085 /// @code 01086 /// class S { 01087 /// S(const S&); // DO NOT IMPLEMENT 01088 /// void operator=(const S&); // DO NOT IMPLEMENT 01089 /// }; 01090 /// @endcode 01091 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 01092 // FIXME: Should check for private access too but access is set after we get 01093 // the decl here. 01094 if (D->doesThisDeclarationHaveABody()) 01095 return false; 01096 01097 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 01098 return CD->isCopyConstructor(); 01099 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 01100 return Method->isCopyAssignmentOperator(); 01101 return false; 01102 } 01103 01104 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 01105 assert(D); 01106 01107 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 01108 return false; 01109 01110 // Ignore class templates. 01111 if (D->getDeclContext()->isDependentContext() || 01112 D->getLexicalDeclContext()->isDependentContext()) 01113 return false; 01114 01115 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 01116 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 01117 return false; 01118 01119 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 01120 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 01121 return false; 01122 } else { 01123 // 'static inline' functions are used in headers; don't warn. 01124 if (FD->getStorageClass() == SC_Static && 01125 FD->isInlineSpecified()) 01126 return false; 01127 } 01128 01129 if (FD->doesThisDeclarationHaveABody() && 01130 Context.DeclMustBeEmitted(FD)) 01131 return false; 01132 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 01133 if (!VD->isFileVarDecl() || 01134 VD->getType().isConstant(Context) || 01135 Context.DeclMustBeEmitted(VD)) 01136 return false; 01137 01138 if (VD->isStaticDataMember() && 01139 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 01140 return false; 01141 01142 } else { 01143 return false; 01144 } 01145 01146 // Only warn for unused decls internal to the translation unit. 01147 if (D->getLinkage() == ExternalLinkage) 01148 return false; 01149 01150 return true; 01151 } 01152 01153 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 01154 if (!D) 01155 return; 01156 01157 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 01158 const FunctionDecl *First = FD->getFirstDeclaration(); 01159 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 01160 return; // First should already be in the vector. 01161 } 01162 01163 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 01164 const VarDecl *First = VD->getFirstDeclaration(); 01165 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 01166 return; // First should already be in the vector. 01167 } 01168 01169 if (ShouldWarnIfUnusedFileScopedDecl(D)) 01170 UnusedFileScopedDecls.push_back(D); 01171 } 01172 01173 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 01174 if (D->isInvalidDecl()) 01175 return false; 01176 01177 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>()) 01178 return false; 01179 01180 if (isa<LabelDecl>(D)) 01181 return true; 01182 01183 // White-list anything that isn't a local variable. 01184 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D) || 01185 !D->getDeclContext()->isFunctionOrMethod()) 01186 return false; 01187 01188 // Types of valid local variables should be complete, so this should succeed. 01189 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 01190 01191 // White-list anything with an __attribute__((unused)) type. 01192 QualType Ty = VD->getType(); 01193 01194 // Only look at the outermost level of typedef. 01195 if (const TypedefType *TT = dyn_cast<TypedefType>(Ty)) { 01196 if (TT->getDecl()->hasAttr<UnusedAttr>()) 01197 return false; 01198 } 01199 01200 // If we failed to complete the type for some reason, or if the type is 01201 // dependent, don't diagnose the variable. 01202 if (Ty->isIncompleteType() || Ty->isDependentType()) 01203 return false; 01204 01205 if (const TagType *TT = Ty->getAs<TagType>()) { 01206 const TagDecl *Tag = TT->getDecl(); 01207 if (Tag->hasAttr<UnusedAttr>()) 01208 return false; 01209 01210 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 01211 if (!RD->hasTrivialDestructor()) 01212 return false; 01213 01214 if (const Expr *Init = VD->getInit()) { 01215 const CXXConstructExpr *Construct = 01216 dyn_cast<CXXConstructExpr>(Init); 01217 if (Construct && !Construct->isElidable()) { 01218 CXXConstructorDecl *CD = Construct->getConstructor(); 01219 if (!CD->isTrivial()) 01220 return false; 01221 } 01222 } 01223 } 01224 } 01225 01226 // TODO: __attribute__((unused)) templates? 01227 } 01228 01229 return true; 01230 } 01231 01232 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 01233 FixItHint &Hint) { 01234 if (isa<LabelDecl>(D)) { 01235 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 01236 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 01237 if (AfterColon.isInvalid()) 01238 return; 01239 Hint = FixItHint::CreateRemoval(CharSourceRange:: 01240 getCharRange(D->getLocStart(), AfterColon)); 01241 } 01242 return; 01243 } 01244 01245 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 01246 /// unless they are marked attr(unused). 01247 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 01248 FixItHint Hint; 01249 if (!ShouldDiagnoseUnusedDecl(D)) 01250 return; 01251 01252 GenerateFixForUnusedDecl(D, Context, Hint); 01253 01254 unsigned DiagID; 01255 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 01256 DiagID = diag::warn_unused_exception_param; 01257 else if (isa<LabelDecl>(D)) 01258 DiagID = diag::warn_unused_label; 01259 else 01260 DiagID = diag::warn_unused_variable; 01261 01262 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 01263 } 01264 01265 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 01266 // Verify that we have no forward references left. If so, there was a goto 01267 // or address of a label taken, but no definition of it. Label fwd 01268 // definitions are indicated with a null substmt. 01269 if (L->getStmt() == 0) 01270 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 01271 } 01272 01273 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 01274 if (S->decl_empty()) return; 01275 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 01276 "Scope shouldn't contain decls!"); 01277 01278 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end(); 01279 I != E; ++I) { 01280 Decl *TmpD = (*I); 01281 assert(TmpD && "This decl didn't get pushed??"); 01282 01283 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 01284 NamedDecl *D = cast<NamedDecl>(TmpD); 01285 01286 if (!D->getDeclName()) continue; 01287 01288 // Diagnose unused variables in this scope. 01289 if (!S->hasErrorOccurred()) 01290 DiagnoseUnusedDecl(D); 01291 01292 // If this was a forward reference to a label, verify it was defined. 01293 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 01294 CheckPoppedLabel(LD, *this); 01295 01296 // Remove this name from our lexical scope. 01297 IdResolver.RemoveDecl(D); 01298 } 01299 } 01300 01301 void Sema::ActOnStartFunctionDeclarator() { 01302 ++InFunctionDeclarator; 01303 } 01304 01305 void Sema::ActOnEndFunctionDeclarator() { 01306 assert(InFunctionDeclarator); 01307 --InFunctionDeclarator; 01308 } 01309 01310 /// \brief Look for an Objective-C class in the translation unit. 01311 /// 01312 /// \param Id The name of the Objective-C class we're looking for. If 01313 /// typo-correction fixes this name, the Id will be updated 01314 /// to the fixed name. 01315 /// 01316 /// \param IdLoc The location of the name in the translation unit. 01317 /// 01318 /// \param TypoCorrection If true, this routine will attempt typo correction 01319 /// if there is no class with the given name. 01320 /// 01321 /// \returns The declaration of the named Objective-C class, or NULL if the 01322 /// class could not be found. 01323 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 01324 SourceLocation IdLoc, 01325 bool DoTypoCorrection) { 01326 // The third "scope" argument is 0 since we aren't enabling lazy built-in 01327 // creation from this context. 01328 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 01329 01330 if (!IDecl && DoTypoCorrection) { 01331 // Perform typo correction at the given location, but only if we 01332 // find an Objective-C class name. 01333 DeclFilterCCC<ObjCInterfaceDecl> Validator; 01334 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 01335 LookupOrdinaryName, TUScope, NULL, 01336 Validator)) { 01337 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 01338 Diag(IdLoc, diag::err_undef_interface_suggest) 01339 << Id << IDecl->getDeclName() 01340 << FixItHint::CreateReplacement(IdLoc, IDecl->getNameAsString()); 01341 Diag(IDecl->getLocation(), diag::note_previous_decl) 01342 << IDecl->getDeclName(); 01343 01344 Id = IDecl->getIdentifier(); 01345 } 01346 } 01347 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 01348 // This routine must always return a class definition, if any. 01349 if (Def && Def->getDefinition()) 01350 Def = Def->getDefinition(); 01351 return Def; 01352 } 01353 01354 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 01355 /// from S, where a non-field would be declared. This routine copes 01356 /// with the difference between C and C++ scoping rules in structs and 01357 /// unions. For example, the following code is well-formed in C but 01358 /// ill-formed in C++: 01359 /// @code 01360 /// struct S6 { 01361 /// enum { BAR } e; 01362 /// }; 01363 /// 01364 /// void test_S6() { 01365 /// struct S6 a; 01366 /// a.e = BAR; 01367 /// } 01368 /// @endcode 01369 /// For the declaration of BAR, this routine will return a different 01370 /// scope. The scope S will be the scope of the unnamed enumeration 01371 /// within S6. In C++, this routine will return the scope associated 01372 /// with S6, because the enumeration's scope is a transparent 01373 /// context but structures can contain non-field names. In C, this 01374 /// routine will return the translation unit scope, since the 01375 /// enumeration's scope is a transparent context and structures cannot 01376 /// contain non-field names. 01377 Scope *Sema::getNonFieldDeclScope(Scope *S) { 01378 while (((S->getFlags() & Scope::DeclScope) == 0) || 01379 (S->getEntity() && 01380 ((DeclContext *)S->getEntity())->isTransparentContext()) || 01381 (S->isClassScope() && !getLangOpts().CPlusPlus)) 01382 S = S->getParent(); 01383 return S; 01384 } 01385 01386 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 01387 /// file scope. lazily create a decl for it. ForRedeclaration is true 01388 /// if we're creating this built-in in anticipation of redeclaring the 01389 /// built-in. 01390 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid, 01391 Scope *S, bool ForRedeclaration, 01392 SourceLocation Loc) { 01393 Builtin::ID BID = (Builtin::ID)bid; 01394 01395 ASTContext::GetBuiltinTypeError Error; 01396 QualType R = Context.GetBuiltinType(BID, Error); 01397 switch (Error) { 01398 case ASTContext::GE_None: 01399 // Okay 01400 break; 01401 01402 case ASTContext::GE_Missing_stdio: 01403 if (ForRedeclaration) 01404 Diag(Loc, diag::warn_implicit_decl_requires_stdio) 01405 << Context.BuiltinInfo.GetName(BID); 01406 return 0; 01407 01408 case ASTContext::GE_Missing_setjmp: 01409 if (ForRedeclaration) 01410 Diag(Loc, diag::warn_implicit_decl_requires_setjmp) 01411 << Context.BuiltinInfo.GetName(BID); 01412 return 0; 01413 01414 case ASTContext::GE_Missing_ucontext: 01415 if (ForRedeclaration) 01416 Diag(Loc, diag::warn_implicit_decl_requires_ucontext) 01417 << Context.BuiltinInfo.GetName(BID); 01418 return 0; 01419 } 01420 01421 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) { 01422 Diag(Loc, diag::ext_implicit_lib_function_decl) 01423 << Context.BuiltinInfo.GetName(BID) 01424 << R; 01425 if (Context.BuiltinInfo.getHeaderName(BID) && 01426 Diags.getDiagnosticLevel(diag::ext_implicit_lib_function_decl, Loc) 01427 != DiagnosticsEngine::Ignored) 01428 Diag(Loc, diag::note_please_include_header) 01429 << Context.BuiltinInfo.getHeaderName(BID) 01430 << Context.BuiltinInfo.GetName(BID); 01431 } 01432 01433 FunctionDecl *New = FunctionDecl::Create(Context, 01434 Context.getTranslationUnitDecl(), 01435 Loc, Loc, II, R, /*TInfo=*/0, 01436 SC_Extern, 01437 SC_None, false, 01438 /*hasPrototype=*/true); 01439 New->setImplicit(); 01440 01441 // Create Decl objects for each parameter, adding them to the 01442 // FunctionDecl. 01443 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 01444 SmallVector<ParmVarDecl*, 16> Params; 01445 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) { 01446 ParmVarDecl *parm = 01447 ParmVarDecl::Create(Context, New, SourceLocation(), 01448 SourceLocation(), 0, 01449 FT->getArgType(i), /*TInfo=*/0, 01450 SC_None, SC_None, 0); 01451 parm->setScopeInfo(0, i); 01452 Params.push_back(parm); 01453 } 01454 New->setParams(Params); 01455 } 01456 01457 AddKnownFunctionAttributes(New); 01458 01459 // TUScope is the translation-unit scope to insert this function into. 01460 // FIXME: This is hideous. We need to teach PushOnScopeChains to 01461 // relate Scopes to DeclContexts, and probably eliminate CurContext 01462 // entirely, but we're not there yet. 01463 DeclContext *SavedContext = CurContext; 01464 CurContext = Context.getTranslationUnitDecl(); 01465 PushOnScopeChains(New, TUScope); 01466 CurContext = SavedContext; 01467 return New; 01468 } 01469 01470 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 01471 QualType OldType; 01472 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 01473 OldType = OldTypedef->getUnderlyingType(); 01474 else 01475 OldType = Context.getTypeDeclType(Old); 01476 QualType NewType = New->getUnderlyingType(); 01477 01478 if (NewType->isVariablyModifiedType()) { 01479 // Must not redefine a typedef with a variably-modified type. 01480 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 01481 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 01482 << Kind << NewType; 01483 if (Old->getLocation().isValid()) 01484 Diag(Old->getLocation(), diag::note_previous_definition); 01485 New->setInvalidDecl(); 01486 return true; 01487 } 01488 01489 if (OldType != NewType && 01490 !OldType->isDependentType() && 01491 !NewType->isDependentType() && 01492 !Context.hasSameType(OldType, NewType)) { 01493 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 01494 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 01495 << Kind << NewType << OldType; 01496 if (Old->getLocation().isValid()) 01497 Diag(Old->getLocation(), diag::note_previous_definition); 01498 New->setInvalidDecl(); 01499 return true; 01500 } 01501 return false; 01502 } 01503 01504 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 01505 /// same name and scope as a previous declaration 'Old'. Figure out 01506 /// how to resolve this situation, merging decls or emitting 01507 /// diagnostics as appropriate. If there was an error, set New to be invalid. 01508 /// 01509 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 01510 // If the new decl is known invalid already, don't bother doing any 01511 // merging checks. 01512 if (New->isInvalidDecl()) return; 01513 01514 // Allow multiple definitions for ObjC built-in typedefs. 01515 // FIXME: Verify the underlying types are equivalent! 01516 if (getLangOpts().ObjC1) { 01517 const IdentifierInfo *TypeID = New->getIdentifier(); 01518 switch (TypeID->getLength()) { 01519 default: break; 01520 case 2: 01521 { 01522 if (!TypeID->isStr("id")) 01523 break; 01524 QualType T = New->getUnderlyingType(); 01525 if (!T->isPointerType()) 01526 break; 01527 if (!T->isVoidPointerType()) { 01528 QualType PT = T->getAs<PointerType>()->getPointeeType(); 01529 if (!PT->isStructureType()) 01530 break; 01531 } 01532 Context.setObjCIdRedefinitionType(T); 01533 // Install the built-in type for 'id', ignoring the current definition. 01534 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 01535 return; 01536 } 01537 case 5: 01538 if (!TypeID->isStr("Class")) 01539 break; 01540 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 01541 // Install the built-in type for 'Class', ignoring the current definition. 01542 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 01543 return; 01544 case 3: 01545 if (!TypeID->isStr("SEL")) 01546 break; 01547 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 01548 // Install the built-in type for 'SEL', ignoring the current definition. 01549 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 01550 return; 01551 } 01552 // Fall through - the typedef name was not a builtin type. 01553 } 01554 01555 // Verify the old decl was also a type. 01556 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 01557 if (!Old) { 01558 Diag(New->getLocation(), diag::err_redefinition_different_kind) 01559 << New->getDeclName(); 01560 01561 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 01562 if (OldD->getLocation().isValid()) 01563 Diag(OldD->getLocation(), diag::note_previous_definition); 01564 01565 return New->setInvalidDecl(); 01566 } 01567 01568 // If the old declaration is invalid, just give up here. 01569 if (Old->isInvalidDecl()) 01570 return New->setInvalidDecl(); 01571 01572 // If the typedef types are not identical, reject them in all languages and 01573 // with any extensions enabled. 01574 if (isIncompatibleTypedef(Old, New)) 01575 return; 01576 01577 // The types match. Link up the redeclaration chain if the old 01578 // declaration was a typedef. 01579 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) 01580 New->setPreviousDeclaration(Typedef); 01581 01582 if (getLangOpts().MicrosoftExt) 01583 return; 01584 01585 if (getLangOpts().CPlusPlus) { 01586 // C++ [dcl.typedef]p2: 01587 // In a given non-class scope, a typedef specifier can be used to 01588 // redefine the name of any type declared in that scope to refer 01589 // to the type to which it already refers. 01590 if (!isa<CXXRecordDecl>(CurContext)) 01591 return; 01592 01593 // C++0x [dcl.typedef]p4: 01594 // In a given class scope, a typedef specifier can be used to redefine 01595 // any class-name declared in that scope that is not also a typedef-name 01596 // to refer to the type to which it already refers. 01597 // 01598 // This wording came in via DR424, which was a correction to the 01599 // wording in DR56, which accidentally banned code like: 01600 // 01601 // struct S { 01602 // typedef struct A { } A; 01603 // }; 01604 // 01605 // in the C++03 standard. We implement the C++0x semantics, which 01606 // allow the above but disallow 01607 // 01608 // struct S { 01609 // typedef int I; 01610 // typedef int I; 01611 // }; 01612 // 01613 // since that was the intent of DR56. 01614 if (!isa<TypedefNameDecl>(Old)) 01615 return; 01616 01617 Diag(New->getLocation(), diag::err_redefinition) 01618 << New->getDeclName(); 01619 Diag(Old->getLocation(), diag::note_previous_definition); 01620 return New->setInvalidDecl(); 01621 } 01622 01623 // Modules always permit redefinition of typedefs, as does C11. 01624 if (getLangOpts().Modules || getLangOpts().C11) 01625 return; 01626 01627 // If we have a redefinition of a typedef in C, emit a warning. This warning 01628 // is normally mapped to an error, but can be controlled with 01629 // -Wtypedef-redefinition. If either the original or the redefinition is 01630 // in a system header, don't emit this for compatibility with GCC. 01631 if (getDiagnostics().getSuppressSystemWarnings() && 01632 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 01633 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 01634 return; 01635 01636 Diag(New->getLocation(), diag::warn_redefinition_of_typedef) 01637 << New->getDeclName(); 01638 Diag(Old->getLocation(), diag::note_previous_definition); 01639 return; 01640 } 01641 01642 /// DeclhasAttr - returns true if decl Declaration already has the target 01643 /// attribute. 01644 static bool 01645 DeclHasAttr(const Decl *D, const Attr *A) { 01646 // There can be multiple AvailabilityAttr in a Decl. Make sure we copy 01647 // all of them. It is mergeAvailabilityAttr in SemaDeclAttr.cpp that is 01648 // responsible for making sure they are consistent. 01649 const AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(A); 01650 if (AA) 01651 return false; 01652 01653 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 01654 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 01655 for (Decl::attr_iterator i = D->attr_begin(), e = D->attr_end(); i != e; ++i) 01656 if ((*i)->getKind() == A->getKind()) { 01657 if (Ann) { 01658 if (Ann->getAnnotation() == cast<AnnotateAttr>(*i)->getAnnotation()) 01659 return true; 01660 continue; 01661 } 01662 // FIXME: Don't hardcode this check 01663 if (OA && isa<OwnershipAttr>(*i)) 01664 return OA->getOwnKind() == cast<OwnershipAttr>(*i)->getOwnKind(); 01665 return true; 01666 } 01667 01668 return false; 01669 } 01670 01671 bool Sema::mergeDeclAttribute(Decl *D, InheritableAttr *Attr) { 01672 InheritableAttr *NewAttr = NULL; 01673 if (AvailabilityAttr *AA = dyn_cast<AvailabilityAttr>(Attr)) 01674 NewAttr = mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 01675 AA->getIntroduced(), AA->getDeprecated(), 01676 AA->getObsoleted(), AA->getUnavailable(), 01677 AA->getMessage()); 01678 else if (VisibilityAttr *VA = dyn_cast<VisibilityAttr>(Attr)) 01679 NewAttr = mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility()); 01680 else if (DLLImportAttr *ImportA = dyn_cast<DLLImportAttr>(Attr)) 01681 NewAttr = mergeDLLImportAttr(D, ImportA->getRange()); 01682 else if (DLLExportAttr *ExportA = dyn_cast<DLLExportAttr>(Attr)) 01683 NewAttr = mergeDLLExportAttr(D, ExportA->getRange()); 01684 else if (FormatAttr *FA = dyn_cast<FormatAttr>(Attr)) 01685 NewAttr = mergeFormatAttr(D, FA->getRange(), FA->getType(), 01686 FA->getFormatIdx(), FA->getFirstArg()); 01687 else if (SectionAttr *SA = dyn_cast<SectionAttr>(Attr)) 01688 NewAttr = mergeSectionAttr(D, SA->getRange(), SA->getName()); 01689 else if (!DeclHasAttr(D, Attr)) 01690 NewAttr = cast<InheritableAttr>(Attr->clone(Context)); 01691 01692 if (NewAttr) { 01693 NewAttr->setInherited(true); 01694 D->addAttr(NewAttr); 01695 return true; 01696 } 01697 01698 return false; 01699 } 01700 01701 static const Decl *getDefinition(Decl *D) { 01702 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 01703 return TD->getDefinition(); 01704 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 01705 return VD->getDefinition(); 01706 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 01707 const FunctionDecl* Def; 01708 if (FD->hasBody(Def)) 01709 return Def; 01710 } 01711 return NULL; 01712 } 01713 01714 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 01715 void Sema::mergeDeclAttributes(Decl *New, Decl *Old, 01716 bool MergeDeprecation) { 01717 // attributes declared post-definition are currently ignored 01718 const Decl *Def = getDefinition(Old); 01719 if (Def && Def != New && New->hasAttrs()) { 01720 Diag(New->getLocation(), diag::warn_attribute_precede_definition); 01721 Diag(Def->getLocation(), diag::note_previous_definition); 01722 New->dropAttrs(); 01723 } 01724 01725 if (!Old->hasAttrs()) 01726 return; 01727 01728 bool foundAny = New->hasAttrs(); 01729 01730 // Ensure that any moving of objects within the allocated map is done before 01731 // we process them. 01732 if (!foundAny) New->setAttrs(AttrVec()); 01733 01734 for (specific_attr_iterator<InheritableAttr> 01735 i = Old->specific_attr_begin<InheritableAttr>(), 01736 e = Old->specific_attr_end<InheritableAttr>(); 01737 i != e; ++i) { 01738 // Ignore deprecated/unavailable/availability attributes if requested. 01739 if (!MergeDeprecation && 01740 (isa<DeprecatedAttr>(*i) || 01741 isa<UnavailableAttr>(*i) || 01742 isa<AvailabilityAttr>(*i))) 01743 continue; 01744 01745 if (mergeDeclAttribute(New, *i)) 01746 foundAny = true; 01747 } 01748 01749 if (!foundAny) New->dropAttrs(); 01750 } 01751 01752 /// mergeParamDeclAttributes - Copy attributes from the old parameter 01753 /// to the new one. 01754 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 01755 const ParmVarDecl *oldDecl, 01756 ASTContext &C) { 01757 if (!oldDecl->hasAttrs()) 01758 return; 01759 01760 bool foundAny = newDecl->hasAttrs(); 01761 01762 // Ensure that any moving of objects within the allocated map is 01763 // done before we process them. 01764 if (!foundAny) newDecl->setAttrs(AttrVec()); 01765 01766 for (specific_attr_iterator<InheritableParamAttr> 01767 i = oldDecl->specific_attr_begin<InheritableParamAttr>(), 01768 e = oldDecl->specific_attr_end<InheritableParamAttr>(); i != e; ++i) { 01769 if (!DeclHasAttr(newDecl, *i)) { 01770 InheritableAttr *newAttr = cast<InheritableParamAttr>((*i)->clone(C)); 01771 newAttr->setInherited(true); 01772 newDecl->addAttr(newAttr); 01773 foundAny = true; 01774 } 01775 } 01776 01777 if (!foundAny) newDecl->dropAttrs(); 01778 } 01779 01780 namespace { 01781 01782 /// Used in MergeFunctionDecl to keep track of function parameters in 01783 /// C. 01784 struct GNUCompatibleParamWarning { 01785 ParmVarDecl *OldParm; 01786 ParmVarDecl *NewParm; 01787 QualType PromotedType; 01788 }; 01789 01790 } 01791 01792 /// getSpecialMember - get the special member enum for a method. 01793 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 01794 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 01795 if (Ctor->isDefaultConstructor()) 01796 return Sema::CXXDefaultConstructor; 01797 01798 if (Ctor->isCopyConstructor()) 01799 return Sema::CXXCopyConstructor; 01800 01801 if (Ctor->isMoveConstructor()) 01802 return Sema::CXXMoveConstructor; 01803 } else if (isa<CXXDestructorDecl>(MD)) { 01804 return Sema::CXXDestructor; 01805 } else if (MD->isCopyAssignmentOperator()) { 01806 return Sema::CXXCopyAssignment; 01807 } else if (MD->isMoveAssignmentOperator()) { 01808 return Sema::CXXMoveAssignment; 01809 } 01810 01811 return Sema::CXXInvalid; 01812 } 01813 01814 /// canRedefineFunction - checks if a function can be redefined. Currently, 01815 /// only extern inline functions can be redefined, and even then only in 01816 /// GNU89 mode. 01817 static bool canRedefineFunction(const FunctionDecl *FD, 01818 const LangOptions& LangOpts) { 01819 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 01820 !LangOpts.CPlusPlus && 01821 FD->isInlineSpecified() && 01822 FD->getStorageClass() == SC_Extern); 01823 } 01824 01825 /// MergeFunctionDecl - We just parsed a function 'New' from 01826 /// declarator D which has the same name and scope as a previous 01827 /// declaration 'Old'. Figure out how to resolve this situation, 01828 /// merging decls or emitting diagnostics as appropriate. 01829 /// 01830 /// In C++, New and Old must be declarations that are not 01831 /// overloaded. Use IsOverload to determine whether New and Old are 01832 /// overloaded, and to select the Old declaration that New should be 01833 /// merged with. 01834 /// 01835 /// Returns true if there was an error, false otherwise. 01836 bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, Scope *S) { 01837 // Verify the old decl was also a function. 01838 FunctionDecl *Old = 0; 01839 if (FunctionTemplateDecl *OldFunctionTemplate 01840 = dyn_cast<FunctionTemplateDecl>(OldD)) 01841 Old = OldFunctionTemplate->getTemplatedDecl(); 01842 else 01843 Old = dyn_cast<FunctionDecl>(OldD); 01844 if (!Old) { 01845 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 01846 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 01847 Diag(Shadow->getTargetDecl()->getLocation(), 01848 diag::note_using_decl_target); 01849 Diag(Shadow->getUsingDecl()->getLocation(), 01850 diag::note_using_decl) << 0; 01851 return true; 01852 } 01853 01854 Diag(New->getLocation(), diag::err_redefinition_different_kind) 01855 << New->getDeclName(); 01856 Diag(OldD->getLocation(), diag::note_previous_definition); 01857 return true; 01858 } 01859 01860 // Determine whether the previous declaration was a definition, 01861 // implicit declaration, or a declaration. 01862 diag::kind PrevDiag; 01863 if (Old->isThisDeclarationADefinition()) 01864 PrevDiag = diag::note_previous_definition; 01865 else if (Old->isImplicit()) 01866 PrevDiag = diag::note_previous_implicit_declaration; 01867 else 01868 PrevDiag = diag::note_previous_declaration; 01869 01870 QualType OldQType = Context.getCanonicalType(Old->getType()); 01871 QualType NewQType = Context.getCanonicalType(New->getType()); 01872 01873 // Don't complain about this if we're in GNU89 mode and the old function 01874 // is an extern inline function. 01875 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 01876 New->getStorageClass() == SC_Static && 01877 Old->getStorageClass() != SC_Static && 01878 !canRedefineFunction(Old, getLangOpts())) { 01879 if (getLangOpts().MicrosoftExt) { 01880 Diag(New->getLocation(), diag::warn_static_non_static) << New; 01881 Diag(Old->getLocation(), PrevDiag); 01882 } else { 01883 Diag(New->getLocation(), diag::err_static_non_static) << New; 01884 Diag(Old->getLocation(), PrevDiag); 01885 return true; 01886 } 01887 } 01888 01889 // If a function is first declared with a calling convention, but is 01890 // later declared or defined without one, the second decl assumes the 01891 // calling convention of the first. 01892 // 01893 // For the new decl, we have to look at the NON-canonical type to tell the 01894 // difference between a function that really doesn't have a calling 01895 // convention and one that is declared cdecl. That's because in 01896 // canonicalization (see ASTContext.cpp), cdecl is canonicalized away 01897 // because it is the default calling convention. 01898 // 01899 // Note also that we DO NOT return at this point, because we still have 01900 // other tests to run. 01901 const FunctionType *OldType = cast<FunctionType>(OldQType); 01902 const FunctionType *NewType = New->getType()->getAs<FunctionType>(); 01903 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 01904 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 01905 bool RequiresAdjustment = false; 01906 if (OldTypeInfo.getCC() != CC_Default && 01907 NewTypeInfo.getCC() == CC_Default) { 01908 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 01909 RequiresAdjustment = true; 01910 } else if (!Context.isSameCallConv(OldTypeInfo.getCC(), 01911 NewTypeInfo.getCC())) { 01912 // Calling conventions really aren't compatible, so complain. 01913 Diag(New->getLocation(), diag::err_cconv_change) 01914 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 01915 << (OldTypeInfo.getCC() == CC_Default) 01916 << (OldTypeInfo.getCC() == CC_Default ? "" : 01917 FunctionType::getNameForCallConv(OldTypeInfo.getCC())); 01918 Diag(Old->getLocation(), diag::note_previous_declaration); 01919 return true; 01920 } 01921 01922 // FIXME: diagnose the other way around? 01923 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 01924 NewTypeInfo = NewTypeInfo.withNoReturn(true); 01925 RequiresAdjustment = true; 01926 } 01927 01928 // Merge regparm attribute. 01929 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 01930 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 01931 if (NewTypeInfo.getHasRegParm()) { 01932 Diag(New->getLocation(), diag::err_regparm_mismatch) 01933 << NewType->getRegParmType() 01934 << OldType->getRegParmType(); 01935 Diag(Old->getLocation(), diag::note_previous_declaration); 01936 return true; 01937 } 01938 01939 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 01940 RequiresAdjustment = true; 01941 } 01942 01943 // Merge ns_returns_retained attribute. 01944 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 01945 if (NewTypeInfo.getProducesResult()) { 01946 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 01947 Diag(Old->getLocation(), diag::note_previous_declaration); 01948 return true; 01949 } 01950 01951 NewTypeInfo = NewTypeInfo.withProducesResult(true); 01952 RequiresAdjustment = true; 01953 } 01954 01955 if (RequiresAdjustment) { 01956 NewType = Context.adjustFunctionType(NewType, NewTypeInfo); 01957 New->setType(QualType(NewType, 0)); 01958 NewQType = Context.getCanonicalType(New->getType()); 01959 } 01960 01961 if (getLangOpts().CPlusPlus) { 01962 // (C++98 13.1p2): 01963 // Certain function declarations cannot be overloaded: 01964 // -- Function declarations that differ only in the return type 01965 // cannot be overloaded. 01966 QualType OldReturnType = OldType->getResultType(); 01967 QualType NewReturnType = cast<FunctionType>(NewQType)->getResultType(); 01968 QualType ResQT; 01969 if (OldReturnType != NewReturnType) { 01970 if (NewReturnType->isObjCObjectPointerType() 01971 && OldReturnType->isObjCObjectPointerType()) 01972 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 01973 if (ResQT.isNull()) { 01974 if (New->isCXXClassMember() && New->isOutOfLine()) 01975 Diag(New->getLocation(), 01976 diag::err_member_def_does_not_match_ret_type) << New; 01977 else 01978 Diag(New->getLocation(), diag::err_ovl_diff_return_type); 01979 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 01980 return true; 01981 } 01982 else 01983 NewQType = ResQT; 01984 } 01985 01986 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 01987 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 01988 if (OldMethod && NewMethod) { 01989 // Preserve triviality. 01990 NewMethod->setTrivial(OldMethod->isTrivial()); 01991 01992 // MSVC allows explicit template specialization at class scope: 01993 // 2 CXMethodDecls referring to the same function will be injected. 01994 // We don't want a redeclartion error. 01995 bool IsClassScopeExplicitSpecialization = 01996 OldMethod->isFunctionTemplateSpecialization() && 01997 NewMethod->isFunctionTemplateSpecialization(); 01998 bool isFriend = NewMethod->getFriendObjectKind(); 01999 02000 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 02001 !IsClassScopeExplicitSpecialization) { 02002 // -- Member function declarations with the same name and the 02003 // same parameter types cannot be overloaded if any of them 02004 // is a static member function declaration. 02005 if (OldMethod->isStatic() || NewMethod->isStatic()) { 02006 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 02007 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 02008 return true; 02009 } 02010 02011 // C++ [class.mem]p1: 02012 // [...] A member shall not be declared twice in the 02013 // member-specification, except that a nested class or member 02014 // class template can be declared and then later defined. 02015 unsigned NewDiag; 02016 if (isa<CXXConstructorDecl>(OldMethod)) 02017 NewDiag = diag::err_constructor_redeclared; 02018 else if (isa<CXXDestructorDecl>(NewMethod)) 02019 NewDiag = diag::err_destructor_redeclared; 02020 else if (isa<CXXConversionDecl>(NewMethod)) 02021 NewDiag = diag::err_conv_function_redeclared; 02022 else 02023 NewDiag = diag::err_member_redeclared; 02024 02025 Diag(New->getLocation(), NewDiag); 02026 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 02027 02028 // Complain if this is an explicit declaration of a special 02029 // member that was initially declared implicitly. 02030 // 02031 // As an exception, it's okay to befriend such methods in order 02032 // to permit the implicit constructor/destructor/operator calls. 02033 } else if (OldMethod->isImplicit()) { 02034 if (isFriend) { 02035 NewMethod->setImplicit(); 02036 } else { 02037 Diag(NewMethod->getLocation(), 02038 diag::err_definition_of_implicitly_declared_member) 02039 << New << getSpecialMember(OldMethod); 02040 return true; 02041 } 02042 } else if (OldMethod->isExplicitlyDefaulted()) { 02043 Diag(NewMethod->getLocation(), 02044 diag::err_definition_of_explicitly_defaulted_member) 02045 << getSpecialMember(OldMethod); 02046 return true; 02047 } 02048 } 02049 02050 // (C++98 8.3.5p3): 02051 // All declarations for a function shall agree exactly in both the 02052 // return type and the parameter-type-list. 02053 // We also want to respect all the extended bits except noreturn. 02054 02055 // noreturn should now match unless the old type info didn't have it. 02056 QualType OldQTypeForComparison = OldQType; 02057 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 02058 assert(OldQType == QualType(OldType, 0)); 02059 const FunctionType *OldTypeForComparison 02060 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 02061 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 02062 assert(OldQTypeForComparison.isCanonical()); 02063 } 02064 02065 if (OldQTypeForComparison == NewQType) 02066 return MergeCompatibleFunctionDecls(New, Old, S); 02067 02068 // Fall through for conflicting redeclarations and redefinitions. 02069 } 02070 02071 // C: Function types need to be compatible, not identical. This handles 02072 // duplicate function decls like "void f(int); void f(enum X);" properly. 02073 if (!getLangOpts().CPlusPlus && 02074 Context.typesAreCompatible(OldQType, NewQType)) { 02075 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 02076 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 02077 const FunctionProtoType *OldProto = 0; 02078 if (isa<FunctionNoProtoType>(NewFuncType) && 02079 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 02080 // The old declaration provided a function prototype, but the 02081 // new declaration does not. Merge in the prototype. 02082 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 02083 SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(), 02084 OldProto->arg_type_end()); 02085 NewQType = Context.getFunctionType(NewFuncType->getResultType(), 02086 ParamTypes.data(), ParamTypes.size(), 02087 OldProto->getExtProtoInfo()); 02088 New->setType(NewQType); 02089 New->setHasInheritedPrototype(); 02090 02091 // Synthesize a parameter for each argument type. 02092 SmallVector<ParmVarDecl*, 16> Params; 02093 for (FunctionProtoType::arg_type_iterator 02094 ParamType = OldProto->arg_type_begin(), 02095 ParamEnd = OldProto->arg_type_end(); 02096 ParamType != ParamEnd; ++ParamType) { 02097 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, 02098 SourceLocation(), 02099 SourceLocation(), 0, 02100 *ParamType, /*TInfo=*/0, 02101 SC_None, SC_None, 02102 0); 02103 Param->setScopeInfo(0, Params.size()); 02104 Param->setImplicit(); 02105 Params.push_back(Param); 02106 } 02107 02108 New->setParams(Params); 02109 } 02110 02111 return MergeCompatibleFunctionDecls(New, Old, S); 02112 } 02113 02114 // GNU C permits a K&R definition to follow a prototype declaration 02115 // if the declared types of the parameters in the K&R definition 02116 // match the types in the prototype declaration, even when the 02117 // promoted types of the parameters from the K&R definition differ 02118 // from the types in the prototype. GCC then keeps the types from 02119 // the prototype. 02120 // 02121 // If a variadic prototype is followed by a non-variadic K&R definition, 02122 // the K&R definition becomes variadic. This is sort of an edge case, but 02123 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 02124 // C99 6.9.1p8. 02125 if (!getLangOpts().CPlusPlus && 02126 Old->hasPrototype() && !New->hasPrototype() && 02127 New->getType()->getAs<FunctionProtoType>() && 02128 Old->getNumParams() == New->getNumParams()) { 02129 SmallVector<QualType, 16> ArgTypes; 02130 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 02131 const FunctionProtoType *OldProto 02132 = Old->getType()->getAs<FunctionProtoType>(); 02133 const FunctionProtoType *NewProto 02134 = New->getType()->getAs<FunctionProtoType>(); 02135 02136 // Determine whether this is the GNU C extension. 02137 QualType MergedReturn = Context.mergeTypes(OldProto->getResultType(), 02138 NewProto->getResultType()); 02139 bool LooseCompatible = !MergedReturn.isNull(); 02140 for (unsigned Idx = 0, End = Old->getNumParams(); 02141 LooseCompatible && Idx != End; ++Idx) { 02142 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 02143 ParmVarDecl *NewParm = New->getParamDecl(Idx); 02144 if (Context.typesAreCompatible(OldParm->getType(), 02145 NewProto->getArgType(Idx))) { 02146 ArgTypes.push_back(NewParm->getType()); 02147 } else if (Context.typesAreCompatible(OldParm->getType(), 02148 NewParm->getType(), 02149 /*CompareUnqualified=*/true)) { 02150 GNUCompatibleParamWarning Warn 02151 = { OldParm, NewParm, NewProto->getArgType(Idx) }; 02152 Warnings.push_back(Warn); 02153 ArgTypes.push_back(NewParm->getType()); 02154 } else 02155 LooseCompatible = false; 02156 } 02157 02158 if (LooseCompatible) { 02159 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 02160 Diag(Warnings[Warn].NewParm->getLocation(), 02161 diag::ext_param_promoted_not_compatible_with_prototype) 02162 << Warnings[Warn].PromotedType 02163 << Warnings[Warn].OldParm->getType(); 02164 if (Warnings[Warn].OldParm->getLocation().isValid()) 02165 Diag(Warnings[Warn].OldParm->getLocation(), 02166 diag::note_previous_declaration); 02167 } 02168 02169 New->setType(Context.getFunctionType(MergedReturn, &ArgTypes[0], 02170 ArgTypes.size(), 02171 OldProto->getExtProtoInfo())); 02172 return MergeCompatibleFunctionDecls(New, Old, S); 02173 } 02174 02175 // Fall through to diagnose conflicting types. 02176 } 02177 02178 // A function that has already been declared has been redeclared or defined 02179 // with a different type- show appropriate diagnostic 02180 if (unsigned BuiltinID = Old->getBuiltinID()) { 02181 // The user has declared a builtin function with an incompatible 02182 // signature. 02183 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 02184 // The function the user is redeclaring is a library-defined 02185 // function like 'malloc' or 'printf'. Warn about the 02186 // redeclaration, then pretend that we don't know about this 02187 // library built-in. 02188 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 02189 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 02190 << Old << Old->getType(); 02191 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 02192 Old->setInvalidDecl(); 02193 return false; 02194 } 02195 02196 PrevDiag = diag::note_previous_builtin_declaration; 02197 } 02198 02199 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 02200 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType(); 02201 return true; 02202 } 02203 02204 /// \brief Completes the merge of two function declarations that are 02205 /// known to be compatible. 02206 /// 02207 /// This routine handles the merging of attributes and other 02208 /// properties of function declarations form the old declaration to 02209 /// the new declaration, once we know that New is in fact a 02210 /// redeclaration of Old. 02211 /// 02212 /// \returns false 02213 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 02214 Scope *S) { 02215 // Merge the attributes 02216 mergeDeclAttributes(New, Old); 02217 02218 // Merge the storage class. 02219 if (Old->getStorageClass() != SC_Extern && 02220 Old->getStorageClass() != SC_None) 02221 New->setStorageClass(Old->getStorageClass()); 02222 02223 // Merge "pure" flag. 02224 if (Old->isPure()) 02225 New->setPure(); 02226 02227 // Merge attributes from the parameters. These can mismatch with K&R 02228 // declarations. 02229 if (New->getNumParams() == Old->getNumParams()) 02230 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 02231 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 02232 Context); 02233 02234 if (getLangOpts().CPlusPlus) 02235 return MergeCXXFunctionDecl(New, Old, S); 02236 02237 return false; 02238 } 02239 02240 02241 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 02242 ObjCMethodDecl *oldMethod) { 02243 // We don't want to merge unavailable and deprecated attributes 02244 // except from interface to implementation. 02245 bool mergeDeprecation = isa<ObjCImplDecl>(newMethod->getDeclContext()); 02246 02247 // Merge the attributes. 02248 mergeDeclAttributes(newMethod, oldMethod, mergeDeprecation); 02249 02250 // Merge attributes from the parameters. 02251 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 02252 oe = oldMethod->param_end(); 02253 for (ObjCMethodDecl::param_iterator 02254 ni = newMethod->param_begin(), ne = newMethod->param_end(); 02255 ni != ne && oi != oe; ++ni, ++oi) 02256 mergeParamDeclAttributes(*ni, *oi, Context); 02257 02258 CheckObjCMethodOverride(newMethod, oldMethod, true); 02259 } 02260 02261 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 02262 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 02263 /// emitting diagnostics as appropriate. 02264 /// 02265 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 02266 /// to here in AddInitializerToDecl. We can't check them before the initializer 02267 /// is attached. 02268 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old) { 02269 if (New->isInvalidDecl() || Old->isInvalidDecl()) 02270 return; 02271 02272 QualType MergedT; 02273 if (getLangOpts().CPlusPlus) { 02274 AutoType *AT = New->getType()->getContainedAutoType(); 02275 if (AT && !AT->isDeduced()) { 02276 // We don't know what the new type is until the initializer is attached. 02277 return; 02278 } else if (Context.hasSameType(New->getType(), Old->getType())) { 02279 // These could still be something that needs exception specs checked. 02280 return MergeVarDeclExceptionSpecs(New, Old); 02281 } 02282 // C++ [basic.link]p10: 02283 // [...] the types specified by all declarations referring to a given 02284 // object or function shall be identical, except that declarations for an 02285 // array object can specify array types that differ by the presence or 02286 // absence of a major array bound (8.3.4). 02287 else if (Old->getType()->isIncompleteArrayType() && 02288 New->getType()->isArrayType()) { 02289 CanQual<ArrayType> OldArray 02290 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 02291 CanQual<ArrayType> NewArray 02292 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 02293 if (OldArray->getElementType() == NewArray->getElementType()) 02294 MergedT = New->getType(); 02295 } else if (Old->getType()->isArrayType() && 02296 New->getType()->isIncompleteArrayType()) { 02297 CanQual<ArrayType> OldArray 02298 = Context.getCanonicalType(Old->getType())->getAs<ArrayType>(); 02299 CanQual<ArrayType> NewArray 02300 = Context.getCanonicalType(New->getType())->getAs<ArrayType>(); 02301 if (OldArray->getElementType() == NewArray->getElementType()) 02302 MergedT = Old->getType(); 02303 } else if (New->getType()->isObjCObjectPointerType() 02304 && Old->getType()->isObjCObjectPointerType()) { 02305 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 02306 Old->getType()); 02307 } 02308 } else { 02309 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 02310 } 02311 if (MergedT.isNull()) { 02312 Diag(New->getLocation(), diag::err_redefinition_different_type) 02313 << New->getDeclName(); 02314 Diag(Old->getLocation(), diag::note_previous_definition); 02315 return New->setInvalidDecl(); 02316 } 02317 New->setType(MergedT); 02318 } 02319 02320 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 02321 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 02322 /// situation, merging decls or emitting diagnostics as appropriate. 02323 /// 02324 /// Tentative definition rules (C99 6.9.2p2) are checked by 02325 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 02326 /// definitions here, since the initializer hasn't been attached. 02327 /// 02328 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 02329 // If the new decl is already invalid, don't do any other checking. 02330 if (New->isInvalidDecl()) 02331 return; 02332 02333 // Verify the old decl was also a variable. 02334 VarDecl *Old = 0; 02335 if (!Previous.isSingleResult() || 02336 !(Old = dyn_cast<VarDecl>(Previous.getFoundDecl()))) { 02337 Diag(New->getLocation(), diag::err_redefinition_different_kind) 02338 << New->getDeclName(); 02339 Diag(Previous.getRepresentativeDecl()->getLocation(), 02340 diag::note_previous_definition); 02341 return New->setInvalidDecl(); 02342 } 02343 02344 // C++ [class.mem]p1: 02345 // A member shall not be declared twice in the member-specification [...] 02346 // 02347 // Here, we need only consider static data members. 02348 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 02349 Diag(New->getLocation(), diag::err_duplicate_member) 02350 << New->getIdentifier(); 02351 Diag(Old->getLocation(), diag::note_previous_declaration); 02352 New->setInvalidDecl(); 02353 } 02354 02355 mergeDeclAttributes(New, Old); 02356 // Warn if an already-declared variable is made a weak_import in a subsequent 02357 // declaration 02358 if (New->getAttr<WeakImportAttr>() && 02359 Old->getStorageClass() == SC_None && 02360 !Old->getAttr<WeakImportAttr>()) { 02361 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 02362 Diag(Old->getLocation(), diag::note_previous_definition); 02363 // Remove weak_import attribute on new declaration. 02364 New->dropAttr<WeakImportAttr>(); 02365 } 02366 02367 // Merge the types. 02368 MergeVarDeclTypes(New, Old); 02369 if (New->isInvalidDecl()) 02370 return; 02371 02372 // C99 6.2.2p4: Check if we have a static decl followed by a non-static. 02373 if (New->getStorageClass() == SC_Static && 02374 (Old->getStorageClass() == SC_None || Old->hasExternalStorage())) { 02375 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName(); 02376 Diag(Old->getLocation(), diag::note_previous_definition); 02377 return New->setInvalidDecl(); 02378 } 02379 // C99 6.2.2p4: 02380 // For an identifier declared with the storage-class specifier 02381 // extern in a scope in which a prior declaration of that 02382 // identifier is visible,23) if the prior declaration specifies 02383 // internal or external linkage, the linkage of the identifier at 02384 // the later declaration is the same as the linkage specified at 02385 // the prior declaration. If no prior declaration is visible, or 02386 // if the prior declaration specifies no linkage, then the 02387 // identifier has external linkage. 02388 if (New->hasExternalStorage() && Old->hasLinkage()) 02389 /* Okay */; 02390 else if (New->getStorageClass() != SC_Static && 02391 Old->getStorageClass() == SC_Static) { 02392 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 02393 Diag(Old->getLocation(), diag::note_previous_definition); 02394 return New->setInvalidDecl(); 02395 } 02396 02397 // Check if extern is followed by non-extern and vice-versa. 02398 if (New->hasExternalStorage() && 02399 !Old->hasLinkage() && Old->isLocalVarDecl()) { 02400 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 02401 Diag(Old->getLocation(), diag::note_previous_definition); 02402 return New->setInvalidDecl(); 02403 } 02404 if (Old->hasExternalStorage() && 02405 !New->hasLinkage() && New->isLocalVarDecl()) { 02406 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 02407 Diag(Old->getLocation(), diag::note_previous_definition); 02408 return New->setInvalidDecl(); 02409 } 02410 02411 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 02412 02413 // FIXME: The test for external storage here seems wrong? We still 02414 // need to check for mismatches. 02415 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 02416 // Don't complain about out-of-line definitions of static members. 02417 !(Old->getLexicalDeclContext()->isRecord() && 02418 !New->getLexicalDeclContext()->isRecord())) { 02419 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 02420 Diag(Old->getLocation(), diag::note_previous_definition); 02421 return New->setInvalidDecl(); 02422 } 02423 02424 if (New->isThreadSpecified() && !Old->isThreadSpecified()) { 02425 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 02426 Diag(Old->getLocation(), diag::note_previous_definition); 02427 } else if (!New->isThreadSpecified() && Old->isThreadSpecified()) { 02428 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 02429 Diag(Old->getLocation(), diag::note_previous_definition); 02430 } 02431 02432 // C++ doesn't have tentative definitions, so go right ahead and check here. 02433 const VarDecl *Def; 02434 if (getLangOpts().CPlusPlus && 02435 New->isThisDeclarationADefinition() == VarDecl::Definition && 02436 (Def = Old->getDefinition())) { 02437 Diag(New->getLocation(), diag::err_redefinition) 02438 << New->getDeclName(); 02439 Diag(Def->getLocation(), diag::note_previous_definition); 02440 New->setInvalidDecl(); 02441 return; 02442 } 02443 // c99 6.2.2 P4. 02444 // For an identifier declared with the storage-class specifier extern in a 02445 // scope in which a prior declaration of that identifier is visible, if 02446 // the prior declaration specifies internal or external linkage, the linkage 02447 // of the identifier at the later declaration is the same as the linkage 02448 // specified at the prior declaration. 02449 // FIXME. revisit this code. 02450 if (New->hasExternalStorage() && 02451 Old->getLinkage() == InternalLinkage && 02452 New->getDeclContext() == Old->getDeclContext()) 02453 New->setStorageClass(Old->getStorageClass()); 02454 02455 // Keep a chain of previous declarations. 02456 New->setPreviousDeclaration(Old); 02457 02458 // Inherit access appropriately. 02459 New->setAccess(Old->getAccess()); 02460 } 02461 02462 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 02463 /// no declarator (e.g. "struct foo;") is parsed. 02464 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 02465 DeclSpec &DS) { 02466 return ParsedFreeStandingDeclSpec(S, AS, DS, 02467 MultiTemplateParamsArg(*this, 0, 0)); 02468 } 02469 02470 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 02471 /// no declarator (e.g. "struct foo;") is parsed. It also accopts template 02472 /// parameters to cope with template friend declarations. 02473 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 02474 DeclSpec &DS, 02475 MultiTemplateParamsArg TemplateParams) { 02476 Decl *TagD = 0; 02477 TagDecl *Tag = 0; 02478 if (DS.getTypeSpecType() == DeclSpec::TST_class || 02479 DS.getTypeSpecType() == DeclSpec::TST_struct || 02480 DS.getTypeSpecType() == DeclSpec::TST_union || 02481 DS.getTypeSpecType() == DeclSpec::TST_enum) { 02482 TagD = DS.getRepAsDecl(); 02483 02484 if (!TagD) // We probably had an error 02485 return 0; 02486 02487 // Note that the above type specs guarantee that the 02488 // type rep is a Decl, whereas in many of the others 02489 // it's a Type. 02490 if (isa<TagDecl>(TagD)) 02491 Tag = cast<TagDecl>(TagD); 02492 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 02493 Tag = CTD->getTemplatedDecl(); 02494 } 02495 02496 if (Tag) { 02497 Tag->setFreeStanding(); 02498 if (Tag->isInvalidDecl()) 02499 return Tag; 02500 } 02501 02502 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 02503 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 02504 // or incomplete types shall not be restrict-qualified." 02505 if (TypeQuals & DeclSpec::TQ_restrict) 02506 Diag(DS.getRestrictSpecLoc(), 02507 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 02508 << DS.getSourceRange(); 02509 } 02510 02511 if (DS.isConstexprSpecified()) { 02512 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 02513 // and definitions of functions and variables. 02514 if (Tag) 02515 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 02516 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 02517 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 02518 DS.getTypeSpecType() == DeclSpec::TST_union ? 2 : 3); 02519 else 02520 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 02521 // Don't emit warnings after this error. 02522 return TagD; 02523 } 02524 02525 if (DS.isFriendSpecified()) { 02526 // If we're dealing with a decl but not a TagDecl, assume that 02527 // whatever routines created it handled the friendship aspect. 02528 if (TagD && !Tag) 02529 return 0; 02530 return ActOnFriendTypeDecl(S, DS, TemplateParams); 02531 } 02532 02533 // Track whether we warned about the fact that there aren't any 02534 // declarators. 02535 bool emittedWarning = false; 02536 02537 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 02538 if (!Record->getDeclName() && Record->isCompleteDefinition() && 02539 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 02540 if (getLangOpts().CPlusPlus || 02541 Record->getDeclContext()->isRecord()) 02542 return BuildAnonymousStructOrUnion(S, DS, AS, Record); 02543 02544 Diag(DS.getLocStart(), diag::ext_no_declarators) 02545 << DS.getSourceRange(); 02546 emittedWarning = true; 02547 } 02548 } 02549 02550 // Check for Microsoft C extension: anonymous struct. 02551 if (getLangOpts().MicrosoftExt && !getLangOpts().CPlusPlus && 02552 CurContext->isRecord() && 02553 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 02554 // Handle 2 kinds of anonymous struct: 02555 // struct STRUCT; 02556 // and 02557 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 02558 RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag); 02559 if ((Record && Record->getDeclName() && !Record->isCompleteDefinition()) || 02560 (DS.getTypeSpecType() == DeclSpec::TST_typename && 02561 DS.getRepAsType().get()->isStructureType())) { 02562 Diag(DS.getLocStart(), diag::ext_ms_anonymous_struct) 02563 << DS.getSourceRange(); 02564 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 02565 } 02566 } 02567 02568 if (getLangOpts().CPlusPlus && 02569 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 02570 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 02571 if (Enum->enumerator_begin() == Enum->enumerator_end() && 02572 !Enum->getIdentifier() && !Enum->isInvalidDecl()) { 02573 Diag(Enum->getLocation(), diag::ext_no_declarators) 02574 << DS.getSourceRange(); 02575 emittedWarning = true; 02576 } 02577 02578 // Skip all the checks below if we have a type error. 02579 if (DS.getTypeSpecType() == DeclSpec::TST_error) return TagD; 02580 02581 if (!DS.isMissingDeclaratorOk()) { 02582 // Warn about typedefs of enums without names, since this is an 02583 // extension in both Microsoft and GNU. 02584 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef && 02585 Tag && isa<EnumDecl>(Tag)) { 02586 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 02587 << DS.getSourceRange(); 02588 return Tag; 02589 } 02590 02591 Diag(DS.getLocStart(), diag::ext_no_declarators) 02592 << DS.getSourceRange(); 02593 emittedWarning = true; 02594 } 02595 02596 // We're going to complain about a bunch of spurious specifiers; 02597 // only do this if we're declaring a tag, because otherwise we 02598 // should be getting diag::ext_no_declarators. 02599 if (emittedWarning || (TagD && TagD->isInvalidDecl())) 02600 return TagD; 02601 02602 // Note that a linkage-specification sets a storage class, but 02603 // 'extern "C" struct foo;' is actually valid and not theoretically 02604 // useless. 02605 if (DeclSpec::SCS scs = DS.getStorageClassSpec()) 02606 if (!DS.isExternInLinkageSpec()) 02607 Diag(DS.getStorageClassSpecLoc(), diag::warn_standalone_specifier) 02608 << DeclSpec::getSpecifierName(scs); 02609 02610 if (DS.isThreadSpecified()) 02611 Diag(DS.getThreadSpecLoc(), diag::warn_standalone_specifier) << "__thread"; 02612 if (DS.getTypeQualifiers()) { 02613 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 02614 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "const"; 02615 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 02616 Diag(DS.getConstSpecLoc(), diag::warn_standalone_specifier) << "volatile"; 02617 // Restrict is covered above. 02618 } 02619 if (DS.isInlineSpecified()) 02620 Diag(DS.getInlineSpecLoc(), diag::warn_standalone_specifier) << "inline"; 02621 if (DS.isVirtualSpecified()) 02622 Diag(DS.getVirtualSpecLoc(), diag::warn_standalone_specifier) << "virtual"; 02623 if (DS.isExplicitSpecified()) 02624 Diag(DS.getExplicitSpecLoc(), diag::warn_standalone_specifier) <<"explicit"; 02625 02626 if (DS.isModulePrivateSpecified() && 02627 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 02628 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 02629 << Tag->getTagKind() 02630 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 02631 02632 // Warn about ignored type attributes, for example: 02633 // __attribute__((aligned)) struct A; 02634 // Attributes should be placed after tag to apply to type declaration. 02635 if (!DS.getAttributes().empty()) { 02636 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 02637 if (TypeSpecType == DeclSpec::TST_class || 02638 TypeSpecType == DeclSpec::TST_struct || 02639 TypeSpecType == DeclSpec::TST_union || 02640 TypeSpecType == DeclSpec::TST_enum) { 02641 AttributeList* attrs = DS.getAttributes().getList(); 02642 while (attrs) { 02643 Diag(attrs->getScopeLoc(), 02644 diag::warn_declspec_attribute_ignored) 02645 << attrs->getName() 02646 << (TypeSpecType == DeclSpec::TST_class ? 0 : 02647 TypeSpecType == DeclSpec::TST_struct ? 1 : 02648 TypeSpecType == DeclSpec::TST_union ? 2 : 3); 02649 attrs = attrs->getNext(); 02650 } 02651 } 02652 } 02653 02654 return TagD; 02655 } 02656 02657 /// We are trying to inject an anonymous member into the given scope; 02658 /// check if there's an existing declaration that can't be overloaded. 02659 /// 02660 /// \return true if this is a forbidden redeclaration 02661 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 02662 Scope *S, 02663 DeclContext *Owner, 02664 DeclarationName Name, 02665 SourceLocation NameLoc, 02666 unsigned diagnostic) { 02667 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 02668 Sema::ForRedeclaration); 02669 if (!SemaRef.LookupName(R, S)) return false; 02670 02671 if (R.getAsSingle<TagDecl>()) 02672 return false; 02673 02674 // Pick a representative declaration. 02675 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 02676 assert(PrevDecl && "Expected a non-null Decl"); 02677 02678 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 02679 return false; 02680 02681 SemaRef.Diag(NameLoc, diagnostic) << Name; 02682 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 02683 02684 return true; 02685 } 02686 02687 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 02688 /// anonymous struct or union AnonRecord into the owning context Owner 02689 /// and scope S. This routine will be invoked just after we realize 02690 /// that an unnamed union or struct is actually an anonymous union or 02691 /// struct, e.g., 02692 /// 02693 /// @code 02694 /// union { 02695 /// int i; 02696 /// float f; 02697 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 02698 /// // f into the surrounding scope.x 02699 /// @endcode 02700 /// 02701 /// This routine is recursive, injecting the names of nested anonymous 02702 /// structs/unions into the owning context and scope as well. 02703 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 02704 DeclContext *Owner, 02705 RecordDecl *AnonRecord, 02706 AccessSpecifier AS, 02707 SmallVector<NamedDecl*, 2> &Chaining, 02708 bool MSAnonStruct) { 02709 unsigned diagKind 02710 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 02711 : diag::err_anonymous_struct_member_redecl; 02712 02713 bool Invalid = false; 02714 02715 // Look every FieldDecl and IndirectFieldDecl with a name. 02716 for (RecordDecl::decl_iterator D = AnonRecord->decls_begin(), 02717 DEnd = AnonRecord->decls_end(); 02718 D != DEnd; ++D) { 02719 if ((isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) && 02720 cast<NamedDecl>(*D)->getDeclName()) { 02721 ValueDecl *VD = cast<ValueDecl>(*D); 02722 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 02723 VD->getLocation(), diagKind)) { 02724 // C++ [class.union]p2: 02725 // The names of the members of an anonymous union shall be 02726 // distinct from the names of any other entity in the 02727 // scope in which the anonymous union is declared. 02728 Invalid = true; 02729 } else { 02730 // C++ [class.union]p2: 02731 // For the purpose of name lookup, after the anonymous union 02732 // definition, the members of the anonymous union are 02733 // considered to have been defined in the scope in which the 02734 // anonymous union is declared. 02735 unsigned OldChainingSize = Chaining.size(); 02736 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 02737 for (IndirectFieldDecl::chain_iterator PI = IF->chain_begin(), 02738 PE = IF->chain_end(); PI != PE; ++PI) 02739 Chaining.push_back(*PI); 02740 else 02741 Chaining.push_back(VD); 02742 02743 assert(Chaining.size() >= 2); 02744 NamedDecl **NamedChain = 02745 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 02746 for (unsigned i = 0; i < Chaining.size(); i++) 02747 NamedChain[i] = Chaining[i]; 02748 02749 IndirectFieldDecl* IndirectField = 02750 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 02751 VD->getIdentifier(), VD->getType(), 02752 NamedChain, Chaining.size()); 02753 02754 IndirectField->setAccess(AS); 02755 IndirectField->setImplicit(); 02756 SemaRef.PushOnScopeChains(IndirectField, S); 02757 02758 // That includes picking up the appropriate access specifier. 02759 if (AS != AS_none) IndirectField->setAccess(AS); 02760 02761 Chaining.resize(OldChainingSize); 02762 } 02763 } 02764 } 02765 02766 return Invalid; 02767 } 02768 02769 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 02770 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 02771 /// illegal input values are mapped to SC_None. 02772 static StorageClass 02773 StorageClassSpecToVarDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 02774 switch (StorageClassSpec) { 02775 case DeclSpec::SCS_unspecified: return SC_None; 02776 case DeclSpec::SCS_extern: return SC_Extern; 02777 case DeclSpec::SCS_static: return SC_Static; 02778 case DeclSpec::SCS_auto: return SC_Auto; 02779 case DeclSpec::SCS_register: return SC_Register; 02780 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 02781 // Illegal SCSs map to None: error reporting is up to the caller. 02782 case DeclSpec::SCS_mutable: // Fall through. 02783 case DeclSpec::SCS_typedef: return SC_None; 02784 } 02785 llvm_unreachable("unknown storage class specifier"); 02786 } 02787 02788 /// StorageClassSpecToFunctionDeclStorageClass - Maps a DeclSpec::SCS to 02789 /// a StorageClass. Any error reporting is up to the caller: 02790 /// illegal input values are mapped to SC_None. 02791 static StorageClass 02792 StorageClassSpecToFunctionDeclStorageClass(DeclSpec::SCS StorageClassSpec) { 02793 switch (StorageClassSpec) { 02794 case DeclSpec::SCS_unspecified: return SC_None; 02795 case DeclSpec::SCS_extern: return SC_Extern; 02796 case DeclSpec::SCS_static: return SC_Static; 02797 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 02798 // Illegal SCSs map to None: error reporting is up to the caller. 02799 case DeclSpec::SCS_auto: // Fall through. 02800 case DeclSpec::SCS_mutable: // Fall through. 02801 case DeclSpec::SCS_register: // Fall through. 02802 case DeclSpec::SCS_typedef: return SC_None; 02803 } 02804 llvm_unreachable("unknown storage class specifier"); 02805 } 02806 02807 /// BuildAnonymousStructOrUnion - Handle the declaration of an 02808 /// anonymous structure or union. Anonymous unions are a C++ feature 02809 /// (C++ [class.union]) and a C11 feature; anonymous structures 02810 /// are a C11 feature and GNU C++ extension. 02811 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 02812 AccessSpecifier AS, 02813 RecordDecl *Record) { 02814 DeclContext *Owner = Record->getDeclContext(); 02815 02816 // Diagnose whether this anonymous struct/union is an extension. 02817 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 02818 Diag(Record->getLocation(), diag::ext_anonymous_union); 02819 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 02820 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 02821 else if (!Record->isUnion() && !getLangOpts().C11) 02822 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 02823 02824 // C and C++ require different kinds of checks for anonymous 02825 // structs/unions. 02826 bool Invalid = false; 02827 if (getLangOpts().CPlusPlus) { 02828 const char* PrevSpec = 0; 02829 unsigned DiagID; 02830 if (Record->isUnion()) { 02831 // C++ [class.union]p6: 02832 // Anonymous unions declared in a named namespace or in the 02833 // global namespace shall be declared static. 02834 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 02835 (isa<TranslationUnitDecl>(Owner) || 02836 (isa<NamespaceDecl>(Owner) && 02837 cast<NamespaceDecl>(Owner)->getDeclName()))) { 02838 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 02839 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 02840 02841 // Recover by adding 'static'. 02842 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 02843 PrevSpec, DiagID); 02844 } 02845 // C++ [class.union]p6: 02846 // A storage class is not allowed in a declaration of an 02847 // anonymous union in a class scope. 02848 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 02849 isa<RecordDecl>(Owner)) { 02850 Diag(DS.getStorageClassSpecLoc(), 02851 diag::err_anonymous_union_with_storage_spec) 02852 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 02853 02854 // Recover by removing the storage specifier. 02855 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 02856 SourceLocation(), 02857 PrevSpec, DiagID); 02858 } 02859 } 02860 02861 // Ignore const/volatile/restrict qualifiers. 02862 if (DS.getTypeQualifiers()) { 02863 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 02864 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 02865 << Record->isUnion() << 0 02866 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 02867 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 02868 Diag(DS.getVolatileSpecLoc(), 02869 diag::ext_anonymous_struct_union_qualified) 02870 << Record->isUnion() << 1 02871 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 02872 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 02873 Diag(DS.getRestrictSpecLoc(), 02874 diag::ext_anonymous_struct_union_qualified) 02875 << Record->isUnion() << 2 02876 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 02877 02878 DS.ClearTypeQualifiers(); 02879 } 02880 02881 // C++ [class.union]p2: 02882 // The member-specification of an anonymous union shall only 02883 // define non-static data members. [Note: nested types and 02884 // functions cannot be declared within an anonymous union. ] 02885 for (DeclContext::decl_iterator Mem = Record->decls_begin(), 02886 MemEnd = Record->decls_end(); 02887 Mem != MemEnd; ++Mem) { 02888 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) { 02889 // C++ [class.union]p3: 02890 // An anonymous union shall not have private or protected 02891 // members (clause 11). 02892 assert(FD->getAccess() != AS_none); 02893 if (FD->getAccess() != AS_public) { 02894 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 02895 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 02896 Invalid = true; 02897 } 02898 02899 // C++ [class.union]p1 02900 // An object of a class with a non-trivial constructor, a non-trivial 02901 // copy constructor, a non-trivial destructor, or a non-trivial copy 02902 // assignment operator cannot be a member of a union, nor can an 02903 // array of such objects. 02904 if (CheckNontrivialField(FD)) 02905 Invalid = true; 02906 } else if ((*Mem)->isImplicit()) { 02907 // Any implicit members are fine. 02908 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) { 02909 // This is a type that showed up in an 02910 // elaborated-type-specifier inside the anonymous struct or 02911 // union, but which actually declares a type outside of the 02912 // anonymous struct or union. It's okay. 02913 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) { 02914 if (!MemRecord->isAnonymousStructOrUnion() && 02915 MemRecord->getDeclName()) { 02916 // Visual C++ allows type definition in anonymous struct or union. 02917 if (getLangOpts().MicrosoftExt) 02918 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 02919 << (int)Record->isUnion(); 02920 else { 02921 // This is a nested type declaration. 02922 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 02923 << (int)Record->isUnion(); 02924 Invalid = true; 02925 } 02926 } 02927 } else if (isa<AccessSpecDecl>(*Mem)) { 02928 // Any access specifier is fine. 02929 } else { 02930 // We have something that isn't a non-static data 02931 // member. Complain about it. 02932 unsigned DK = diag::err_anonymous_record_bad_member; 02933 if (isa<TypeDecl>(*Mem)) 02934 DK = diag::err_anonymous_record_with_type; 02935 else if (isa<FunctionDecl>(*Mem)) 02936 DK = diag::err_anonymous_record_with_function; 02937 else if (isa<VarDecl>(*Mem)) 02938 DK = diag::err_anonymous_record_with_static; 02939 02940 // Visual C++ allows type definition in anonymous struct or union. 02941 if (getLangOpts().MicrosoftExt && 02942 DK == diag::err_anonymous_record_with_type) 02943 Diag((*Mem)->getLocation(), diag::ext_anonymous_record_with_type) 02944 << (int)Record->isUnion(); 02945 else { 02946 Diag((*Mem)->getLocation(), DK) 02947 << (int)Record->isUnion(); 02948 Invalid = true; 02949 } 02950 } 02951 } 02952 } 02953 02954 if (!Record->isUnion() && !Owner->isRecord()) { 02955 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 02956 << (int)getLangOpts().CPlusPlus; 02957 Invalid = true; 02958 } 02959 02960 // Mock up a declarator. 02961 Declarator Dc(DS, Declarator::MemberContext); 02962 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 02963 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 02964 02965 // Create a declaration for this anonymous struct/union. 02966 NamedDecl *Anon = 0; 02967 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 02968 Anon = FieldDecl::Create(Context, OwningClass, 02969 DS.getLocStart(), 02970 Record->getLocation(), 02971 /*IdentifierInfo=*/0, 02972 Context.getTypeDeclType(Record), 02973 TInfo, 02974 /*BitWidth=*/0, /*Mutable=*/false, 02975 /*HasInit=*/false); 02976 Anon->setAccess(AS); 02977 if (getLangOpts().CPlusPlus) 02978 FieldCollector->Add(cast<FieldDecl>(Anon)); 02979 } else { 02980 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 02981 assert(SCSpec != DeclSpec::SCS_typedef && 02982 "Parser allowed 'typedef' as storage class VarDecl."); 02983 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 02984 if (SCSpec == DeclSpec::SCS_mutable) { 02985 // mutable can only appear on non-static class members, so it's always 02986 // an error here 02987 Diag(Record->getLocation(), diag::err_mutable_nonmember); 02988 Invalid = true; 02989 SC = SC_None; 02990 } 02991 SCSpec = DS.getStorageClassSpecAsWritten(); 02992 VarDecl::StorageClass SCAsWritten 02993 = StorageClassSpecToVarDeclStorageClass(SCSpec); 02994 02995 Anon = VarDecl::Create(Context, Owner, 02996 DS.getLocStart(), 02997 Record->getLocation(), /*IdentifierInfo=*/0, 02998 Context.getTypeDeclType(Record), 02999 TInfo, SC, SCAsWritten); 03000 03001 // Default-initialize the implicit variable. This initialization will be 03002 // trivial in almost all cases, except if a union member has an in-class 03003 // initializer: 03004 // union { int n = 0; }; 03005 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 03006 } 03007 Anon->setImplicit(); 03008 03009 // Add the anonymous struct/union object to the current 03010 // context. We'll be referencing this object when we refer to one of 03011 // its members. 03012 Owner->addDecl(Anon); 03013 03014 // Inject the members of the anonymous struct/union into the owning 03015 // context and into the identifier resolver chain for name lookup 03016 // purposes. 03017 SmallVector<NamedDecl*, 2> Chain; 03018 Chain.push_back(Anon); 03019 03020 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 03021 Chain, false)) 03022 Invalid = true; 03023 03024 // Mark this as an anonymous struct/union type. Note that we do not 03025 // do this until after we have already checked and injected the 03026 // members of this anonymous struct/union type, because otherwise 03027 // the members could be injected twice: once by DeclContext when it 03028 // builds its lookup table, and once by 03029 // InjectAnonymousStructOrUnionMembers. 03030 Record->setAnonymousStructOrUnion(true); 03031 03032 if (Invalid) 03033 Anon->setInvalidDecl(); 03034 03035 return Anon; 03036 } 03037 03038 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 03039 /// Microsoft C anonymous structure. 03040 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 03041 /// Example: 03042 /// 03043 /// struct A { int a; }; 03044 /// struct B { struct A; int b; }; 03045 /// 03046 /// void foo() { 03047 /// B var; 03048 /// var.a = 3; 03049 /// } 03050 /// 03051 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 03052 RecordDecl *Record) { 03053 03054 // If there is no Record, get the record via the typedef. 03055 if (!Record) 03056 Record = DS.getRepAsType().get()->getAsStructureType()->getDecl(); 03057 03058 // Mock up a declarator. 03059 Declarator Dc(DS, Declarator::TypeNameContext); 03060 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 03061 assert(TInfo && "couldn't build declarator info for anonymous struct"); 03062 03063 // Create a declaration for this anonymous struct. 03064 NamedDecl* Anon = FieldDecl::Create(Context, 03065 cast<RecordDecl>(CurContext), 03066 DS.getLocStart(), 03067 DS.getLocStart(), 03068 /*IdentifierInfo=*/0, 03069 Context.getTypeDeclType(Record), 03070 TInfo, 03071 /*BitWidth=*/0, /*Mutable=*/false, 03072 /*HasInit=*/false); 03073 Anon->setImplicit(); 03074 03075 // Add the anonymous struct object to the current context. 03076 CurContext->addDecl(Anon); 03077 03078 // Inject the members of the anonymous struct into the current 03079 // context and into the identifier resolver chain for name lookup 03080 // purposes. 03081 SmallVector<NamedDecl*, 2> Chain; 03082 Chain.push_back(Anon); 03083 03084 RecordDecl *RecordDef = Record->getDefinition(); 03085 if (!RecordDef || InjectAnonymousStructOrUnionMembers(*this, S, CurContext, 03086 RecordDef, AS_none, 03087 Chain, true)) 03088 Anon->setInvalidDecl(); 03089 03090 return Anon; 03091 } 03092 03093 /// GetNameForDeclarator - Determine the full declaration name for the 03094 /// given Declarator. 03095 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 03096 return GetNameFromUnqualifiedId(D.getName()); 03097 } 03098 03099 /// \brief Retrieves the declaration name from a parsed unqualified-id. 03100 DeclarationNameInfo 03101 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 03102 DeclarationNameInfo NameInfo; 03103 NameInfo.setLoc(Name.StartLocation); 03104 03105 switch (Name.getKind()) { 03106 03107 case UnqualifiedId::IK_ImplicitSelfParam: 03108 case UnqualifiedId::IK_Identifier: 03109 NameInfo.setName(Name.Identifier); 03110 NameInfo.setLoc(Name.StartLocation); 03111 return NameInfo; 03112 03113 case UnqualifiedId::IK_OperatorFunctionId: 03114 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 03115 Name.OperatorFunctionId.Operator)); 03116 NameInfo.setLoc(Name.StartLocation); 03117 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 03118 = Name.OperatorFunctionId.SymbolLocations[0]; 03119 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 03120 = Name.EndLocation.getRawEncoding(); 03121 return NameInfo; 03122 03123 case UnqualifiedId::IK_LiteralOperatorId: 03124 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 03125 Name.Identifier)); 03126 NameInfo.setLoc(Name.StartLocation); 03127 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 03128 return NameInfo; 03129 03130 case UnqualifiedId::IK_ConversionFunctionId: { 03131 TypeSourceInfo *TInfo; 03132 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 03133 if (Ty.isNull()) 03134 return DeclarationNameInfo(); 03135 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 03136 Context.getCanonicalType(Ty))); 03137 NameInfo.setLoc(Name.StartLocation); 03138 NameInfo.setNamedTypeInfo(TInfo); 03139 return NameInfo; 03140 } 03141 03142 case UnqualifiedId::IK_ConstructorName: { 03143 TypeSourceInfo *TInfo; 03144 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 03145 if (Ty.isNull()) 03146 return DeclarationNameInfo(); 03147 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 03148 Context.getCanonicalType(Ty))); 03149 NameInfo.setLoc(Name.StartLocation); 03150 NameInfo.setNamedTypeInfo(TInfo); 03151 return NameInfo; 03152 } 03153 03154 case UnqualifiedId::IK_ConstructorTemplateId: { 03155 // In well-formed code, we can only have a constructor 03156 // template-id that refers to the current context, so go there 03157 // to find the actual type being constructed. 03158 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 03159 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 03160 return DeclarationNameInfo(); 03161 03162 // Determine the type of the class being constructed. 03163 QualType CurClassType = Context.getTypeDeclType(CurClass); 03164 03165 // FIXME: Check two things: that the template-id names the same type as 03166 // CurClassType, and that the template-id does not occur when the name 03167 // was qualified. 03168 03169 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 03170 Context.getCanonicalType(CurClassType))); 03171 NameInfo.setLoc(Name.StartLocation); 03172 // FIXME: should we retrieve TypeSourceInfo? 03173 NameInfo.setNamedTypeInfo(0); 03174 return NameInfo; 03175 } 03176 03177 case UnqualifiedId::IK_DestructorName: { 03178 TypeSourceInfo *TInfo; 03179 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 03180 if (Ty.isNull()) 03181 return DeclarationNameInfo(); 03182 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 03183 Context.getCanonicalType(Ty))); 03184 NameInfo.setLoc(Name.StartLocation); 03185 NameInfo.setNamedTypeInfo(TInfo); 03186 return NameInfo; 03187 } 03188 03189 case UnqualifiedId::IK_TemplateId: { 03190 TemplateName TName = Name.TemplateId->Template.get(); 03191 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 03192 return Context.getNameForTemplate(TName, TNameLoc); 03193 } 03194 03195 } // switch (Name.getKind()) 03196 03197 llvm_unreachable("Unknown name kind"); 03198 } 03199 03200 static QualType getCoreType(QualType Ty) { 03201 do { 03202 if (Ty->isPointerType() || Ty->isReferenceType()) 03203 Ty = Ty->getPointeeType(); 03204 else if (Ty->isArrayType()) 03205 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 03206 else 03207 return Ty.withoutLocalFastQualifiers(); 03208 } while (true); 03209 } 03210 03211 /// hasSimilarParameters - Determine whether the C++ functions Declaration 03212 /// and Definition have "nearly" matching parameters. This heuristic is 03213 /// used to improve diagnostics in the case where an out-of-line function 03214 /// definition doesn't match any declaration within the class or namespace. 03215 /// Also sets Params to the list of indices to the parameters that differ 03216 /// between the declaration and the definition. If hasSimilarParameters 03217 /// returns true and Params is empty, then all of the parameters match. 03218 static bool hasSimilarParameters(ASTContext &Context, 03219 FunctionDecl *Declaration, 03220 FunctionDecl *Definition, 03221 llvm::SmallVectorImpl<unsigned> &Params) { 03222 Params.clear(); 03223 if (Declaration->param_size() != Definition->param_size()) 03224 return false; 03225 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 03226 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 03227 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 03228 03229 // The parameter types are identical 03230 if (Context.hasSameType(DefParamTy, DeclParamTy)) 03231 continue; 03232 03233 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 03234 QualType DefParamBaseTy = getCoreType(DefParamTy); 03235 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 03236 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 03237 03238 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 03239 (DeclTyName && DeclTyName == DefTyName)) 03240 Params.push_back(Idx); 03241 else // The two parameters aren't even close 03242 return false; 03243 } 03244 03245 return true; 03246 } 03247 03248 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 03249 /// declarator needs to be rebuilt in the current instantiation. 03250 /// Any bits of declarator which appear before the name are valid for 03251 /// consideration here. That's specifically the type in the decl spec 03252 /// and the base type in any member-pointer chunks. 03253 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 03254 DeclarationName Name) { 03255 // The types we specifically need to rebuild are: 03256 // - typenames, typeofs, and decltypes 03257 // - types which will become injected class names 03258 // Of course, we also need to rebuild any type referencing such a 03259 // type. It's safest to just say "dependent", but we call out a 03260 // few cases here. 03261 03262 DeclSpec &DS = D.getMutableDeclSpec(); 03263 switch (DS.getTypeSpecType()) { 03264 case DeclSpec::TST_typename: 03265 case DeclSpec::TST_typeofType: 03266 case DeclSpec::TST_decltype: 03267 case DeclSpec::TST_underlyingType: 03268 case DeclSpec::TST_atomic: { 03269 // Grab the type from the parser. 03270 TypeSourceInfo *TSI = 0; 03271 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 03272 if (T.isNull() || !T->isDependentType()) break; 03273 03274 // Make sure there's a type source info. This isn't really much 03275 // of a waste; most dependent types should have type source info 03276 // attached already. 03277 if (!TSI) 03278 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 03279 03280 // Rebuild the type in the current instantiation. 03281 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 03282 if (!TSI) return true; 03283 03284 // Store the new type back in the decl spec. 03285 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 03286 DS.UpdateTypeRep(LocType); 03287 break; 03288 } 03289 03290 case DeclSpec::TST_typeofExpr: { 03291 Expr *E = DS.getRepAsExpr(); 03292 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 03293 if (Result.isInvalid()) return true; 03294 DS.UpdateExprRep(Result.get()); 03295 break; 03296 } 03297 03298 default: 03299 // Nothing to do for these decl specs. 03300 break; 03301 } 03302 03303 // It doesn't matter what order we do this in. 03304 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 03305 DeclaratorChunk &Chunk = D.getTypeObject(I); 03306 03307 // The only type information in the declarator which can come 03308 // before the declaration name is the base type of a member 03309 // pointer. 03310 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 03311 continue; 03312 03313 // Rebuild the scope specifier in-place. 03314 CXXScopeSpec &SS = Chunk.Mem.Scope(); 03315 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 03316 return true; 03317 } 03318 03319 return false; 03320 } 03321 03322 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 03323 D.setFunctionDefinitionKind(FDK_Declaration); 03324 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg(*this)); 03325 03326 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 03327 Dcl && Dcl->getDeclContext()->isFileContext()) 03328 Dcl->setTopLevelDeclInObjCContainer(); 03329 03330 return Dcl; 03331 } 03332 03333 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 03334 /// If T is the name of a class, then each of the following shall have a 03335 /// name different from T: 03336 /// - every static data member of class T; 03337 /// - every member function of class T 03338 /// - every member of class T that is itself a type; 03339 /// \returns true if the declaration name violates these rules. 03340 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 03341 DeclarationNameInfo NameInfo) { 03342 DeclarationName Name = NameInfo.getName(); 03343 03344 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 03345 if (Record->getIdentifier() && Record->getDeclName() == Name) { 03346 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 03347 return true; 03348 } 03349 03350 return false; 03351 } 03352 03353 /// \brief Diagnose a declaration whose declarator-id has the given 03354 /// nested-name-specifier. 03355 /// 03356 /// \param SS The nested-name-specifier of the declarator-id. 03357 /// 03358 /// \param DC The declaration context to which the nested-name-specifier 03359 /// resolves. 03360 /// 03361 /// \param Name The name of the entity being declared. 03362 /// 03363 /// \param Loc The location of the name of the entity being declared. 03364 /// 03365 /// \returns true if we cannot safely recover from this error, false otherwise. 03366 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 03367 DeclarationName Name, 03368 SourceLocation Loc) { 03369 DeclContext *Cur = CurContext; 03370 while (isa<LinkageSpecDecl>(Cur)) 03371 Cur = Cur->getParent(); 03372 03373 // C++ [dcl.meaning]p1: 03374 // A declarator-id shall not be qualified except for the definition 03375 // of a member function (9.3) or static data member (9.4) outside of 03376 // its class, the definition or explicit instantiation of a function 03377 // or variable member of a namespace outside of its namespace, or the 03378 // definition of an explicit specialization outside of its namespace, 03379 // or the declaration of a friend function that is a member of 03380 // another class or namespace (11.3). [...] 03381 03382 // The user provided a superfluous scope specifier that refers back to the 03383 // class or namespaces in which the entity is already declared. 03384 // 03385 // class X { 03386 // void X::f(); 03387 // }; 03388 if (Cur->Equals(DC)) { 03389 Diag(Loc, diag::warn_member_extra_qualification) 03390 << Name << FixItHint::CreateRemoval(SS.getRange()); 03391 SS.clear(); 03392 return false; 03393 } 03394 03395 // Check whether the qualifying scope encloses the scope of the original 03396 // declaration. 03397 if (!Cur->Encloses(DC)) { 03398 if (Cur->isRecord()) 03399 Diag(Loc, diag::err_member_qualification) 03400 << Name << SS.getRange(); 03401 else if (isa<TranslationUnitDecl>(DC)) 03402 Diag(Loc, diag::err_invalid_declarator_global_scope) 03403 << Name << SS.getRange(); 03404 else if (isa<FunctionDecl>(Cur)) 03405 Diag(Loc, diag::err_invalid_declarator_in_function) 03406 << Name << SS.getRange(); 03407 else 03408 Diag(Loc, diag::err_invalid_declarator_scope) 03409 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 03410 03411 return true; 03412 } 03413 03414 if (Cur->isRecord()) { 03415 // Cannot qualify members within a class. 03416 Diag(Loc, diag::err_member_qualification) 03417 << Name << SS.getRange(); 03418 SS.clear(); 03419 03420 // C++ constructors and destructors with incorrect scopes can break 03421 // our AST invariants by having the wrong underlying types. If 03422 // that's the case, then drop this declaration entirely. 03423 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 03424 Name.getNameKind() == DeclarationName::CXXDestructorName) && 03425 !Context.hasSameType(Name.getCXXNameType(), 03426 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 03427 return true; 03428 03429 return false; 03430 } 03431 03432 // C++11 [dcl.meaning]p1: 03433 // [...] "The nested-name-specifier of the qualified declarator-id shall 03434 // not begin with a decltype-specifer" 03435 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 03436 while (SpecLoc.getPrefix()) 03437 SpecLoc = SpecLoc.getPrefix(); 03438 if (dyn_cast_or_null<DecltypeType>( 03439 SpecLoc.getNestedNameSpecifier()->getAsType())) 03440 Diag(Loc, diag::err_decltype_in_declarator) 03441 << SpecLoc.getTypeLoc().getSourceRange(); 03442 03443 return false; 03444 } 03445 03446 Decl *Sema::HandleDeclarator(Scope *S, Declarator &D, 03447 MultiTemplateParamsArg TemplateParamLists) { 03448 // TODO: consider using NameInfo for diagnostic. 03449 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 03450 DeclarationName Name = NameInfo.getName(); 03451 03452 // All of these full declarators require an identifier. If it doesn't have 03453 // one, the ParsedFreeStandingDeclSpec action should be used. 03454 if (!Name) { 03455 if (!D.isInvalidType()) // Reject this if we think it is valid. 03456 Diag(D.getDeclSpec().getLocStart(), 03457 diag::err_declarator_need_ident) 03458 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 03459 return 0; 03460 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 03461 return 0; 03462 03463 // The scope passed in may not be a decl scope. Zip up the scope tree until 03464 // we find one that is. 03465 while ((S->getFlags() & Scope::DeclScope) == 0 || 03466 (S->getFlags() & Scope::TemplateParamScope) != 0) 03467 S = S->getParent(); 03468 03469 DeclContext *DC = CurContext; 03470 if (D.getCXXScopeSpec().isInvalid()) 03471 D.setInvalidType(); 03472 else if (D.getCXXScopeSpec().isSet()) { 03473 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 03474 UPPC_DeclarationQualifier)) 03475 return 0; 03476 03477 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 03478 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 03479 if (!DC) { 03480 // If we could not compute the declaration context, it's because the 03481 // declaration context is dependent but does not refer to a class, 03482 // class template, or class template partial specialization. Complain 03483 // and return early, to avoid the coming semantic disaster. 03484 Diag(D.getIdentifierLoc(), 03485 diag::err_template_qualified_declarator_no_match) 03486 << (NestedNameSpecifier*)D.getCXXScopeSpec().getScopeRep() 03487 << D.getCXXScopeSpec().getRange(); 03488 return 0; 03489 } 03490 bool IsDependentContext = DC->isDependentContext(); 03491 03492 if (!IsDependentContext && 03493 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 03494 return 0; 03495 03496 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 03497 Diag(D.getIdentifierLoc(), 03498 diag::err_member_def_undefined_record) 03499 << Name << DC << D.getCXXScopeSpec().getRange(); 03500 D.setInvalidType(); 03501 } else if (!D.getDeclSpec().isFriendSpecified()) { 03502 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 03503 Name, D.getIdentifierLoc())) { 03504 if (DC->isRecord()) 03505 return 0; 03506 03507 D.setInvalidType(); 03508 } 03509 } 03510 03511 // Check whether we need to rebuild the type of the given 03512 // declaration in the current instantiation. 03513 if (EnteringContext && IsDependentContext && 03514 TemplateParamLists.size() != 0) { 03515 ContextRAII SavedContext(*this, DC); 03516 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 03517 D.setInvalidType(); 03518 } 03519 } 03520 03521 if (DiagnoseClassNameShadow(DC, NameInfo)) 03522 // If this is a typedef, we'll end up spewing multiple diagnostics. 03523 // Just return early; it's safer. 03524 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 03525 return 0; 03526 03527 NamedDecl *New; 03528 03529 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 03530 QualType R = TInfo->getType(); 03531 03532 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 03533 UPPC_DeclarationType)) 03534 D.setInvalidType(); 03535 03536 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 03537 ForRedeclaration); 03538 03539 // See if this is a redefinition of a variable in the same scope. 03540 if (!D.getCXXScopeSpec().isSet()) { 03541 bool IsLinkageLookup = false; 03542 03543 // If the declaration we're planning to build will be a function 03544 // or object with linkage, then look for another declaration with 03545 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 03546 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 03547 /* Do nothing*/; 03548 else if (R->isFunctionType()) { 03549 if (CurContext->isFunctionOrMethod() || 03550 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 03551 IsLinkageLookup = true; 03552 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) 03553 IsLinkageLookup = true; 03554 else if (CurContext->getRedeclContext()->isTranslationUnit() && 03555 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 03556 IsLinkageLookup = true; 03557 03558 if (IsLinkageLookup) 03559 Previous.clear(LookupRedeclarationWithLinkage); 03560 03561 LookupName(Previous, S, /* CreateBuiltins = */ IsLinkageLookup); 03562 } else { // Something like "int foo::x;" 03563 LookupQualifiedName(Previous, DC); 03564 03565 // C++ [dcl.meaning]p1: 03566 // When the declarator-id is qualified, the declaration shall refer to a 03567 // previously declared member of the class or namespace to which the 03568 // qualifier refers (or, in the case of a namespace, of an element of the 03569 // inline namespace set of that namespace (7.3.1)) or to a specialization 03570 // thereof; [...] 03571 // 03572 // Note that we already checked the context above, and that we do not have 03573 // enough information to make sure that Previous contains the declaration 03574 // we want to match. For example, given: 03575 // 03576 // class X { 03577 // void f(); 03578 // void f(float); 03579 // }; 03580 // 03581 // void X::f(int) { } // ill-formed 03582 // 03583 // In this case, Previous will point to the overload set 03584 // containing the two f's declared in X, but neither of them 03585 // matches. 03586 03587 // C++ [dcl.meaning]p1: 03588 // [...] the member shall not merely have been introduced by a 03589 // using-declaration in the scope of the class or namespace nominated by 03590 // the nested-name-specifier of the declarator-id. 03591 RemoveUsingDecls(Previous); 03592 } 03593 03594 if (Previous.isSingleResult() && 03595 Previous.getFoundDecl()->isTemplateParameter()) { 03596 // Maybe we will complain about the shadowed template parameter. 03597 if (!D.isInvalidType()) 03598 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 03599 Previous.getFoundDecl()); 03600 03601 // Just pretend that we didn't see the previous declaration. 03602 Previous.clear(); 03603 } 03604 03605 // In C++, the previous declaration we find might be a tag type 03606 // (class or enum). In this case, the new declaration will hide the 03607 // tag type. Note that this does does not apply if we're declaring a 03608 // typedef (C++ [dcl.typedef]p4). 03609 if (Previous.isSingleTagDecl() && 03610 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 03611 Previous.clear(); 03612 03613 bool AddToScope = true; 03614 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 03615 if (TemplateParamLists.size()) { 03616 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 03617 return 0; 03618 } 03619 03620 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 03621 } else if (R->isFunctionType()) { 03622 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 03623 move(TemplateParamLists), 03624 AddToScope); 03625 } else { 03626 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, 03627 move(TemplateParamLists)); 03628 } 03629 03630 if (New == 0) 03631 return 0; 03632 03633 // If this has an identifier and is not an invalid redeclaration or 03634 // function template specialization, add it to the scope stack. 03635 if (New->getDeclName() && AddToScope && 03636 !(D.isRedeclaration() && New->isInvalidDecl())) 03637 PushOnScopeChains(New, S); 03638 03639 return New; 03640 } 03641 03642 /// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array 03643 /// types into constant array types in certain situations which would otherwise 03644 /// be errors (for GCC compatibility). 03645 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 03646 ASTContext &Context, 03647 bool &SizeIsNegative, 03648 llvm::APSInt &Oversized) { 03649 // This method tries to turn a variable array into a constant 03650 // array even when the size isn't an ICE. This is necessary 03651 // for compatibility with code that depends on gcc's buggy 03652 // constant expression folding, like struct {char x[(int)(char*)2];} 03653 SizeIsNegative = false; 03654 Oversized = 0; 03655 03656 if (T->isDependentType()) 03657 return QualType(); 03658 03659 QualifierCollector Qs; 03660 const Type *Ty = Qs.strip(T); 03661 03662 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 03663 QualType Pointee = PTy->getPointeeType(); 03664 QualType FixedType = 03665 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 03666 Oversized); 03667 if (FixedType.isNull()) return FixedType; 03668 FixedType = Context.getPointerType(FixedType); 03669 return Qs.apply(Context, FixedType); 03670 } 03671 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 03672 QualType Inner = PTy->getInnerType(); 03673 QualType FixedType = 03674 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 03675 Oversized); 03676 if (FixedType.isNull()) return FixedType; 03677 FixedType = Context.getParenType(FixedType); 03678 return Qs.apply(Context, FixedType); 03679 } 03680 03681 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 03682 if (!VLATy) 03683 return QualType(); 03684 // FIXME: We should probably handle this case 03685 if (VLATy->getElementType()->isVariablyModifiedType()) 03686 return QualType(); 03687 03688 llvm::APSInt Res; 03689 if (!VLATy->getSizeExpr() || 03690 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 03691 return QualType(); 03692 03693 // Check whether the array size is negative. 03694 if (Res.isSigned() && Res.isNegative()) { 03695 SizeIsNegative = true; 03696 return QualType(); 03697 } 03698 03699 // Check whether the array is too large to be addressed. 03700 unsigned ActiveSizeBits 03701 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 03702 Res); 03703 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 03704 Oversized = Res; 03705 return QualType(); 03706 } 03707 03708 return Context.getConstantArrayType(VLATy->getElementType(), 03709 Res, ArrayType::Normal, 0); 03710 } 03711 03712 /// \brief Register the given locally-scoped external C declaration so 03713 /// that it can be found later for redeclarations 03714 void 03715 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, 03716 const LookupResult &Previous, 03717 Scope *S) { 03718 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() && 03719 "Decl is not a locally-scoped decl!"); 03720 // Note that we have a locally-scoped external with this name. 03721 LocallyScopedExternalDecls[ND->getDeclName()] = ND; 03722 03723 if (!Previous.isSingleResult()) 03724 return; 03725 03726 NamedDecl *PrevDecl = Previous.getFoundDecl(); 03727 03728 // If there was a previous declaration of this variable, it may be 03729 // in our identifier chain. Update the identifier chain with the new 03730 // declaration. 03731 if (S && IdResolver.ReplaceDecl(PrevDecl, ND)) { 03732 // The previous declaration was found on the identifer resolver 03733 // chain, so remove it from its scope. 03734 03735 if (S->isDeclScope(PrevDecl)) { 03736 // Special case for redeclarations in the SAME scope. 03737 // Because this declaration is going to be added to the identifier chain 03738 // later, we should temporarily take it OFF the chain. 03739 IdResolver.RemoveDecl(ND); 03740 03741 } else { 03742 // Find the scope for the original declaration. 03743 while (S && !S->isDeclScope(PrevDecl)) 03744 S = S->getParent(); 03745 } 03746 03747 if (S) 03748 S->RemoveDecl(PrevDecl); 03749 } 03750 } 03751 03752 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 03753 Sema::findLocallyScopedExternalDecl(DeclarationName Name) { 03754 if (ExternalSource) { 03755 // Load locally-scoped external decls from the external source. 03756 SmallVector<NamedDecl *, 4> Decls; 03757 ExternalSource->ReadLocallyScopedExternalDecls(Decls); 03758 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 03759 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 03760 = LocallyScopedExternalDecls.find(Decls[I]->getDeclName()); 03761 if (Pos == LocallyScopedExternalDecls.end()) 03762 LocallyScopedExternalDecls[Decls[I]->getDeclName()] = Decls[I]; 03763 } 03764 } 03765 03766 return LocallyScopedExternalDecls.find(Name); 03767 } 03768 03769 /// \brief Diagnose function specifiers on a declaration of an identifier that 03770 /// does not identify a function. 03771 void Sema::DiagnoseFunctionSpecifiers(Declarator& D) { 03772 // FIXME: We should probably indicate the identifier in question to avoid 03773 // confusion for constructs like "inline int a(), b;" 03774 if (D.getDeclSpec().isInlineSpecified()) 03775 Diag(D.getDeclSpec().getInlineSpecLoc(), 03776 diag::err_inline_non_function); 03777 03778 if (D.getDeclSpec().isVirtualSpecified()) 03779 Diag(D.getDeclSpec().getVirtualSpecLoc(), 03780 diag::err_virtual_non_function); 03781 03782 if (D.getDeclSpec().isExplicitSpecified()) 03783 Diag(D.getDeclSpec().getExplicitSpecLoc(), 03784 diag::err_explicit_non_function); 03785 } 03786 03787 NamedDecl* 03788 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 03789 TypeSourceInfo *TInfo, LookupResult &Previous) { 03790 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 03791 if (D.getCXXScopeSpec().isSet()) { 03792 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 03793 << D.getCXXScopeSpec().getRange(); 03794 D.setInvalidType(); 03795 // Pretend we didn't see the scope specifier. 03796 DC = CurContext; 03797 Previous.clear(); 03798 } 03799 03800 if (getLangOpts().CPlusPlus) { 03801 // Check that there are no default arguments (C++ only). 03802 CheckExtraCXXDefaultArguments(D); 03803 } 03804 03805 DiagnoseFunctionSpecifiers(D); 03806 03807 if (D.getDeclSpec().isThreadSpecified()) 03808 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 03809 if (D.getDeclSpec().isConstexprSpecified()) 03810 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 03811 << 1; 03812 03813 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 03814 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 03815 << D.getName().getSourceRange(); 03816 return 0; 03817 } 03818 03819 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 03820 if (!NewTD) return 0; 03821 03822 // Handle attributes prior to checking for duplicates in MergeVarDecl 03823 ProcessDeclAttributes(S, NewTD, D); 03824 03825 CheckTypedefForVariablyModifiedType(S, NewTD); 03826 03827 bool Redeclaration = D.isRedeclaration(); 03828 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 03829 D.setRedeclaration(Redeclaration); 03830 return ND; 03831 } 03832 03833 void 03834 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 03835 // C99 6.7.7p2: If a typedef name specifies a variably modified type 03836 // then it shall have block scope. 03837 // Note that variably modified types must be fixed before merging the decl so 03838 // that redeclarations will match. 03839 QualType T = NewTD->getUnderlyingType(); 03840 if (T->isVariablyModifiedType()) { 03841 getCurFunction()->setHasBranchProtectedScope(); 03842 03843 if (S->getFnParent() == 0) { 03844 bool SizeIsNegative; 03845 llvm::APSInt Oversized; 03846 QualType FixedTy = 03847 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 03848 Oversized); 03849 if (!FixedTy.isNull()) { 03850 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 03851 NewTD->setTypeSourceInfo(Context.getTrivialTypeSourceInfo(FixedTy)); 03852 } else { 03853 if (SizeIsNegative) 03854 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 03855 else if (T->isVariableArrayType()) 03856 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 03857 else if (Oversized.getBoolValue()) 03858 Diag(NewTD->getLocation(), diag::err_array_too_large) 03859 << Oversized.toString(10); 03860 else 03861 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 03862 NewTD->setInvalidDecl(); 03863 } 03864 } 03865 } 03866 } 03867 03868 03869 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 03870 /// declares a typedef-name, either using the 'typedef' type specifier or via 03871 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 03872 NamedDecl* 03873 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 03874 LookupResult &Previous, bool &Redeclaration) { 03875 // Merge the decl with the existing one if appropriate. If the decl is 03876 // in an outer scope, it isn't the same thing. 03877 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/ false, 03878 /*ExplicitInstantiationOrSpecialization=*/false); 03879 if (!Previous.empty()) { 03880 Redeclaration = true; 03881 MergeTypedefNameDecl(NewTD, Previous); 03882 } 03883 03884 // If this is the C FILE type, notify the AST context. 03885 if (IdentifierInfo *II = NewTD->getIdentifier()) 03886 if (!NewTD->isInvalidDecl() && 03887 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 03888 if (II->isStr("FILE")) 03889 Context.setFILEDecl(NewTD); 03890 else if (II->isStr("jmp_buf")) 03891 Context.setjmp_bufDecl(NewTD); 03892 else if (II->isStr("sigjmp_buf")) 03893 Context.setsigjmp_bufDecl(NewTD); 03894 else if (II->isStr("ucontext_t")) 03895 Context.setucontext_tDecl(NewTD); 03896 else if (II->isStr("__builtin_va_list")) 03897 Context.setBuiltinVaListType(Context.getTypedefType(NewTD)); 03898 } 03899 03900 return NewTD; 03901 } 03902 03903 /// \brief Determines whether the given declaration is an out-of-scope 03904 /// previous declaration. 03905 /// 03906 /// This routine should be invoked when name lookup has found a 03907 /// previous declaration (PrevDecl) that is not in the scope where a 03908 /// new declaration by the same name is being introduced. If the new 03909 /// declaration occurs in a local scope, previous declarations with 03910 /// linkage may still be considered previous declarations (C99 03911 /// 6.2.2p4-5, C++ [basic.link]p6). 03912 /// 03913 /// \param PrevDecl the previous declaration found by name 03914 /// lookup 03915 /// 03916 /// \param DC the context in which the new declaration is being 03917 /// declared. 03918 /// 03919 /// \returns true if PrevDecl is an out-of-scope previous declaration 03920 /// for a new delcaration with the same name. 03921 static bool 03922 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 03923 ASTContext &Context) { 03924 if (!PrevDecl) 03925 return false; 03926 03927 if (!PrevDecl->hasLinkage()) 03928 return false; 03929 03930 if (Context.getLangOpts().CPlusPlus) { 03931 // C++ [basic.link]p6: 03932 // If there is a visible declaration of an entity with linkage 03933 // having the same name and type, ignoring entities declared 03934 // outside the innermost enclosing namespace scope, the block 03935 // scope declaration declares that same entity and receives the 03936 // linkage of the previous declaration. 03937 DeclContext *OuterContext = DC->getRedeclContext(); 03938 if (!OuterContext->isFunctionOrMethod()) 03939 // This rule only applies to block-scope declarations. 03940 return false; 03941 03942 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 03943 if (PrevOuterContext->isRecord()) 03944 // We found a member function: ignore it. 03945 return false; 03946 03947 // Find the innermost enclosing namespace for the new and 03948 // previous declarations. 03949 OuterContext = OuterContext->getEnclosingNamespaceContext(); 03950 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 03951 03952 // The previous declaration is in a different namespace, so it 03953 // isn't the same function. 03954 if (!OuterContext->Equals(PrevOuterContext)) 03955 return false; 03956 } 03957 03958 return true; 03959 } 03960 03961 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 03962 CXXScopeSpec &SS = D.getCXXScopeSpec(); 03963 if (!SS.isSet()) return; 03964 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 03965 } 03966 03967 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 03968 QualType type = decl->getType(); 03969 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 03970 if (lifetime == Qualifiers::OCL_Autoreleasing) { 03971 // Various kinds of declaration aren't allowed to be __autoreleasing. 03972 unsigned kind = -1U; 03973 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 03974 if (var->hasAttr<BlocksAttr>()) 03975 kind = 0; // __block 03976 else if (!var->hasLocalStorage()) 03977 kind = 1; // global 03978 } else if (isa<ObjCIvarDecl>(decl)) { 03979 kind = 3; // ivar 03980 } else if (isa<FieldDecl>(decl)) { 03981 kind = 2; // field 03982 } 03983 03984 if (kind != -1U) { 03985 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 03986 << kind; 03987 } 03988 } else if (lifetime == Qualifiers::OCL_None) { 03989 // Try to infer lifetime. 03990 if (!type->isObjCLifetimeType()) 03991 return false; 03992 03993 lifetime = type->getObjCARCImplicitLifetime(); 03994 type = Context.getLifetimeQualifiedType(type, lifetime); 03995 decl->setType(type); 03996 } 03997 03998 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 03999 // Thread-local variables cannot have lifetime. 04000 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 04001 var->isThreadSpecified()) { 04002 Diag(var->getLocation(), diag::err_arc_thread_ownership) 04003 << var->getType(); 04004 return true; 04005 } 04006 } 04007 04008 return false; 04009 } 04010 04011 NamedDecl* 04012 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 04013 TypeSourceInfo *TInfo, LookupResult &Previous, 04014 MultiTemplateParamsArg TemplateParamLists) { 04015 QualType R = TInfo->getType(); 04016 DeclarationName Name = GetNameForDeclarator(D).getName(); 04017 04018 // Check that there are no default arguments (C++ only). 04019 if (getLangOpts().CPlusPlus) 04020 CheckExtraCXXDefaultArguments(D); 04021 04022 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 04023 assert(SCSpec != DeclSpec::SCS_typedef && 04024 "Parser allowed 'typedef' as storage class VarDecl."); 04025 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(SCSpec); 04026 if (SCSpec == DeclSpec::SCS_mutable) { 04027 // mutable can only appear on non-static class members, so it's always 04028 // an error here 04029 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 04030 D.setInvalidType(); 04031 SC = SC_None; 04032 } 04033 SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 04034 VarDecl::StorageClass SCAsWritten 04035 = StorageClassSpecToVarDeclStorageClass(SCSpec); 04036 04037 IdentifierInfo *II = Name.getAsIdentifierInfo(); 04038 if (!II) { 04039 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 04040 << Name; 04041 return 0; 04042 } 04043 04044 DiagnoseFunctionSpecifiers(D); 04045 04046 if (!DC->isRecord() && S->getFnParent() == 0) { 04047 // C99 6.9p2: The storage-class specifiers auto and register shall not 04048 // appear in the declaration specifiers in an external declaration. 04049 if (SC == SC_Auto || SC == SC_Register) { 04050 04051 // If this is a register variable with an asm label specified, then this 04052 // is a GNU extension. 04053 if (SC == SC_Register && D.getAsmLabel()) 04054 Diag(D.getIdentifierLoc(), diag::err_unsupported_global_register); 04055 else 04056 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 04057 D.setInvalidType(); 04058 } 04059 } 04060 04061 if (getLangOpts().OpenCL) { 04062 // Set up the special work-group-local storage class for variables in the 04063 // OpenCL __local address space. 04064 if (R.getAddressSpace() == LangAS::opencl_local) 04065 SC = SC_OpenCLWorkGroupLocal; 04066 } 04067 04068 bool isExplicitSpecialization = false; 04069 VarDecl *NewVD; 04070 if (!getLangOpts().CPlusPlus) { 04071 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 04072 D.getIdentifierLoc(), II, 04073 R, TInfo, SC, SCAsWritten); 04074 04075 if (D.isInvalidType()) 04076 NewVD->setInvalidDecl(); 04077 } else { 04078 if (DC->isRecord() && !CurContext->isRecord()) { 04079 // This is an out-of-line definition of a static data member. 04080 if (SC == SC_Static) { 04081 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 04082 diag::err_static_out_of_line) 04083 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 04084 } else if (SC == SC_None) 04085 SC = SC_Static; 04086 } 04087 if (SC == SC_Static && CurContext->isRecord()) { 04088 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 04089 if (RD->isLocalClass()) 04090 Diag(D.getIdentifierLoc(), 04091 diag::err_static_data_member_not_allowed_in_local_class) 04092 << Name << RD->getDeclName(); 04093 04094 // C++98 [class.union]p1: If a union contains a static data member, 04095 // the program is ill-formed. C++11 drops this restriction. 04096 if (RD->isUnion()) 04097 Diag(D.getIdentifierLoc(), 04098 getLangOpts().CPlusPlus0x 04099 ? diag::warn_cxx98_compat_static_data_member_in_union 04100 : diag::ext_static_data_member_in_union) << Name; 04101 // We conservatively disallow static data members in anonymous structs. 04102 else if (!RD->getDeclName()) 04103 Diag(D.getIdentifierLoc(), 04104 diag::err_static_data_member_not_allowed_in_anon_struct) 04105 << Name << RD->isUnion(); 04106 } 04107 } 04108 04109 // Match up the template parameter lists with the scope specifier, then 04110 // determine whether we have a template or a template specialization. 04111 isExplicitSpecialization = false; 04112 bool Invalid = false; 04113 if (TemplateParameterList *TemplateParams 04114 = MatchTemplateParametersToScopeSpecifier( 04115 D.getDeclSpec().getLocStart(), 04116 D.getIdentifierLoc(), 04117 D.getCXXScopeSpec(), 04118 TemplateParamLists.get(), 04119 TemplateParamLists.size(), 04120 /*never a friend*/ false, 04121 isExplicitSpecialization, 04122 Invalid)) { 04123 if (TemplateParams->size() > 0) { 04124 // There is no such thing as a variable template. 04125 Diag(D.getIdentifierLoc(), diag::err_template_variable) 04126 << II 04127 << SourceRange(TemplateParams->getTemplateLoc(), 04128 TemplateParams->getRAngleLoc()); 04129 return 0; 04130 } else { 04131 // There is an extraneous 'template<>' for this variable. Complain 04132 // about it, but allow the declaration of the variable. 04133 Diag(TemplateParams->getTemplateLoc(), 04134 diag::err_template_variable_noparams) 04135 << II 04136 << SourceRange(TemplateParams->getTemplateLoc(), 04137 TemplateParams->getRAngleLoc()); 04138 } 04139 } 04140 04141 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 04142 D.getIdentifierLoc(), II, 04143 R, TInfo, SC, SCAsWritten); 04144 04145 // If this decl has an auto type in need of deduction, make a note of the 04146 // Decl so we can diagnose uses of it in its own initializer. 04147 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto && 04148 R->getContainedAutoType()) 04149 ParsingInitForAutoVars.insert(NewVD); 04150 04151 if (D.isInvalidType() || Invalid) 04152 NewVD->setInvalidDecl(); 04153 04154 SetNestedNameSpecifier(NewVD, D); 04155 04156 if (TemplateParamLists.size() > 0 && D.getCXXScopeSpec().isSet()) { 04157 NewVD->setTemplateParameterListsInfo(Context, 04158 TemplateParamLists.size(), 04159 TemplateParamLists.release()); 04160 } 04161 04162 if (D.getDeclSpec().isConstexprSpecified()) 04163 NewVD->setConstexpr(true); 04164 } 04165 04166 // Set the lexical context. If the declarator has a C++ scope specifier, the 04167 // lexical context will be different from the semantic context. 04168 NewVD->setLexicalDeclContext(CurContext); 04169 04170 if (D.getDeclSpec().isThreadSpecified()) { 04171 if (NewVD->hasLocalStorage()) 04172 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_non_global); 04173 else if (!Context.getTargetInfo().isTLSSupported()) 04174 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_thread_unsupported); 04175 else 04176 NewVD->setThreadSpecified(true); 04177 } 04178 04179 if (D.getDeclSpec().isModulePrivateSpecified()) { 04180 if (isExplicitSpecialization) 04181 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 04182 << 2 04183 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 04184 else if (NewVD->hasLocalStorage()) 04185 Diag(NewVD->getLocation(), diag::err_module_private_local) 04186 << 0 << NewVD->getDeclName() 04187 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 04188 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 04189 else 04190 NewVD->setModulePrivate(); 04191 } 04192 04193 // Handle attributes prior to checking for duplicates in MergeVarDecl 04194 ProcessDeclAttributes(S, NewVD, D); 04195 04196 // In auto-retain/release, infer strong retension for variables of 04197 // retainable type. 04198 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 04199 NewVD->setInvalidDecl(); 04200 04201 // Handle GNU asm-label extension (encoded as an attribute). 04202 if (Expr *E = (Expr*)D.getAsmLabel()) { 04203 // The parser guarantees this is a string. 04204 StringLiteral *SE = cast<StringLiteral>(E); 04205 StringRef Label = SE->getString(); 04206 if (S->getFnParent() != 0) { 04207 switch (SC) { 04208 case SC_None: 04209 case SC_Auto: 04210 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 04211 break; 04212 case SC_Register: 04213 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 04214 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 04215 break; 04216 case SC_Static: 04217 case SC_Extern: 04218 case SC_PrivateExtern: 04219 case SC_OpenCLWorkGroupLocal: 04220 break; 04221 } 04222 } 04223 04224 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 04225 Context, Label)); 04226 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 04227 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 04228 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 04229 if (I != ExtnameUndeclaredIdentifiers.end()) { 04230 NewVD->addAttr(I->second); 04231 ExtnameUndeclaredIdentifiers.erase(I); 04232 } 04233 } 04234 04235 // Diagnose shadowed variables before filtering for scope. 04236 if (!D.getCXXScopeSpec().isSet()) 04237 CheckShadow(S, NewVD, Previous); 04238 04239 // Don't consider existing declarations that are in a different 04240 // scope and are out-of-semantic-context declarations (if the new 04241 // declaration has linkage). 04242 FilterLookupForScope(Previous, DC, S, NewVD->hasLinkage(), 04243 isExplicitSpecialization); 04244 04245 if (!getLangOpts().CPlusPlus) { 04246 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 04247 } else { 04248 // Merge the decl with the existing one if appropriate. 04249 if (!Previous.empty()) { 04250 if (Previous.isSingleResult() && 04251 isa<FieldDecl>(Previous.getFoundDecl()) && 04252 D.getCXXScopeSpec().isSet()) { 04253 // The user tried to define a non-static data member 04254 // out-of-line (C++ [dcl.meaning]p1). 04255 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 04256 << D.getCXXScopeSpec().getRange(); 04257 Previous.clear(); 04258 NewVD->setInvalidDecl(); 04259 } 04260 } else if (D.getCXXScopeSpec().isSet()) { 04261 // No previous declaration in the qualifying scope. 04262 Diag(D.getIdentifierLoc(), diag::err_no_member) 04263 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 04264 << D.getCXXScopeSpec().getRange(); 04265 NewVD->setInvalidDecl(); 04266 } 04267 04268 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 04269 04270 // This is an explicit specialization of a static data member. Check it. 04271 if (isExplicitSpecialization && !NewVD->isInvalidDecl() && 04272 CheckMemberSpecialization(NewVD, Previous)) 04273 NewVD->setInvalidDecl(); 04274 } 04275 04276 // If this is a locally-scoped extern C variable, update the map of 04277 // such variables. 04278 if (CurContext->isFunctionOrMethod() && NewVD->isExternC() && 04279 !NewVD->isInvalidDecl()) 04280 RegisterLocallyScopedExternCDecl(NewVD, Previous, S); 04281 04282 // If there's a #pragma GCC visibility in scope, and this isn't a class 04283 // member, set the visibility of this variable. 04284 if (NewVD->getLinkage() == ExternalLinkage && !DC->isRecord()) 04285 AddPushedVisibilityAttribute(NewVD); 04286 04287 MarkUnusedFileScopedDecl(NewVD); 04288 04289 return NewVD; 04290 } 04291 04292 /// \brief Diagnose variable or built-in function shadowing. Implements 04293 /// -Wshadow. 04294 /// 04295 /// This method is called whenever a VarDecl is added to a "useful" 04296 /// scope. 04297 /// 04298 /// \param S the scope in which the shadowing name is being declared 04299 /// \param R the lookup of the name 04300 /// 04301 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 04302 // Return if warning is ignored. 04303 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, R.getNameLoc()) == 04304 DiagnosticsEngine::Ignored) 04305 return; 04306 04307 // Don't diagnose declarations at file scope. 04308 if (D->hasGlobalStorage()) 04309 return; 04310 04311 DeclContext *NewDC = D->getDeclContext(); 04312 04313 // Only diagnose if we're shadowing an unambiguous field or variable. 04314 if (R.getResultKind() != LookupResult::Found) 04315 return; 04316 04317 NamedDecl* ShadowedDecl = R.getFoundDecl(); 04318 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 04319 return; 04320 04321 // Fields are not shadowed by variables in C++ static methods. 04322 if (isa<FieldDecl>(ShadowedDecl)) 04323 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 04324 if (MD->isStatic()) 04325 return; 04326 04327 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 04328 if (shadowedVar->isExternC()) { 04329 // For shadowing external vars, make sure that we point to the global 04330 // declaration, not a locally scoped extern declaration. 04331 for (VarDecl::redecl_iterator 04332 I = shadowedVar->redecls_begin(), E = shadowedVar->redecls_end(); 04333 I != E; ++I) 04334 if (I->isFileVarDecl()) { 04335 ShadowedDecl = *I; 04336 break; 04337 } 04338 } 04339 04340 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 04341 04342 // Only warn about certain kinds of shadowing for class members. 04343 if (NewDC && NewDC->isRecord()) { 04344 // In particular, don't warn about shadowing non-class members. 04345 if (!OldDC->isRecord()) 04346 return; 04347 04348 // TODO: should we warn about static data members shadowing 04349 // static data members from base classes? 04350 04351 // TODO: don't diagnose for inaccessible shadowed members. 04352 // This is hard to do perfectly because we might friend the 04353 // shadowing context, but that's just a false negative. 04354 } 04355 04356 // Determine what kind of declaration we're shadowing. 04357 unsigned Kind; 04358 if (isa<RecordDecl>(OldDC)) { 04359 if (isa<FieldDecl>(ShadowedDecl)) 04360 Kind = 3; // field 04361 else 04362 Kind = 2; // static data member 04363 } else if (OldDC->isFileContext()) 04364 Kind = 1; // global 04365 else 04366 Kind = 0; // local 04367 04368 DeclarationName Name = R.getLookupName(); 04369 04370 // Emit warning and note. 04371 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 04372 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 04373 } 04374 04375 /// \brief Check -Wshadow without the advantage of a previous lookup. 04376 void Sema::CheckShadow(Scope *S, VarDecl *D) { 04377 if (Diags.getDiagnosticLevel(diag::warn_decl_shadow, D->getLocation()) == 04378 DiagnosticsEngine::Ignored) 04379 return; 04380 04381 LookupResult R(*this, D->getDeclName(), D->getLocation(), 04382 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 04383 LookupName(R, S); 04384 CheckShadow(S, D, R); 04385 } 04386 04387 /// \brief Perform semantic checking on a newly-created variable 04388 /// declaration. 04389 /// 04390 /// This routine performs all of the type-checking required for a 04391 /// variable declaration once it has been built. It is used both to 04392 /// check variables after they have been parsed and their declarators 04393 /// have been translated into a declaration, and to check variables 04394 /// that have been instantiated from a template. 04395 /// 04396 /// Sets NewVD->isInvalidDecl() if an error was encountered. 04397 /// 04398 /// Returns true if the variable declaration is a redeclaration. 04399 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, 04400 LookupResult &Previous) { 04401 // If the decl is already known invalid, don't check it. 04402 if (NewVD->isInvalidDecl()) 04403 return false; 04404 04405 QualType T = NewVD->getType(); 04406 04407 if (T->isObjCObjectType()) { 04408 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 04409 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 04410 T = Context.getObjCObjectPointerType(T); 04411 NewVD->setType(T); 04412 } 04413 04414 // Emit an error if an address space was applied to decl with local storage. 04415 // This includes arrays of objects with address space qualifiers, but not 04416 // automatic variables that point to other address spaces. 04417 // ISO/IEC TR 18037 S5.1.2 04418 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 04419 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 04420 NewVD->setInvalidDecl(); 04421 return false; 04422 } 04423 04424 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 04425 && !NewVD->hasAttr<BlocksAttr>()) { 04426 if (getLangOpts().getGC() != LangOptions::NonGC) 04427 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 04428 else 04429 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 04430 } 04431 04432 bool isVM = T->isVariablyModifiedType(); 04433 if (isVM || NewVD->hasAttr<CleanupAttr>() || 04434 NewVD->hasAttr<BlocksAttr>()) 04435 getCurFunction()->setHasBranchProtectedScope(); 04436 04437 if ((isVM && NewVD->hasLinkage()) || 04438 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 04439 bool SizeIsNegative; 04440 llvm::APSInt Oversized; 04441 QualType FixedTy = 04442 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 04443 Oversized); 04444 04445 if (FixedTy.isNull() && T->isVariableArrayType()) { 04446 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 04447 // FIXME: This won't give the correct result for 04448 // int a[10][n]; 04449 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 04450 04451 if (NewVD->isFileVarDecl()) 04452 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 04453 << SizeRange; 04454 else if (NewVD->getStorageClass() == SC_Static) 04455 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 04456 << SizeRange; 04457 else 04458 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 04459 << SizeRange; 04460 NewVD->setInvalidDecl(); 04461 return false; 04462 } 04463 04464 if (FixedTy.isNull()) { 04465 if (NewVD->isFileVarDecl()) 04466 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 04467 else 04468 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 04469 NewVD->setInvalidDecl(); 04470 return false; 04471 } 04472 04473 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 04474 NewVD->setType(FixedTy); 04475 } 04476 04477 if (Previous.empty() && NewVD->isExternC()) { 04478 // Since we did not find anything by this name and we're declaring 04479 // an extern "C" variable, look for a non-visible extern "C" 04480 // declaration with the same name. 04481 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 04482 = findLocallyScopedExternalDecl(NewVD->getDeclName()); 04483 if (Pos != LocallyScopedExternalDecls.end()) 04484 Previous.addDecl(Pos->second); 04485 } 04486 04487 if (T->isVoidType() && !NewVD->hasExternalStorage()) { 04488 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 04489 << T; 04490 NewVD->setInvalidDecl(); 04491 return false; 04492 } 04493 04494 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 04495 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 04496 NewVD->setInvalidDecl(); 04497 return false; 04498 } 04499 04500 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 04501 Diag(NewVD->getLocation(), diag::err_block_on_vm); 04502 NewVD->setInvalidDecl(); 04503 return false; 04504 } 04505 04506 if (NewVD->isConstexpr() && !T->isDependentType() && 04507 RequireLiteralType(NewVD->getLocation(), T, 04508 diag::err_constexpr_var_non_literal)) { 04509 NewVD->setInvalidDecl(); 04510 return false; 04511 } 04512 04513 if (!Previous.empty()) { 04514 MergeVarDecl(NewVD, Previous); 04515 return true; 04516 } 04517 return false; 04518 } 04519 04520 /// \brief Data used with FindOverriddenMethod 04521 struct FindOverriddenMethodData { 04522 Sema *S; 04523 CXXMethodDecl *Method; 04524 }; 04525 04526 /// \brief Member lookup function that determines whether a given C++ 04527 /// method overrides a method in a base class, to be used with 04528 /// CXXRecordDecl::lookupInBases(). 04529 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 04530 CXXBasePath &Path, 04531 void *UserData) { 04532 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 04533 04534 FindOverriddenMethodData *Data 04535 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 04536 04537 DeclarationName Name = Data->Method->getDeclName(); 04538 04539 // FIXME: Do we care about other names here too? 04540 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 04541 // We really want to find the base class destructor here. 04542 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 04543 CanQualType CT = Data->S->Context.getCanonicalType(T); 04544 04545 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 04546 } 04547 04548 for (Path.Decls = BaseRecord->lookup(Name); 04549 Path.Decls.first != Path.Decls.second; 04550 ++Path.Decls.first) { 04551 NamedDecl *D = *Path.Decls.first; 04552 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 04553 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 04554 return true; 04555 } 04556 } 04557 04558 return false; 04559 } 04560 04561 static bool hasDelayedExceptionSpec(CXXMethodDecl *Method) { 04562 const FunctionProtoType *Proto =Method->getType()->getAs<FunctionProtoType>(); 04563 return Proto && Proto->getExceptionSpecType() == EST_Delayed; 04564 } 04565 04566 /// AddOverriddenMethods - See if a method overrides any in the base classes, 04567 /// and if so, check that it's a valid override and remember it. 04568 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 04569 // Look for virtual methods in base classes that this method might override. 04570 CXXBasePaths Paths; 04571 FindOverriddenMethodData Data; 04572 Data.Method = MD; 04573 Data.S = this; 04574 bool AddedAny = false; 04575 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 04576 for (CXXBasePaths::decl_iterator I = Paths.found_decls_begin(), 04577 E = Paths.found_decls_end(); I != E; ++I) { 04578 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(*I)) { 04579 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 04580 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 04581 (hasDelayedExceptionSpec(MD) || 04582 !CheckOverridingFunctionExceptionSpec(MD, OldMD)) && 04583 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 04584 AddedAny = true; 04585 } 04586 } 04587 } 04588 } 04589 04590 return AddedAny; 04591 } 04592 04593 namespace { 04594 // Struct for holding all of the extra arguments needed by 04595 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 04596 struct ActOnFDArgs { 04597 Scope *S; 04598 Declarator &D; 04599 MultiTemplateParamsArg TemplateParamLists; 04600 bool AddToScope; 04601 }; 04602 } 04603 04604 namespace { 04605 04606 // Callback to only accept typo corrections that have a non-zero edit distance. 04607 // Also only accept corrections that have the same parent decl. 04608 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 04609 public: 04610 DifferentNameValidatorCCC(CXXRecordDecl *Parent) 04611 : ExpectedParent(Parent ? Parent->getCanonicalDecl() : 0) {} 04612 04613 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 04614 if (candidate.getEditDistance() == 0) 04615 return false; 04616 04617 if (CXXMethodDecl *MD = candidate.getCorrectionDeclAs<CXXMethodDecl>()) { 04618 CXXRecordDecl *Parent = MD->getParent(); 04619 return Parent && Parent->getCanonicalDecl() == ExpectedParent; 04620 } 04621 04622 return !ExpectedParent; 04623 } 04624 04625 private: 04626 CXXRecordDecl *ExpectedParent; 04627 }; 04628 04629 } 04630 04631 /// \brief Generate diagnostics for an invalid function redeclaration. 04632 /// 04633 /// This routine handles generating the diagnostic messages for an invalid 04634 /// function redeclaration, including finding possible similar declarations 04635 /// or performing typo correction if there are no previous declarations with 04636 /// the same name. 04637 /// 04638 /// Returns a NamedDecl iff typo correction was performed and substituting in 04639 /// the new declaration name does not cause new errors. 04640 static NamedDecl* DiagnoseInvalidRedeclaration( 04641 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 04642 ActOnFDArgs &ExtraArgs) { 04643 NamedDecl *Result = NULL; 04644 DeclarationName Name = NewFD->getDeclName(); 04645 DeclContext *NewDC = NewFD->getDeclContext(); 04646 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 04647 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 04648 llvm::SmallVector<unsigned, 1> MismatchedParams; 04649 llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1> NearMatches; 04650 TypoCorrection Correction; 04651 bool isFriendDecl = (SemaRef.getLangOpts().CPlusPlus && 04652 ExtraArgs.D.getDeclSpec().isFriendSpecified()); 04653 unsigned DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend 04654 : diag::err_member_def_does_not_match; 04655 04656 NewFD->setInvalidDecl(); 04657 SemaRef.LookupQualifiedName(Prev, NewDC); 04658 assert(!Prev.isAmbiguous() && 04659 "Cannot have an ambiguity in previous-declaration lookup"); 04660 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 04661 DifferentNameValidatorCCC Validator(MD ? MD->getParent() : 0); 04662 if (!Prev.empty()) { 04663 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 04664 Func != FuncEnd; ++Func) { 04665 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 04666 if (FD && 04667 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 04668 // Add 1 to the index so that 0 can mean the mismatch didn't 04669 // involve a parameter 04670 unsigned ParamNum = 04671 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 04672 NearMatches.push_back(std::make_pair(FD, ParamNum)); 04673 } 04674 } 04675 // If the qualified name lookup yielded nothing, try typo correction 04676 } else if ((Correction = SemaRef.CorrectTypo(Prev.getLookupNameInfo(), 04677 Prev.getLookupKind(), 0, 0, 04678 Validator, NewDC))) { 04679 // Trap errors. 04680 Sema::SFINAETrap Trap(SemaRef); 04681 04682 // Set up everything for the call to ActOnFunctionDeclarator 04683 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 04684 ExtraArgs.D.getIdentifierLoc()); 04685 Previous.clear(); 04686 Previous.setLookupName(Correction.getCorrection()); 04687 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 04688 CDeclEnd = Correction.end(); 04689 CDecl != CDeclEnd; ++CDecl) { 04690 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 04691 if (FD && hasSimilarParameters(SemaRef.Context, FD, NewFD, 04692 MismatchedParams)) { 04693 Previous.addDecl(FD); 04694 } 04695 } 04696 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 04697 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 04698 // pieces need to verify the typo-corrected C++ declaraction and hopefully 04699 // eliminate the need for the parameter pack ExtraArgs. 04700 Result = SemaRef.ActOnFunctionDeclarator( 04701 ExtraArgs.S, ExtraArgs.D, 04702 Correction.getCorrectionDecl()->getDeclContext(), 04703 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 04704 ExtraArgs.AddToScope); 04705 if (Trap.hasErrorOccurred()) { 04706 // Pretend the typo correction never occurred 04707 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 04708 ExtraArgs.D.getIdentifierLoc()); 04709 ExtraArgs.D.setRedeclaration(wasRedeclaration); 04710 Previous.clear(); 04711 Previous.setLookupName(Name); 04712 Result = NULL; 04713 } else { 04714 for (LookupResult::iterator Func = Previous.begin(), 04715 FuncEnd = Previous.end(); 04716 Func != FuncEnd; ++Func) { 04717 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) 04718 NearMatches.push_back(std::make_pair(FD, 0)); 04719 } 04720 } 04721 if (NearMatches.empty()) { 04722 // Ignore the correction if it didn't yield any close FunctionDecl matches 04723 Correction = TypoCorrection(); 04724 } else { 04725 DiagMsg = isFriendDecl ? diag::err_no_matching_local_friend_suggest 04726 : diag::err_member_def_does_not_match_suggest; 04727 } 04728 } 04729 04730 if (Correction) 04731 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 04732 << Name << NewDC << Correction.getQuoted(SemaRef.getLangOpts()) 04733 << FixItHint::CreateReplacement( 04734 NewFD->getLocation(), 04735 Correction.getAsString(SemaRef.getLangOpts())); 04736 else 04737 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 04738 << Name << NewDC << NewFD->getLocation(); 04739 04740 bool NewFDisConst = false; 04741 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 04742 NewFDisConst = NewMD->getTypeQualifiers() & Qualifiers::Const; 04743 04744 for (llvm::SmallVector<std::pair<FunctionDecl*, unsigned>, 1>::iterator 04745 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 04746 NearMatch != NearMatchEnd; ++NearMatch) { 04747 FunctionDecl *FD = NearMatch->first; 04748 bool FDisConst = false; 04749 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 04750 FDisConst = MD->getTypeQualifiers() & Qualifiers::Const; 04751 04752 if (unsigned Idx = NearMatch->second) { 04753 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 04754 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 04755 if (Loc.isInvalid()) Loc = FD->getLocation(); 04756 SemaRef.Diag(Loc, diag::note_member_def_close_param_match) 04757 << Idx << FDParam->getType() << NewFD->getParamDecl(Idx-1)->getType(); 04758 } else if (Correction) { 04759 SemaRef.Diag(FD->getLocation(), diag::note_previous_decl) 04760 << Correction.getQuoted(SemaRef.getLangOpts()); 04761 } else if (FDisConst != NewFDisConst) { 04762 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 04763 << NewFDisConst << FD->getSourceRange().getEnd(); 04764 } else 04765 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_match); 04766 } 04767 return Result; 04768 } 04769 04770 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 04771 Declarator &D) { 04772 switch (D.getDeclSpec().getStorageClassSpec()) { 04773 default: llvm_unreachable("Unknown storage class!"); 04774 case DeclSpec::SCS_auto: 04775 case DeclSpec::SCS_register: 04776 case DeclSpec::SCS_mutable: 04777 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 04778 diag::err_typecheck_sclass_func); 04779 D.setInvalidType(); 04780 break; 04781 case DeclSpec::SCS_unspecified: break; 04782 case DeclSpec::SCS_extern: return SC_Extern; 04783 case DeclSpec::SCS_static: { 04784 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 04785 // C99 6.7.1p5: 04786 // The declaration of an identifier for a function that has 04787 // block scope shall have no explicit storage-class specifier 04788 // other than extern 04789 // See also (C++ [dcl.stc]p4). 04790 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 04791 diag::err_static_block_func); 04792 break; 04793 } else 04794 return SC_Static; 04795 } 04796 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 04797 } 04798 04799 // No explicit storage class has already been returned 04800 return SC_None; 04801 } 04802 04803 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 04804 DeclContext *DC, QualType &R, 04805 TypeSourceInfo *TInfo, 04806 FunctionDecl::StorageClass SC, 04807 bool &IsVirtualOkay) { 04808 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 04809 DeclarationName Name = NameInfo.getName(); 04810 04811 FunctionDecl *NewFD = 0; 04812 bool isInline = D.getDeclSpec().isInlineSpecified(); 04813 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpecAsWritten(); 04814 FunctionDecl::StorageClass SCAsWritten 04815 = StorageClassSpecToFunctionDeclStorageClass(SCSpec); 04816 04817 if (!SemaRef.getLangOpts().CPlusPlus) { 04818 // Determine whether the function was written with a 04819 // prototype. This true when: 04820 // - there is a prototype in the declarator, or 04821 // - the type R of the function is some kind of typedef or other reference 04822 // to a type name (which eventually refers to a function type). 04823 bool HasPrototype = 04824 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 04825 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 04826 04827 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 04828 D.getLocStart(), NameInfo, R, 04829 TInfo, SC, SCAsWritten, isInline, 04830 HasPrototype); 04831 if (D.isInvalidType()) 04832 NewFD->setInvalidDecl(); 04833 04834 // Set the lexical context. 04835 NewFD->setLexicalDeclContext(SemaRef.CurContext); 04836 04837 return NewFD; 04838 } 04839 04840 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 04841 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 04842 04843 // Check that the return type is not an abstract class type. 04844 // For record types, this is done by the AbstractClassUsageDiagnoser once 04845 // the class has been completely parsed. 04846 if (!DC->isRecord() && 04847 SemaRef.RequireNonAbstractType(D.getIdentifierLoc(), 04848 R->getAs<FunctionType>()->getResultType(), 04849 diag::err_abstract_type_in_decl, 04850 SemaRef.AbstractReturnType)) 04851 D.setInvalidType(); 04852 04853 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 04854 // This is a C++ constructor declaration. 04855 assert(DC->isRecord() && 04856 "Constructors can only be declared in a member context"); 04857 04858 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 04859 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 04860 D.getLocStart(), NameInfo, 04861 R, TInfo, isExplicit, isInline, 04862 /*isImplicitlyDeclared=*/false, 04863 isConstexpr); 04864 04865 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 04866 // This is a C++ destructor declaration. 04867 if (DC->isRecord()) { 04868 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 04869 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 04870 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 04871 SemaRef.Context, Record, 04872 D.getLocStart(), 04873 NameInfo, R, TInfo, isInline, 04874 /*isImplicitlyDeclared=*/false); 04875 04876 // If the class is complete, then we now create the implicit exception 04877 // specification. If the class is incomplete or dependent, we can't do 04878 // it yet. 04879 if (SemaRef.getLangOpts().CPlusPlus0x && !Record->isDependentType() && 04880 Record->getDefinition() && !Record->isBeingDefined() && 04881 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 04882 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 04883 } 04884 04885 IsVirtualOkay = true; 04886 return NewDD; 04887 04888 } else { 04889 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 04890 D.setInvalidType(); 04891 04892 // Create a FunctionDecl to satisfy the function definition parsing 04893 // code path. 04894 return FunctionDecl::Create(SemaRef.Context, DC, 04895 D.getLocStart(), 04896 D.getIdentifierLoc(), Name, R, TInfo, 04897 SC, SCAsWritten, isInline, 04898 /*hasPrototype=*/true, isConstexpr); 04899 } 04900 04901 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 04902 if (!DC->isRecord()) { 04903 SemaRef.Diag(D.getIdentifierLoc(), 04904 diag::err_conv_function_not_member); 04905 return 0; 04906 } 04907 04908 SemaRef.CheckConversionDeclarator(D, R, SC); 04909 IsVirtualOkay = true; 04910 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 04911 D.getLocStart(), NameInfo, 04912 R, TInfo, isInline, isExplicit, 04913 isConstexpr, SourceLocation()); 04914 04915 } else if (DC->isRecord()) { 04916 // If the name of the function is the same as the name of the record, 04917 // then this must be an invalid constructor that has a return type. 04918 // (The parser checks for a return type and makes the declarator a 04919 // constructor if it has no return type). 04920 if (Name.getAsIdentifierInfo() && 04921 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 04922 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 04923 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 04924 << SourceRange(D.getIdentifierLoc()); 04925 return 0; 04926 } 04927 04928 bool isStatic = SC == SC_Static; 04929 04930 // [class.free]p1: 04931 // Any allocation function for a class T is a static member 04932 // (even if not explicitly declared static). 04933 if (Name.getCXXOverloadedOperator() == OO_New || 04934 Name.getCXXOverloadedOperator() == OO_Array_New) 04935 isStatic = true; 04936 04937 // [class.free]p6 Any deallocation function for a class X is a static member 04938 // (even if not explicitly declared static). 04939 if (Name.getCXXOverloadedOperator() == OO_Delete || 04940 Name.getCXXOverloadedOperator() == OO_Array_Delete) 04941 isStatic = true; 04942 04943 IsVirtualOkay = !isStatic; 04944 04945 // This is a C++ method declaration. 04946 return CXXMethodDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 04947 D.getLocStart(), NameInfo, R, 04948 TInfo, isStatic, SCAsWritten, isInline, 04949 isConstexpr, SourceLocation()); 04950 04951 } else { 04952 // Determine whether the function was written with a 04953 // prototype. This true when: 04954 // - we're in C++ (where every function has a prototype), 04955 return FunctionDecl::Create(SemaRef.Context, DC, 04956 D.getLocStart(), 04957 NameInfo, R, TInfo, SC, SCAsWritten, isInline, 04958 true/*HasPrototype*/, isConstexpr); 04959 } 04960 } 04961 04962 NamedDecl* 04963 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 04964 TypeSourceInfo *TInfo, LookupResult &Previous, 04965 MultiTemplateParamsArg TemplateParamLists, 04966 bool &AddToScope) { 04967 QualType R = TInfo->getType(); 04968 04969 assert(R.getTypePtr()->isFunctionType()); 04970 04971 // TODO: consider using NameInfo for diagnostic. 04972 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 04973 DeclarationName Name = NameInfo.getName(); 04974 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 04975 04976 if (D.getDeclSpec().isThreadSpecified()) 04977 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 04978 04979 // Do not allow returning a objc interface by-value. 04980 if (R->getAs<FunctionType>()->getResultType()->isObjCObjectType()) { 04981 Diag(D.getIdentifierLoc(), 04982 diag::err_object_cannot_be_passed_returned_by_value) << 0 04983 << R->getAs<FunctionType>()->getResultType() 04984 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*"); 04985 04986 QualType T = R->getAs<FunctionType>()->getResultType(); 04987 T = Context.getObjCObjectPointerType(T); 04988 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(R)) { 04989 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 04990 R = Context.getFunctionType(T, FPT->arg_type_begin(), 04991 FPT->getNumArgs(), EPI); 04992 } 04993 else if (isa<FunctionNoProtoType>(R)) 04994 R = Context.getFunctionNoProtoType(T); 04995 } 04996 04997 bool isFriend = false; 04998 FunctionTemplateDecl *FunctionTemplate = 0; 04999 bool isExplicitSpecialization = false; 05000 bool isFunctionTemplateSpecialization = false; 05001 bool isDependentClassScopeExplicitSpecialization = false; 05002 bool isVirtualOkay = false; 05003 05004 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 05005 isVirtualOkay); 05006 if (!NewFD) return 0; 05007 05008 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 05009 NewFD->setTopLevelDeclInObjCContainer(); 05010 05011 if (getLangOpts().CPlusPlus) { 05012 bool isInline = D.getDeclSpec().isInlineSpecified(); 05013 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 05014 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 05015 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 05016 isFriend = D.getDeclSpec().isFriendSpecified(); 05017 if (isFriend && !isInline && D.isFunctionDefinition()) { 05018 // C++ [class.friend]p5 05019 // A function can be defined in a friend declaration of a 05020 // class . . . . Such a function is implicitly inline. 05021 NewFD->setImplicitlyInline(); 05022 } 05023 05024 SetNestedNameSpecifier(NewFD, D); 05025 isExplicitSpecialization = false; 05026 isFunctionTemplateSpecialization = false; 05027 if (D.isInvalidType()) 05028 NewFD->setInvalidDecl(); 05029 05030 // Set the lexical context. If the declarator has a C++ 05031 // scope specifier, or is the object of a friend declaration, the 05032 // lexical context will be different from the semantic context. 05033 NewFD->setLexicalDeclContext(CurContext); 05034 05035 // Match up the template parameter lists with the scope specifier, then 05036 // determine whether we have a template or a template specialization. 05037 bool Invalid = false; 05038 if (TemplateParameterList *TemplateParams 05039 = MatchTemplateParametersToScopeSpecifier( 05040 D.getDeclSpec().getLocStart(), 05041 D.getIdentifierLoc(), 05042 D.getCXXScopeSpec(), 05043 TemplateParamLists.get(), 05044 TemplateParamLists.size(), 05045 isFriend, 05046 isExplicitSpecialization, 05047 Invalid)) { 05048 if (TemplateParams->size() > 0) { 05049 // This is a function template 05050 05051 // Check that we can declare a template here. 05052 if (CheckTemplateDeclScope(S, TemplateParams)) 05053 return 0; 05054 05055 // A destructor cannot be a template. 05056 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 05057 Diag(NewFD->getLocation(), diag::err_destructor_template); 05058 return 0; 05059 } 05060 05061 // If we're adding a template to a dependent context, we may need to 05062 // rebuilding some of the types used within the template parameter list, 05063 // now that we know what the current instantiation is. 05064 if (DC->isDependentContext()) { 05065 ContextRAII SavedContext(*this, DC); 05066 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 05067 Invalid = true; 05068 } 05069 05070 05071 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 05072 NewFD->getLocation(), 05073 Name, TemplateParams, 05074 NewFD); 05075 FunctionTemplate->setLexicalDeclContext(CurContext); 05076 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 05077 05078 // For source fidelity, store the other template param lists. 05079 if (TemplateParamLists.size() > 1) { 05080 NewFD->setTemplateParameterListsInfo(Context, 05081 TemplateParamLists.size() - 1, 05082 TemplateParamLists.release()); 05083 } 05084 } else { 05085 // This is a function template specialization. 05086 isFunctionTemplateSpecialization = true; 05087 // For source fidelity, store all the template param lists. 05088 NewFD->setTemplateParameterListsInfo(Context, 05089 TemplateParamLists.size(), 05090 TemplateParamLists.release()); 05091 05092 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 05093 if (isFriend) { 05094 // We want to remove the "template<>", found here. 05095 SourceRange RemoveRange = TemplateParams->getSourceRange(); 05096 05097 // If we remove the template<> and the name is not a 05098 // template-id, we're actually silently creating a problem: 05099 // the friend declaration will refer to an untemplated decl, 05100 // and clearly the user wants a template specialization. So 05101 // we need to insert '<>' after the name. 05102 SourceLocation InsertLoc; 05103 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 05104 InsertLoc = D.getName().getSourceRange().getEnd(); 05105 InsertLoc = PP.getLocForEndOfToken(InsertLoc); 05106 } 05107 05108 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 05109 << Name << RemoveRange 05110 << FixItHint::CreateRemoval(RemoveRange) 05111 << FixItHint::CreateInsertion(InsertLoc, "<>"); 05112 } 05113 } 05114 } 05115 else { 05116 // All template param lists were matched against the scope specifier: 05117 // this is NOT (an explicit specialization of) a template. 05118 if (TemplateParamLists.size() > 0) 05119 // For source fidelity, store all the template param lists. 05120 NewFD->setTemplateParameterListsInfo(Context, 05121 TemplateParamLists.size(), 05122 TemplateParamLists.release()); 05123 } 05124 05125 if (Invalid) { 05126 NewFD->setInvalidDecl(); 05127 if (FunctionTemplate) 05128 FunctionTemplate->setInvalidDecl(); 05129 } 05130 05131 // If we see "T var();" at block scope, where T is a class type, it is 05132 // probably an attempt to initialize a variable, not a function declaration. 05133 // We don't catch this case earlier, since there is no ambiguity here. 05134 if (!FunctionTemplate && D.getFunctionDefinitionKind() == FDK_Declaration && 05135 CurContext->isFunctionOrMethod() && 05136 D.getNumTypeObjects() == 1 && D.isFunctionDeclarator() && 05137 D.getDeclSpec().getStorageClassSpecAsWritten() 05138 == DeclSpec::SCS_unspecified) { 05139 QualType T = R->getAs<FunctionType>()->getResultType(); 05140 DeclaratorChunk &C = D.getTypeObject(0); 05141 if (!T->isVoidType() && C.Fun.NumArgs == 0 && !C.Fun.isVariadic && 05142 !C.Fun.TrailingReturnType && 05143 C.Fun.getExceptionSpecType() == EST_None) { 05144 SourceRange ParenRange(C.Loc, C.EndLoc); 05145 Diag(C.Loc, diag::warn_empty_parens_are_function_decl) << ParenRange; 05146 05147 // If the declaration looks like: 05148 // T var1, 05149 // f(); 05150 // and name lookup finds a function named 'f', then the ',' was 05151 // probably intended to be a ';'. 05152 if (!D.isFirstDeclarator() && D.getIdentifier()) { 05153 FullSourceLoc Comma(D.getCommaLoc(), SourceMgr); 05154 FullSourceLoc Name(D.getIdentifierLoc(), SourceMgr); 05155 if (Comma.getFileID() != Name.getFileID() || 05156 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) { 05157 LookupResult Result(*this, D.getIdentifier(), SourceLocation(), 05158 LookupOrdinaryName); 05159 if (LookupName(Result, S)) 05160 Diag(D.getCommaLoc(), diag::note_empty_parens_function_call) 05161 << FixItHint::CreateReplacement(D.getCommaLoc(), ";") << NewFD; 05162 } 05163 } 05164 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 05165 // Empty parens mean value-initialization, and no parens mean default 05166 // initialization. These are equivalent if the default constructor is 05167 // user-provided, or if zero-initialization is a no-op. 05168 if (RD && RD->hasDefinition() && 05169 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor())) 05170 Diag(C.Loc, diag::note_empty_parens_default_ctor) 05171 << FixItHint::CreateRemoval(ParenRange); 05172 else { 05173 std::string Init = getFixItZeroInitializerForType(T); 05174 if (Init.empty() && LangOpts.CPlusPlus0x) 05175 Init = "{}"; 05176 if (!Init.empty()) 05177 Diag(C.Loc, diag::note_empty_parens_zero_initialize) 05178 << FixItHint::CreateReplacement(ParenRange, Init); 05179 } 05180 } 05181 } 05182 05183 // C++ [dcl.fct.spec]p5: 05184 // The virtual specifier shall only be used in declarations of 05185 // nonstatic class member functions that appear within a 05186 // member-specification of a class declaration; see 10.3. 05187 // 05188 if (isVirtual && !NewFD->isInvalidDecl()) { 05189 if (!isVirtualOkay) { 05190 Diag(D.getDeclSpec().getVirtualSpecLoc(), 05191 diag::err_virtual_non_function); 05192 } else if (!CurContext->isRecord()) { 05193 // 'virtual' was specified outside of the class. 05194 Diag(D.getDeclSpec().getVirtualSpecLoc(), 05195 diag::err_virtual_out_of_class) 05196 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 05197 } else if (NewFD->getDescribedFunctionTemplate()) { 05198 // C++ [temp.mem]p3: 05199 // A member function template shall not be virtual. 05200 Diag(D.getDeclSpec().getVirtualSpecLoc(), 05201 diag::err_virtual_member_function_template) 05202 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 05203 } else { 05204 // Okay: Add virtual to the method. 05205 NewFD->setVirtualAsWritten(true); 05206 } 05207 } 05208 05209 // C++ [dcl.fct.spec]p3: 05210 // The inline specifier shall not appear on a block scope function 05211 // declaration. 05212 if (isInline && !NewFD->isInvalidDecl()) { 05213 if (CurContext->isFunctionOrMethod()) { 05214 // 'inline' is not allowed on block scope function declaration. 05215 Diag(D.getDeclSpec().getInlineSpecLoc(), 05216 diag::err_inline_declaration_block_scope) << Name 05217 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 05218 } 05219 } 05220 05221 // C++ [dcl.fct.spec]p6: 05222 // The explicit specifier shall be used only in the declaration of a 05223 // constructor or conversion function within its class definition; 05224 // see 12.3.1 and 12.3.2. 05225 if (isExplicit && !NewFD->isInvalidDecl()) { 05226 if (!CurContext->isRecord()) { 05227 // 'explicit' was specified outside of the class. 05228 Diag(D.getDeclSpec().getExplicitSpecLoc(), 05229 diag::err_explicit_out_of_class) 05230 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 05231 } else if (!isa<CXXConstructorDecl>(NewFD) && 05232 !isa<CXXConversionDecl>(NewFD)) { 05233 // 'explicit' was specified on a function that wasn't a constructor 05234 // or conversion function. 05235 Diag(D.getDeclSpec().getExplicitSpecLoc(), 05236 diag::err_explicit_non_ctor_or_conv_function) 05237 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 05238 } 05239 } 05240 05241 if (isConstexpr) { 05242 // C++0x [dcl.constexpr]p2: constexpr functions and constexpr constructors 05243 // are implicitly inline. 05244 NewFD->setImplicitlyInline(); 05245 05246 // C++0x [dcl.constexpr]p3: functions declared constexpr are required to 05247 // be either constructors or to return a literal type. Therefore, 05248 // destructors cannot be declared constexpr. 05249 if (isa<CXXDestructorDecl>(NewFD)) 05250 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 05251 } 05252 05253 // If __module_private__ was specified, mark the function accordingly. 05254 if (D.getDeclSpec().isModulePrivateSpecified()) { 05255 if (isFunctionTemplateSpecialization) { 05256 SourceLocation ModulePrivateLoc 05257 = D.getDeclSpec().getModulePrivateSpecLoc(); 05258 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 05259 << 0 05260 << FixItHint::CreateRemoval(ModulePrivateLoc); 05261 } else { 05262 NewFD->setModulePrivate(); 05263 if (FunctionTemplate) 05264 FunctionTemplate->setModulePrivate(); 05265 } 05266 } 05267 05268 if (isFriend) { 05269 // For now, claim that the objects have no previous declaration. 05270 if (FunctionTemplate) { 05271 FunctionTemplate->setObjectOfFriendDecl(false); 05272 FunctionTemplate->setAccess(AS_public); 05273 } 05274 NewFD->setObjectOfFriendDecl(false); 05275 NewFD->setAccess(AS_public); 05276 } 05277 05278 // If a function is defined as defaulted or deleted, mark it as such now. 05279 switch (D.getFunctionDefinitionKind()) { 05280 case FDK_Declaration: 05281 case FDK_Definition: 05282 break; 05283 05284 case FDK_Defaulted: 05285 NewFD->setDefaulted(); 05286 break; 05287 05288 case FDK_Deleted: 05289 NewFD->setDeletedAsWritten(); 05290 break; 05291 } 05292 05293 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 05294 D.isFunctionDefinition()) { 05295 // C++ [class.mfct]p2: 05296 // A member function may be defined (8.4) in its class definition, in 05297 // which case it is an inline member function (7.1.2) 05298 NewFD->setImplicitlyInline(); 05299 } 05300 05301 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 05302 !CurContext->isRecord()) { 05303 // C++ [class.static]p1: 05304 // A data or function member of a class may be declared static 05305 // in a class definition, in which case it is a static member of 05306 // the class. 05307 05308 // Complain about the 'static' specifier if it's on an out-of-line 05309 // member function definition. 05310 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 05311 diag::err_static_out_of_line) 05312 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 05313 } 05314 } 05315 05316 // Filter out previous declarations that don't match the scope. 05317 FilterLookupForScope(Previous, DC, S, NewFD->hasLinkage(), 05318 isExplicitSpecialization || 05319 isFunctionTemplateSpecialization); 05320 05321 // Handle GNU asm-label extension (encoded as an attribute). 05322 if (Expr *E = (Expr*) D.getAsmLabel()) { 05323 // The parser guarantees this is a string. 05324 StringLiteral *SE = cast<StringLiteral>(E); 05325 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 05326 SE->getString())); 05327 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 05328 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 05329 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 05330 if (I != ExtnameUndeclaredIdentifiers.end()) { 05331 NewFD->addAttr(I->second); 05332 ExtnameUndeclaredIdentifiers.erase(I); 05333 } 05334 } 05335 05336 // Copy the parameter declarations from the declarator D to the function 05337 // declaration NewFD, if they are available. First scavenge them into Params. 05338 SmallVector<ParmVarDecl*, 16> Params; 05339 if (D.isFunctionDeclarator()) { 05340 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 05341 05342 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 05343 // function that takes no arguments, not a function that takes a 05344 // single void argument. 05345 // We let through "const void" here because Sema::GetTypeForDeclarator 05346 // already checks for that case. 05347 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 && 05348 FTI.ArgInfo[0].Param && 05349 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) { 05350 // Empty arg list, don't push any params. 05351 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[0].Param); 05352 05353 // In C++, the empty parameter-type-list must be spelled "void"; a 05354 // typedef of void is not permitted. 05355 if (getLangOpts().CPlusPlus && 05356 Param->getType().getUnqualifiedType() != Context.VoidTy) { 05357 bool IsTypeAlias = false; 05358 if (const TypedefType *TT = Param->getType()->getAs<TypedefType>()) 05359 IsTypeAlias = isa<TypeAliasDecl>(TT->getDecl()); 05360 else if (const TemplateSpecializationType *TST = 05361 Param->getType()->getAs<TemplateSpecializationType>()) 05362 IsTypeAlias = TST->isTypeAlias(); 05363 Diag(Param->getLocation(), diag::err_param_typedef_of_void) 05364 << IsTypeAlias; 05365 } 05366 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) { 05367 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 05368 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param); 05369 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 05370 Param->setDeclContext(NewFD); 05371 Params.push_back(Param); 05372 05373 if (Param->isInvalidDecl()) 05374 NewFD->setInvalidDecl(); 05375 } 05376 } 05377 05378 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 05379 // When we're declaring a function with a typedef, typeof, etc as in the 05380 // following example, we'll need to synthesize (unnamed) 05381 // parameters for use in the declaration. 05382 // 05383 // @code 05384 // typedef void fn(int); 05385 // fn f; 05386 // @endcode 05387 05388 // Synthesize a parameter for each argument type. 05389 for (FunctionProtoType::arg_type_iterator AI = FT->arg_type_begin(), 05390 AE = FT->arg_type_end(); AI != AE; ++AI) { 05391 ParmVarDecl *Param = 05392 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), *AI); 05393 Param->setScopeInfo(0, Params.size()); 05394 Params.push_back(Param); 05395 } 05396 } else { 05397 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 05398 "Should not need args for typedef of non-prototype fn"); 05399 } 05400 05401 // Finally, we know we have the right number of parameters, install them. 05402 NewFD->setParams(Params); 05403 05404 // Find all anonymous symbols defined during the declaration of this function 05405 // and add to NewFD. This lets us track decls such 'enum Y' in: 05406 // 05407 // void f(enum Y {AA} x) {} 05408 // 05409 // which would otherwise incorrectly end up in the translation unit scope. 05410 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 05411 DeclsInPrototypeScope.clear(); 05412 05413 // Process the non-inheritable attributes on this declaration. 05414 ProcessDeclAttributes(S, NewFD, D, 05415 /*NonInheritable=*/true, /*Inheritable=*/false); 05416 05417 // Functions returning a variably modified type violate C99 6.7.5.2p2 05418 // because all functions have linkage. 05419 if (!NewFD->isInvalidDecl() && 05420 NewFD->getResultType()->isVariablyModifiedType()) { 05421 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 05422 NewFD->setInvalidDecl(); 05423 } 05424 05425 // Handle attributes. 05426 ProcessDeclAttributes(S, NewFD, D, 05427 /*NonInheritable=*/false, /*Inheritable=*/true); 05428 05429 if (!getLangOpts().CPlusPlus) { 05430 // Perform semantic checking on the function declaration. 05431 bool isExplicitSpecialization=false; 05432 if (!NewFD->isInvalidDecl()) { 05433 if (NewFD->isMain()) 05434 CheckMain(NewFD, D.getDeclSpec()); 05435 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 05436 isExplicitSpecialization)); 05437 } 05438 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 05439 Previous.getResultKind() != LookupResult::FoundOverloaded) && 05440 "previous declaration set still overloaded"); 05441 } else { 05442 // If the declarator is a template-id, translate the parser's template 05443 // argument list into our AST format. 05444 bool HasExplicitTemplateArgs = false; 05445 TemplateArgumentListInfo TemplateArgs; 05446 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 05447 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 05448 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 05449 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 05450 ASTTemplateArgsPtr TemplateArgsPtr(*this, 05451 TemplateId->getTemplateArgs(), 05452 TemplateId->NumArgs); 05453 translateTemplateArguments(TemplateArgsPtr, 05454 TemplateArgs); 05455 TemplateArgsPtr.release(); 05456 05457 HasExplicitTemplateArgs = true; 05458 05459 if (NewFD->isInvalidDecl()) { 05460 HasExplicitTemplateArgs = false; 05461 } else if (FunctionTemplate) { 05462 // Function template with explicit template arguments. 05463 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 05464 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 05465 05466 HasExplicitTemplateArgs = false; 05467 } else if (!isFunctionTemplateSpecialization && 05468 !D.getDeclSpec().isFriendSpecified()) { 05469 // We have encountered something that the user meant to be a 05470 // specialization (because it has explicitly-specified template 05471 // arguments) but that was not introduced with a "template<>" (or had 05472 // too few of them). 05473 Diag(D.getIdentifierLoc(), diag::err_template_spec_needs_header) 05474 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc) 05475 << FixItHint::CreateInsertion( 05476 D.getDeclSpec().getLocStart(), 05477 "template<> "); 05478 isFunctionTemplateSpecialization = true; 05479 } else { 05480 // "friend void foo<>(int);" is an implicit specialization decl. 05481 isFunctionTemplateSpecialization = true; 05482 } 05483 } else if (isFriend && isFunctionTemplateSpecialization) { 05484 // This combination is only possible in a recovery case; the user 05485 // wrote something like: 05486 // template <> friend void foo(int); 05487 // which we're recovering from as if the user had written: 05488 // friend void foo<>(int); 05489 // Go ahead and fake up a template id. 05490 HasExplicitTemplateArgs = true; 05491 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 05492 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 05493 } 05494 05495 // If it's a friend (and only if it's a friend), it's possible 05496 // that either the specialized function type or the specialized 05497 // template is dependent, and therefore matching will fail. In 05498 // this case, don't check the specialization yet. 05499 bool InstantiationDependent = false; 05500 if (isFunctionTemplateSpecialization && isFriend && 05501 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 05502 TemplateSpecializationType::anyDependentTemplateArguments( 05503 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 05504 InstantiationDependent))) { 05505 assert(HasExplicitTemplateArgs && 05506 "friend function specialization without template args"); 05507 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 05508 Previous)) 05509 NewFD->setInvalidDecl(); 05510 } else if (isFunctionTemplateSpecialization) { 05511 if (CurContext->isDependentContext() && CurContext->isRecord() 05512 && !isFriend) { 05513 isDependentClassScopeExplicitSpecialization = true; 05514 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 05515 diag::ext_function_specialization_in_class : 05516 diag::err_function_specialization_in_class) 05517 << NewFD->getDeclName(); 05518 } else if (CheckFunctionTemplateSpecialization(NewFD, 05519 (HasExplicitTemplateArgs ? &TemplateArgs : 0), 05520 Previous)) 05521 NewFD->setInvalidDecl(); 05522 05523 // C++ [dcl.stc]p1: 05524 // A storage-class-specifier shall not be specified in an explicit 05525 // specialization (14.7.3) 05526 if (SC != SC_None) { 05527 if (SC != NewFD->getStorageClass()) 05528 Diag(NewFD->getLocation(), 05529 diag::err_explicit_specialization_inconsistent_storage_class) 05530 << SC 05531 << FixItHint::CreateRemoval( 05532 D.getDeclSpec().getStorageClassSpecLoc()); 05533 05534 else 05535 Diag(NewFD->getLocation(), 05536 diag::ext_explicit_specialization_storage_class) 05537 << FixItHint::CreateRemoval( 05538 D.getDeclSpec().getStorageClassSpecLoc()); 05539 } 05540 05541 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 05542 if (CheckMemberSpecialization(NewFD, Previous)) 05543 NewFD->setInvalidDecl(); 05544 } 05545 05546 // Perform semantic checking on the function declaration. 05547 if (!isDependentClassScopeExplicitSpecialization) { 05548 if (NewFD->isInvalidDecl()) { 05549 // If this is a class member, mark the class invalid immediately. 05550 // This avoids some consistency errors later. 05551 if (CXXMethodDecl* methodDecl = dyn_cast<CXXMethodDecl>(NewFD)) 05552 methodDecl->getParent()->setInvalidDecl(); 05553 } else { 05554 if (NewFD->isMain()) 05555 CheckMain(NewFD, D.getDeclSpec()); 05556 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 05557 isExplicitSpecialization)); 05558 } 05559 } 05560 05561 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 05562 Previous.getResultKind() != LookupResult::FoundOverloaded) && 05563 "previous declaration set still overloaded"); 05564 05565 NamedDecl *PrincipalDecl = (FunctionTemplate 05566 ? cast<NamedDecl>(FunctionTemplate) 05567 : NewFD); 05568 05569 if (isFriend && D.isRedeclaration()) { 05570 AccessSpecifier Access = AS_public; 05571 if (!NewFD->isInvalidDecl()) 05572 Access = NewFD->getPreviousDecl()->getAccess(); 05573 05574 NewFD->setAccess(Access); 05575 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 05576 05577 PrincipalDecl->setObjectOfFriendDecl(true); 05578 } 05579 05580 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 05581 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 05582 PrincipalDecl->setNonMemberOperator(); 05583 05584 // If we have a function template, check the template parameter 05585 // list. This will check and merge default template arguments. 05586 if (FunctionTemplate) { 05587 FunctionTemplateDecl *PrevTemplate = 05588 FunctionTemplate->getPreviousDecl(); 05589 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 05590 PrevTemplate ? PrevTemplate->getTemplateParameters() : 0, 05591 D.getDeclSpec().isFriendSpecified() 05592 ? (D.isFunctionDefinition() 05593 ? TPC_FriendFunctionTemplateDefinition 05594 : TPC_FriendFunctionTemplate) 05595 : (D.getCXXScopeSpec().isSet() && 05596 DC && DC->isRecord() && 05597 DC->isDependentContext()) 05598 ? TPC_ClassTemplateMember 05599 : TPC_FunctionTemplate); 05600 } 05601 05602 if (NewFD->isInvalidDecl()) { 05603 // Ignore all the rest of this. 05604 } else if (!D.isRedeclaration()) { 05605 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 05606 AddToScope }; 05607 // Fake up an access specifier if it's supposed to be a class member. 05608 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 05609 NewFD->setAccess(AS_public); 05610 05611 // Qualified decls generally require a previous declaration. 05612 if (D.getCXXScopeSpec().isSet()) { 05613 // ...with the major exception of templated-scope or 05614 // dependent-scope friend declarations. 05615 05616 // TODO: we currently also suppress this check in dependent 05617 // contexts because (1) the parameter depth will be off when 05618 // matching friend templates and (2) we might actually be 05619 // selecting a friend based on a dependent factor. But there 05620 // are situations where these conditions don't apply and we 05621 // can actually do this check immediately. 05622 if (isFriend && 05623 (TemplateParamLists.size() || 05624 D.getCXXScopeSpec().getScopeRep()->isDependent() || 05625 CurContext->isDependentContext())) { 05626 // ignore these 05627 } else { 05628 // The user tried to provide an out-of-line definition for a 05629 // function that is a member of a class or namespace, but there 05630 // was no such member function declared (C++ [class.mfct]p2, 05631 // C++ [namespace.memdef]p2). For example: 05632 // 05633 // class X { 05634 // void f() const; 05635 // }; 05636 // 05637 // void X::f() { } // ill-formed 05638 // 05639 // Complain about this problem, and attempt to suggest close 05640 // matches (e.g., those that differ only in cv-qualifiers and 05641 // whether the parameter types are references). 05642 05643 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 05644 NewFD, 05645 ExtraArgs)) { 05646 AddToScope = ExtraArgs.AddToScope; 05647 return Result; 05648 } 05649 } 05650 05651 // Unqualified local friend declarations are required to resolve 05652 // to something. 05653 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 05654 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(*this, Previous, 05655 NewFD, 05656 ExtraArgs)) { 05657 AddToScope = ExtraArgs.AddToScope; 05658 return Result; 05659 } 05660 } 05661 05662 } else if (!D.isFunctionDefinition() && D.getCXXScopeSpec().isSet() && 05663 !isFriend && !isFunctionTemplateSpecialization && 05664 !isExplicitSpecialization) { 05665 // An out-of-line member function declaration must also be a 05666 // definition (C++ [dcl.meaning]p1). 05667 // Note that this is not the case for explicit specializations of 05668 // function templates or member functions of class templates, per 05669 // C++ [temp.expl.spec]p2. We also allow these declarations as an 05670 // extension for compatibility with old SWIG code which likes to 05671 // generate them. 05672 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 05673 << D.getCXXScopeSpec().getRange(); 05674 } 05675 } 05676 05677 AddKnownFunctionAttributes(NewFD); 05678 05679 if (NewFD->hasAttr<OverloadableAttr>() && 05680 !NewFD->getType()->getAs<FunctionProtoType>()) { 05681 Diag(NewFD->getLocation(), 05682 diag::err_attribute_overloadable_no_prototype) 05683 << NewFD; 05684 05685 // Turn this into a variadic function with no parameters. 05686 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 05687 FunctionProtoType::ExtProtoInfo EPI; 05688 EPI.Variadic = true; 05689 EPI.ExtInfo = FT->getExtInfo(); 05690 05691 QualType R = Context.getFunctionType(FT->getResultType(), 0, 0, EPI); 05692 NewFD->setType(R); 05693 } 05694 05695 // If there's a #pragma GCC visibility in scope, and this isn't a class 05696 // member, set the visibility of this function. 05697 if (NewFD->getLinkage() == ExternalLinkage && !DC->isRecord()) 05698 AddPushedVisibilityAttribute(NewFD); 05699 05700 // If there's a #pragma clang arc_cf_code_audited in scope, consider 05701 // marking the function. 05702 AddCFAuditedAttribute(NewFD); 05703 05704 // If this is a locally-scoped extern C function, update the 05705 // map of such names. 05706 if (CurContext->isFunctionOrMethod() && NewFD->isExternC() 05707 && !NewFD->isInvalidDecl()) 05708 RegisterLocallyScopedExternCDecl(NewFD, Previous, S); 05709 05710 // Set this FunctionDecl's range up to the right paren. 05711 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 05712 05713 if (getLangOpts().CPlusPlus) { 05714 if (FunctionTemplate) { 05715 if (NewFD->isInvalidDecl()) 05716 FunctionTemplate->setInvalidDecl(); 05717 return FunctionTemplate; 05718 } 05719 } 05720 05721 MarkUnusedFileScopedDecl(NewFD); 05722 05723 if (getLangOpts().CUDA) 05724 if (IdentifierInfo *II = NewFD->getIdentifier()) 05725 if (!NewFD->isInvalidDecl() && 05726 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 05727 if (II->isStr("cudaConfigureCall")) { 05728 if (!R->getAs<FunctionType>()->getResultType()->isScalarType()) 05729 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 05730 05731 Context.setcudaConfigureCallDecl(NewFD); 05732 } 05733 } 05734 05735 // Here we have an function template explicit specialization at class scope. 05736 // The actually specialization will be postponed to template instatiation 05737 // time via the ClassScopeFunctionSpecializationDecl node. 05738 if (isDependentClassScopeExplicitSpecialization) { 05739 ClassScopeFunctionSpecializationDecl *NewSpec = 05740 ClassScopeFunctionSpecializationDecl::Create( 05741 Context, CurContext, SourceLocation(), 05742 cast<CXXMethodDecl>(NewFD)); 05743 CurContext->addDecl(NewSpec); 05744 AddToScope = false; 05745 } 05746 05747 return NewFD; 05748 } 05749 05750 /// \brief Perform semantic checking of a new function declaration. 05751 /// 05752 /// Performs semantic analysis of the new function declaration 05753 /// NewFD. This routine performs all semantic checking that does not 05754 /// require the actual declarator involved in the declaration, and is 05755 /// used both for the declaration of functions as they are parsed 05756 /// (called via ActOnDeclarator) and for the declaration of functions 05757 /// that have been instantiated via C++ template instantiation (called 05758 /// via InstantiateDecl). 05759 /// 05760 /// \param IsExplicitSpecialiation whether this new function declaration is 05761 /// an explicit specialization of the previous declaration. 05762 /// 05763 /// This sets NewFD->isInvalidDecl() to true if there was an error. 05764 /// 05765 /// Returns true if the function declaration is a redeclaration. 05766 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 05767 LookupResult &Previous, 05768 bool IsExplicitSpecialization) { 05769 assert(!NewFD->getResultType()->isVariablyModifiedType() 05770 && "Variably modified return types are not handled here"); 05771 05772 // Check for a previous declaration of this name. 05773 if (Previous.empty() && NewFD->isExternC()) { 05774 // Since we did not find anything by this name and we're declaring 05775 // an extern "C" function, look for a non-visible extern "C" 05776 // declaration with the same name. 05777 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 05778 = findLocallyScopedExternalDecl(NewFD->getDeclName()); 05779 if (Pos != LocallyScopedExternalDecls.end()) 05780 Previous.addDecl(Pos->second); 05781 } 05782 05783 bool Redeclaration = false; 05784 05785 // Merge or overload the declaration with an existing declaration of 05786 // the same name, if appropriate. 05787 if (!Previous.empty()) { 05788 // Determine whether NewFD is an overload of PrevDecl or 05789 // a declaration that requires merging. If it's an overload, 05790 // there's no more work to do here; we'll just add the new 05791 // function to the scope. 05792 05793 NamedDecl *OldDecl = 0; 05794 if (!AllowOverloadingOfFunction(Previous, Context)) { 05795 Redeclaration = true; 05796 OldDecl = Previous.getFoundDecl(); 05797 } else { 05798 switch (CheckOverload(S, NewFD, Previous, OldDecl, 05799 /*NewIsUsingDecl*/ false)) { 05800 case Ovl_Match: 05801 Redeclaration = true; 05802 break; 05803 05804 case Ovl_NonFunction: 05805 Redeclaration = true; 05806 break; 05807 05808 case Ovl_Overload: 05809 Redeclaration = false; 05810 break; 05811 } 05812 05813 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 05814 // If a function name is overloadable in C, then every function 05815 // with that name must be marked "overloadable". 05816 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 05817 << Redeclaration << NewFD; 05818 NamedDecl *OverloadedDecl = 0; 05819 if (Redeclaration) 05820 OverloadedDecl = OldDecl; 05821 else if (!Previous.empty()) 05822 OverloadedDecl = Previous.getRepresentativeDecl(); 05823 if (OverloadedDecl) 05824 Diag(OverloadedDecl->getLocation(), 05825 diag::note_attribute_overloadable_prev_overload); 05826 NewFD->addAttr(::new (Context) OverloadableAttr(SourceLocation(), 05827 Context)); 05828 } 05829 } 05830 05831 if (Redeclaration) { 05832 // NewFD and OldDecl represent declarations that need to be 05833 // merged. 05834 if (MergeFunctionDecl(NewFD, OldDecl, S)) { 05835 NewFD->setInvalidDecl(); 05836 return Redeclaration; 05837 } 05838 05839 Previous.clear(); 05840 Previous.addDecl(OldDecl); 05841 05842 if (FunctionTemplateDecl *OldTemplateDecl 05843 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 05844 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 05845 FunctionTemplateDecl *NewTemplateDecl 05846 = NewFD->getDescribedFunctionTemplate(); 05847 assert(NewTemplateDecl && "Template/non-template mismatch"); 05848 if (CXXMethodDecl *Method 05849 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 05850 Method->setAccess(OldTemplateDecl->getAccess()); 05851 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 05852 } 05853 05854 // If this is an explicit specialization of a member that is a function 05855 // template, mark it as a member specialization. 05856 if (IsExplicitSpecialization && 05857 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 05858 NewTemplateDecl->setMemberSpecialization(); 05859 assert(OldTemplateDecl->isMemberSpecialization()); 05860 } 05861 05862 } else { 05863 if (isa<CXXMethodDecl>(NewFD)) // Set access for out-of-line definitions 05864 NewFD->setAccess(OldDecl->getAccess()); 05865 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 05866 } 05867 } 05868 } 05869 05870 // Semantic checking for this function declaration (in isolation). 05871 if (getLangOpts().CPlusPlus) { 05872 // C++-specific checks. 05873 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 05874 CheckConstructor(Constructor); 05875 } else if (CXXDestructorDecl *Destructor = 05876 dyn_cast<CXXDestructorDecl>(NewFD)) { 05877 CXXRecordDecl *Record = Destructor->getParent(); 05878 QualType ClassType = Context.getTypeDeclType(Record); 05879 05880 // FIXME: Shouldn't we be able to perform this check even when the class 05881 // type is dependent? Both gcc and edg can handle that. 05882 if (!ClassType->isDependentType()) { 05883 DeclarationName Name 05884 = Context.DeclarationNames.getCXXDestructorName( 05885 Context.getCanonicalType(ClassType)); 05886 if (NewFD->getDeclName() != Name) { 05887 Diag(NewFD->getLocation(), diag::err_destructor_name); 05888 NewFD->setInvalidDecl(); 05889 return Redeclaration; 05890 } 05891 } 05892 } else if (CXXConversionDecl *Conversion 05893 = dyn_cast<CXXConversionDecl>(NewFD)) { 05894 ActOnConversionDeclarator(Conversion); 05895 } 05896 05897 // Find any virtual functions that this function overrides. 05898 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 05899 if (!Method->isFunctionTemplateSpecialization() && 05900 !Method->getDescribedFunctionTemplate()) { 05901 if (AddOverriddenMethods(Method->getParent(), Method)) { 05902 // If the function was marked as "static", we have a problem. 05903 if (NewFD->getStorageClass() == SC_Static) { 05904 Diag(NewFD->getLocation(), diag::err_static_overrides_virtual) 05905 << NewFD->getDeclName(); 05906 for (CXXMethodDecl::method_iterator 05907 Overridden = Method->begin_overridden_methods(), 05908 OverriddenEnd = Method->end_overridden_methods(); 05909 Overridden != OverriddenEnd; 05910 ++Overridden) { 05911 Diag((*Overridden)->getLocation(), 05912 diag::note_overridden_virtual_function); 05913 } 05914 } 05915 } 05916 } 05917 05918 if (Method->isStatic()) 05919 checkThisInStaticMemberFunctionType(Method); 05920 } 05921 05922 // Extra checking for C++ overloaded operators (C++ [over.oper]). 05923 if (NewFD->isOverloadedOperator() && 05924 CheckOverloadedOperatorDeclaration(NewFD)) { 05925 NewFD->setInvalidDecl(); 05926 return Redeclaration; 05927 } 05928 05929 // Extra checking for C++0x literal operators (C++0x [over.literal]). 05930 if (NewFD->getLiteralIdentifier() && 05931 CheckLiteralOperatorDeclaration(NewFD)) { 05932 NewFD->setInvalidDecl(); 05933 return Redeclaration; 05934 } 05935 05936 // In C++, check default arguments now that we have merged decls. Unless 05937 // the lexical context is the class, because in this case this is done 05938 // during delayed parsing anyway. 05939 if (!CurContext->isRecord()) 05940 CheckCXXDefaultArguments(NewFD); 05941 05942 // If this function declares a builtin function, check the type of this 05943 // declaration against the expected type for the builtin. 05944 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 05945 ASTContext::GetBuiltinTypeError Error; 05946 QualType T = Context.GetBuiltinType(BuiltinID, Error); 05947 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 05948 // The type of this function differs from the type of the builtin, 05949 // so forget about the builtin entirely. 05950 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 05951 } 05952 } 05953 05954 // If this function is declared as being extern "C", then check to see if 05955 // the function returns a UDT (class, struct, or union type) that is not C 05956 // compatible, and if it does, warn the user. 05957 if (NewFD->isExternC()) { 05958 QualType R = NewFD->getResultType(); 05959 if (!R.isPODType(Context) && 05960 !R->isVoidType()) 05961 Diag( NewFD->getLocation(), diag::warn_return_value_udt ) 05962 << NewFD << R; 05963 } 05964 } 05965 return Redeclaration; 05966 } 05967 05968 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 05969 // C++11 [basic.start.main]p3: A program that declares main to be inline, 05970 // static or constexpr is ill-formed. 05971 // C99 6.7.4p4: In a hosted environment, the inline function specifier 05972 // shall not appear in a declaration of main. 05973 // static main is not an error under C99, but we should warn about it. 05974 if (FD->getStorageClass() == SC_Static) 05975 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 05976 ? diag::err_static_main : diag::warn_static_main) 05977 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 05978 if (FD->isInlineSpecified()) 05979 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 05980 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 05981 if (FD->isConstexpr()) { 05982 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 05983 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 05984 FD->setConstexpr(false); 05985 } 05986 05987 QualType T = FD->getType(); 05988 assert(T->isFunctionType() && "function decl is not of function type"); 05989 const FunctionType* FT = T->castAs<FunctionType>(); 05990 05991 // All the standards say that main() should should return 'int'. 05992 if (Context.hasSameUnqualifiedType(FT->getResultType(), Context.IntTy)) { 05993 // In C and C++, main magically returns 0 if you fall off the end; 05994 // set the flag which tells us that. 05995 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 05996 FD->setHasImplicitReturnZero(true); 05997 05998 // In C with GNU extensions we allow main() to have non-integer return 05999 // type, but we should warn about the extension, and we disable the 06000 // implicit-return-zero rule. 06001 } else if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 06002 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 06003 06004 // Otherwise, this is just a flat-out error. 06005 } else { 06006 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint); 06007 FD->setInvalidDecl(true); 06008 } 06009 06010 // Treat protoless main() as nullary. 06011 if (isa<FunctionNoProtoType>(FT)) return; 06012 06013 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 06014 unsigned nparams = FTP->getNumArgs(); 06015 assert(FD->getNumParams() == nparams); 06016 06017 bool HasExtraParameters = (nparams > 3); 06018 06019 // Darwin passes an undocumented fourth argument of type char**. If 06020 // other platforms start sprouting these, the logic below will start 06021 // getting shifty. 06022 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 06023 HasExtraParameters = false; 06024 06025 if (HasExtraParameters) { 06026 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 06027 FD->setInvalidDecl(true); 06028 nparams = 3; 06029 } 06030 06031 // FIXME: a lot of the following diagnostics would be improved 06032 // if we had some location information about types. 06033 06034 QualType CharPP = 06035 Context.getPointerType(Context.getPointerType(Context.CharTy)); 06036 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 06037 06038 for (unsigned i = 0; i < nparams; ++i) { 06039 QualType AT = FTP->getArgType(i); 06040 06041 bool mismatch = true; 06042 06043 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 06044 mismatch = false; 06045 else if (Expected[i] == CharPP) { 06046 // As an extension, the following forms are okay: 06047 // char const ** 06048 // char const * const * 06049 // char * const * 06050 06051 QualifierCollector qs; 06052 const PointerType* PT; 06053 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 06054 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 06055 (QualType(qs.strip(PT->getPointeeType()), 0) == Context.CharTy)) { 06056 qs.removeConst(); 06057 mismatch = !qs.empty(); 06058 } 06059 } 06060 06061 if (mismatch) { 06062 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 06063 // TODO: suggest replacing given type with expected type 06064 FD->setInvalidDecl(true); 06065 } 06066 } 06067 06068 if (nparams == 1 && !FD->isInvalidDecl()) { 06069 Diag(FD->getLocation(), diag::warn_main_one_arg); 06070 } 06071 06072 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 06073 Diag(FD->getLocation(), diag::err_main_template_decl); 06074 FD->setInvalidDecl(); 06075 } 06076 } 06077 06078 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 06079 // FIXME: Need strict checking. In C89, we need to check for 06080 // any assignment, increment, decrement, function-calls, or 06081 // commas outside of a sizeof. In C99, it's the same list, 06082 // except that the aforementioned are allowed in unevaluated 06083 // expressions. Everything else falls under the 06084 // "may accept other forms of constant expressions" exception. 06085 // (We never end up here for C++, so the constant expression 06086 // rules there don't matter.) 06087 if (Init->isConstantInitializer(Context, false)) 06088 return false; 06089 Diag(Init->getExprLoc(), diag::err_init_element_not_constant) 06090 << Init->getSourceRange(); 06091 return true; 06092 } 06093 06094 namespace { 06095 // Visits an initialization expression to see if OrigDecl is evaluated in 06096 // its own initialization and throws a warning if it does. 06097 class SelfReferenceChecker 06098 : public EvaluatedExprVisitor<SelfReferenceChecker> { 06099 Sema &S; 06100 Decl *OrigDecl; 06101 bool isRecordType; 06102 bool isPODType; 06103 06104 public: 06105 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 06106 06107 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 06108 S(S), OrigDecl(OrigDecl) { 06109 isPODType = false; 06110 isRecordType = false; 06111 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 06112 isPODType = VD->getType().isPODType(S.Context); 06113 isRecordType = VD->getType()->isRecordType(); 06114 } 06115 } 06116 06117 // Sometimes, the expression passed in lacks the casts that are used 06118 // to determine which DeclRefExpr's to check. Assume that the casts 06119 // are present and continue visiting the expression. 06120 void HandleExpr(Expr *E) { 06121 // Skip checking T a = a where T is not a record type. Doing so is a 06122 // way to silence uninitialized warnings. 06123 if (isRecordType) 06124 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 06125 HandleDeclRefExpr(DRE); 06126 06127 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 06128 HandleValue(CO->getTrueExpr()); 06129 HandleValue(CO->getFalseExpr()); 06130 } 06131 06132 Visit(E); 06133 } 06134 06135 // For most expressions, the cast is directly above the DeclRefExpr. 06136 // For conditional operators, the cast can be outside the conditional 06137 // operator if both expressions are DeclRefExpr's. 06138 void HandleValue(Expr *E) { 06139 E = E->IgnoreParenImpCasts(); 06140 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 06141 HandleDeclRefExpr(DRE); 06142 return; 06143 } 06144 06145 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 06146 HandleValue(CO->getTrueExpr()); 06147 HandleValue(CO->getFalseExpr()); 06148 } 06149 } 06150 06151 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 06152 if ((!isRecordType && E->getCastKind() == CK_LValueToRValue) || 06153 (isRecordType && E->getCastKind() == CK_NoOp)) 06154 HandleValue(E->getSubExpr()); 06155 06156 Inherited::VisitImplicitCastExpr(E); 06157 } 06158 06159 void VisitMemberExpr(MemberExpr *E) { 06160 // Don't warn on arrays since they can be treated as pointers. 06161 if (E->getType()->canDecayToPointerType()) return; 06162 06163 ValueDecl *VD = E->getMemberDecl(); 06164 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(VD); 06165 if (isa<FieldDecl>(VD) || (MD && !MD->isStatic())) 06166 if (DeclRefExpr *DRE 06167 = dyn_cast<DeclRefExpr>(E->getBase()->IgnoreParenImpCasts())) { 06168 HandleDeclRefExpr(DRE); 06169 return; 06170 } 06171 06172 Inherited::VisitMemberExpr(E); 06173 } 06174 06175 void VisitUnaryOperator(UnaryOperator *E) { 06176 // For POD record types, addresses of its own members are well-defined. 06177 if (E->getOpcode() == UO_AddrOf && isRecordType && isPODType && 06178 isa<MemberExpr>(E->getSubExpr())) return; 06179 Inherited::VisitUnaryOperator(E); 06180 } 06181 06182 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 06183 06184 void HandleDeclRefExpr(DeclRefExpr *DRE) { 06185 Decl* ReferenceDecl = DRE->getDecl(); 06186 if (OrigDecl != ReferenceDecl) return; 06187 LookupResult Result(S, DRE->getNameInfo(), Sema::LookupOrdinaryName, 06188 Sema::NotForRedeclaration); 06189 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 06190 S.PDiag(diag::warn_uninit_self_reference_in_init) 06191 << Result.getLookupName() 06192 << OrigDecl->getLocation() 06193 << DRE->getSourceRange()); 06194 } 06195 }; 06196 } 06197 06198 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 06199 void Sema::CheckSelfReference(Decl* OrigDecl, Expr *E) { 06200 SelfReferenceChecker(*this, OrigDecl).HandleExpr(E); 06201 } 06202 06203 /// AddInitializerToDecl - Adds the initializer Init to the 06204 /// declaration dcl. If DirectInit is true, this is C++ direct 06205 /// initialization rather than copy initialization. 06206 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 06207 bool DirectInit, bool TypeMayContainAuto) { 06208 // If there is no declaration, there was an error parsing it. Just ignore 06209 // the initializer. 06210 if (RealDecl == 0 || RealDecl->isInvalidDecl()) 06211 return; 06212 06213 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 06214 // With declarators parsed the way they are, the parser cannot 06215 // distinguish between a normal initializer and a pure-specifier. 06216 // Thus this grotesque test. 06217 IntegerLiteral *IL; 06218 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 06219 Context.getCanonicalType(IL->getType()) == Context.IntTy) 06220 CheckPureMethod(Method, Init->getSourceRange()); 06221 else { 06222 Diag(Method->getLocation(), diag::err_member_function_initialization) 06223 << Method->getDeclName() << Init->getSourceRange(); 06224 Method->setInvalidDecl(); 06225 } 06226 return; 06227 } 06228 06229 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 06230 if (!VDecl) { 06231 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 06232 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 06233 RealDecl->setInvalidDecl(); 06234 return; 06235 } 06236 06237 // Check for self-references within variable initializers. 06238 // Variables declared within a function/method body are handled 06239 // by a dataflow analysis. 06240 if (!VDecl->hasLocalStorage() && !VDecl->isStaticLocal()) 06241 CheckSelfReference(RealDecl, Init); 06242 06243 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 06244 06245 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 06246 if (TypeMayContainAuto && VDecl->getType()->getContainedAutoType()) { 06247 Expr *DeduceInit = Init; 06248 // Initializer could be a C++ direct-initializer. Deduction only works if it 06249 // contains exactly one expression. 06250 if (CXXDirectInit) { 06251 if (CXXDirectInit->getNumExprs() == 0) { 06252 // It isn't possible to write this directly, but it is possible to 06253 // end up in this situation with "auto x(some_pack...);" 06254 Diag(CXXDirectInit->getLocStart(), 06255 diag::err_auto_var_init_no_expression) 06256 << VDecl->getDeclName() << VDecl->getType() 06257 << VDecl->getSourceRange(); 06258 RealDecl->setInvalidDecl(); 06259 return; 06260 } else if (CXXDirectInit->getNumExprs() > 1) { 06261 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 06262 diag::err_auto_var_init_multiple_expressions) 06263 << VDecl->getDeclName() << VDecl->getType() 06264 << VDecl->getSourceRange(); 06265 RealDecl->setInvalidDecl(); 06266 return; 06267 } else { 06268 DeduceInit = CXXDirectInit->getExpr(0); 06269 } 06270 } 06271 TypeSourceInfo *DeducedType = 0; 06272 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 06273 DAR_Failed) 06274 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 06275 if (!DeducedType) { 06276 RealDecl->setInvalidDecl(); 06277 return; 06278 } 06279 VDecl->setTypeSourceInfo(DeducedType); 06280 VDecl->setType(DeducedType->getType()); 06281 VDecl->ClearLinkageCache(); 06282 06283 // In ARC, infer lifetime. 06284 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 06285 VDecl->setInvalidDecl(); 06286 06287 // If this is a redeclaration, check that the type we just deduced matches 06288 // the previously declared type. 06289 if (VarDecl *Old = VDecl->getPreviousDecl()) 06290 MergeVarDeclTypes(VDecl, Old); 06291 } 06292 06293 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 06294 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 06295 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 06296 VDecl->setInvalidDecl(); 06297 return; 06298 } 06299 06300 if (!VDecl->getType()->isDependentType()) { 06301 // A definition must end up with a complete type, which means it must be 06302 // complete with the restriction that an array type might be completed by 06303 // the initializer; note that later code assumes this restriction. 06304 QualType BaseDeclType = VDecl->getType(); 06305 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 06306 BaseDeclType = Array->getElementType(); 06307 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 06308 diag::err_typecheck_decl_incomplete_type)) { 06309 RealDecl->setInvalidDecl(); 06310 return; 06311 } 06312 06313 // The variable can not have an abstract class type. 06314 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 06315 diag::err_abstract_type_in_decl, 06316 AbstractVariableType)) 06317 VDecl->setInvalidDecl(); 06318 } 06319 06320 const VarDecl *Def; 06321 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 06322 Diag(VDecl->getLocation(), diag::err_redefinition) 06323 << VDecl->getDeclName(); 06324 Diag(Def->getLocation(), diag::note_previous_definition); 06325 VDecl->setInvalidDecl(); 06326 return; 06327 } 06328 06329 const VarDecl* PrevInit = 0; 06330 if (getLangOpts().CPlusPlus) { 06331 // C++ [class.static.data]p4 06332 // If a static data member is of const integral or const 06333 // enumeration type, its declaration in the class definition can 06334 // specify a constant-initializer which shall be an integral 06335 // constant expression (5.19). In that case, the member can appear 06336 // in integral constant expressions. The member shall still be 06337 // defined in a namespace scope if it is used in the program and the 06338 // namespace scope definition shall not contain an initializer. 06339 // 06340 // We already performed a redefinition check above, but for static 06341 // data members we also need to check whether there was an in-class 06342 // declaration with an initializer. 06343 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 06344 Diag(VDecl->getLocation(), diag::err_redefinition) 06345 << VDecl->getDeclName(); 06346 Diag(PrevInit->getLocation(), diag::note_previous_definition); 06347 return; 06348 } 06349 06350 if (VDecl->hasLocalStorage()) 06351 getCurFunction()->setHasBranchProtectedScope(); 06352 06353 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 06354 VDecl->setInvalidDecl(); 06355 return; 06356 } 06357 } 06358 06359 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 06360 // a kernel function cannot be initialized." 06361 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 06362 Diag(VDecl->getLocation(), diag::err_local_cant_init); 06363 VDecl->setInvalidDecl(); 06364 return; 06365 } 06366 06367 // Get the decls type and save a reference for later, since 06368 // CheckInitializerTypes may change it. 06369 QualType DclT = VDecl->getType(), SavT = DclT; 06370 06371 // Top-level message sends default to 'id' when we're in a debugger 06372 // and we are assigning it to a variable of 'id' type. 06373 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCIdType()) 06374 if (Init->getType() == Context.UnknownAnyTy && isa<ObjCMessageExpr>(Init)) { 06375 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 06376 if (Result.isInvalid()) { 06377 VDecl->setInvalidDecl(); 06378 return; 06379 } 06380 Init = Result.take(); 06381 } 06382 06383 // Perform the initialization. 06384 if (!VDecl->isInvalidDecl()) { 06385 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 06386 InitializationKind Kind 06387 = DirectInit ? 06388 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 06389 Init->getLocStart(), 06390 Init->getLocEnd()) 06391 : InitializationKind::CreateDirectList( 06392 VDecl->getLocation()) 06393 : InitializationKind::CreateCopy(VDecl->getLocation(), 06394 Init->getLocStart()); 06395 06396 Expr **Args = &Init; 06397 unsigned NumArgs = 1; 06398 if (CXXDirectInit) { 06399 Args = CXXDirectInit->getExprs(); 06400 NumArgs = CXXDirectInit->getNumExprs(); 06401 } 06402 InitializationSequence InitSeq(*this, Entity, Kind, Args, NumArgs); 06403 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, 06404 MultiExprArg(*this, Args,NumArgs), 06405 &DclT); 06406 if (Result.isInvalid()) { 06407 VDecl->setInvalidDecl(); 06408 return; 06409 } 06410 06411 Init = Result.takeAs<Expr>(); 06412 } 06413 06414 // If the type changed, it means we had an incomplete type that was 06415 // completed by the initializer. For example: 06416 // int ary[] = { 1, 3, 5 }; 06417 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 06418 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 06419 VDecl->setType(DclT); 06420 06421 // Check any implicit conversions within the expression. 06422 CheckImplicitConversions(Init, VDecl->getLocation()); 06423 06424 if (!VDecl->isInvalidDecl()) 06425 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 06426 06427 Init = MaybeCreateExprWithCleanups(Init); 06428 // Attach the initializer to the decl. 06429 VDecl->setInit(Init); 06430 06431 if (VDecl->isLocalVarDecl()) { 06432 // C99 6.7.8p4: All the expressions in an initializer for an object that has 06433 // static storage duration shall be constant expressions or string literals. 06434 // C++ does not have this restriction. 06435 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl() && 06436 VDecl->getStorageClass() == SC_Static) 06437 CheckForConstantInitializer(Init, DclT); 06438 } else if (VDecl->isStaticDataMember() && 06439 VDecl->getLexicalDeclContext()->isRecord()) { 06440 // This is an in-class initialization for a static data member, e.g., 06441 // 06442 // struct S { 06443 // static const int value = 17; 06444 // }; 06445 06446 // C++ [class.mem]p4: 06447 // A member-declarator can contain a constant-initializer only 06448 // if it declares a static member (9.4) of const integral or 06449 // const enumeration type, see 9.4.2. 06450 // 06451 // C++11 [class.static.data]p3: 06452 // If a non-volatile const static data member is of integral or 06453 // enumeration type, its declaration in the class definition can 06454 // specify a brace-or-equal-initializer in which every initalizer-clause 06455 // that is an assignment-expression is a constant expression. A static 06456 // data member of literal type can be declared in the class definition 06457 // with the constexpr specifier; if so, its declaration shall specify a 06458 // brace-or-equal-initializer in which every initializer-clause that is 06459 // an assignment-expression is a constant expression. 06460 06461 // Do nothing on dependent types. 06462 if (DclT->isDependentType()) { 06463 06464 // Allow any 'static constexpr' members, whether or not they are of literal 06465 // type. We separately check that every constexpr variable is of literal 06466 // type. 06467 } else if (VDecl->isConstexpr()) { 06468 06469 // Require constness. 06470 } else if (!DclT.isConstQualified()) { 06471 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 06472 << Init->getSourceRange(); 06473 VDecl->setInvalidDecl(); 06474 06475 // We allow integer constant expressions in all cases. 06476 } else if (DclT->isIntegralOrEnumerationType()) { 06477 // Check whether the expression is a constant expression. 06478 SourceLocation Loc; 06479 if (getLangOpts().CPlusPlus0x && DclT.isVolatileQualified()) 06480 // In C++11, a non-constexpr const static data member with an 06481 // in-class initializer cannot be volatile. 06482 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 06483 else if (Init->isValueDependent()) 06484 ; // Nothing to check. 06485 else if (Init->isIntegerConstantExpr(Context, &Loc)) 06486 ; // Ok, it's an ICE! 06487 else if (Init->isEvaluatable(Context)) { 06488 // If we can constant fold the initializer through heroics, accept it, 06489 // but report this as a use of an extension for -pedantic. 06490 Diag(Loc, diag::ext_in_class_initializer_non_constant) 06491 << Init->getSourceRange(); 06492 } else { 06493 // Otherwise, this is some crazy unknown case. Report the issue at the 06494 // location provided by the isIntegerConstantExpr failed check. 06495 Diag(Loc, diag::err_in_class_initializer_non_constant) 06496 << Init->getSourceRange(); 06497 VDecl->setInvalidDecl(); 06498 } 06499 06500 // We allow foldable floating-point constants as an extension. 06501 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 06502 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 06503 << DclT << Init->getSourceRange(); 06504 if (getLangOpts().CPlusPlus0x) 06505 Diag(VDecl->getLocation(), 06506 diag::note_in_class_initializer_float_type_constexpr) 06507 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 06508 06509 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 06510 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 06511 << Init->getSourceRange(); 06512 VDecl->setInvalidDecl(); 06513 } 06514 06515 // Suggest adding 'constexpr' in C++11 for literal types. 06516 } else if (getLangOpts().CPlusPlus0x && DclT->isLiteralType()) { 06517 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 06518 << DclT << Init->getSourceRange() 06519 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 06520 VDecl->setConstexpr(true); 06521 06522 } else { 06523 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 06524 << DclT << Init->getSourceRange(); 06525 VDecl->setInvalidDecl(); 06526 } 06527 } else if (VDecl->isFileVarDecl()) { 06528 if (VDecl->getStorageClassAsWritten() == SC_Extern && 06529 (!getLangOpts().CPlusPlus || 06530 !Context.getBaseElementType(VDecl->getType()).isConstQualified())) 06531 Diag(VDecl->getLocation(), diag::warn_extern_init); 06532 06533 // C99 6.7.8p4. All file scoped initializers need to be constant. 06534 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 06535 CheckForConstantInitializer(Init, DclT); 06536 } 06537 06538 // We will represent direct-initialization similarly to copy-initialization: 06539 // int x(1); -as-> int x = 1; 06540 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 06541 // 06542 // Clients that want to distinguish between the two forms, can check for 06543 // direct initializer using VarDecl::getInitStyle(). 06544 // A major benefit is that clients that don't particularly care about which 06545 // exactly form was it (like the CodeGen) can handle both cases without 06546 // special case code. 06547 06548 // C++ 8.5p11: 06549 // The form of initialization (using parentheses or '=') is generally 06550 // insignificant, but does matter when the entity being initialized has a 06551 // class type. 06552 if (CXXDirectInit) { 06553 assert(DirectInit && "Call-style initializer must be direct init."); 06554 VDecl->setInitStyle(VarDecl::CallInit); 06555 } else if (DirectInit) { 06556 // This must be list-initialization. No other way is direct-initialization. 06557 VDecl->setInitStyle(VarDecl::ListInit); 06558 } 06559 06560 CheckCompleteVariableDeclaration(VDecl); 06561 } 06562 06563 /// ActOnInitializerError - Given that there was an error parsing an 06564 /// initializer for the given declaration, try to return to some form 06565 /// of sanity. 06566 void Sema::ActOnInitializerError(Decl *D) { 06567 // Our main concern here is re-establishing invariants like "a 06568 // variable's type is either dependent or complete". 06569 if (!D || D->isInvalidDecl()) return; 06570 06571 VarDecl *VD = dyn_cast<VarDecl>(D); 06572 if (!VD) return; 06573 06574 // Auto types are meaningless if we can't make sense of the initializer. 06575 if (ParsingInitForAutoVars.count(D)) { 06576 D->setInvalidDecl(); 06577 return; 06578 } 06579 06580 QualType Ty = VD->getType(); 06581 if (Ty->isDependentType()) return; 06582 06583 // Require a complete type. 06584 if (RequireCompleteType(VD->getLocation(), 06585 Context.getBaseElementType(Ty), 06586 diag::err_typecheck_decl_incomplete_type)) { 06587 VD->setInvalidDecl(); 06588 return; 06589 } 06590 06591 // Require an abstract type. 06592 if (RequireNonAbstractType(VD->getLocation(), Ty, 06593 diag::err_abstract_type_in_decl, 06594 AbstractVariableType)) { 06595 VD->setInvalidDecl(); 06596 return; 06597 } 06598 06599 // Don't bother complaining about constructors or destructors, 06600 // though. 06601 } 06602 06603 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 06604 bool TypeMayContainAuto) { 06605 // If there is no declaration, there was an error parsing it. Just ignore it. 06606 if (RealDecl == 0) 06607 return; 06608 06609 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 06610 QualType Type = Var->getType(); 06611 06612 // C++11 [dcl.spec.auto]p3 06613 if (TypeMayContainAuto && Type->getContainedAutoType()) { 06614 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 06615 << Var->getDeclName() << Type; 06616 Var->setInvalidDecl(); 06617 return; 06618 } 06619 06620 // C++11 [class.static.data]p3: A static data member can be declared with 06621 // the constexpr specifier; if so, its declaration shall specify 06622 // a brace-or-equal-initializer. 06623 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 06624 // the definition of a variable [...] or the declaration of a static data 06625 // member. 06626 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 06627 if (Var->isStaticDataMember()) 06628 Diag(Var->getLocation(), 06629 diag::err_constexpr_static_mem_var_requires_init) 06630 << Var->getDeclName(); 06631 else 06632 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 06633 Var->setInvalidDecl(); 06634 return; 06635 } 06636 06637 switch (Var->isThisDeclarationADefinition()) { 06638 case VarDecl::Definition: 06639 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 06640 break; 06641 06642 // We have an out-of-line definition of a static data member 06643 // that has an in-class initializer, so we type-check this like 06644 // a declaration. 06645 // 06646 // Fall through 06647 06648 case VarDecl::DeclarationOnly: 06649 // It's only a declaration. 06650 06651 // Block scope. C99 6.7p7: If an identifier for an object is 06652 // declared with no linkage (C99 6.2.2p6), the type for the 06653 // object shall be complete. 06654 if (!Type->isDependentType() && Var->isLocalVarDecl() && 06655 !Var->getLinkage() && !Var->isInvalidDecl() && 06656 RequireCompleteType(Var->getLocation(), Type, 06657 diag::err_typecheck_decl_incomplete_type)) 06658 Var->setInvalidDecl(); 06659 06660 // Make sure that the type is not abstract. 06661 if (!Type->isDependentType() && !Var->isInvalidDecl() && 06662 RequireNonAbstractType(Var->getLocation(), Type, 06663 diag::err_abstract_type_in_decl, 06664 AbstractVariableType)) 06665 Var->setInvalidDecl(); 06666 return; 06667 06668 case VarDecl::TentativeDefinition: 06669 // File scope. C99 6.9.2p2: A declaration of an identifier for an 06670 // object that has file scope without an initializer, and without a 06671 // storage-class specifier or with the storage-class specifier "static", 06672 // constitutes a tentative definition. Note: A tentative definition with 06673 // external linkage is valid (C99 6.2.2p5). 06674 if (!Var->isInvalidDecl()) { 06675 if (const IncompleteArrayType *ArrayT 06676 = Context.getAsIncompleteArrayType(Type)) { 06677 if (RequireCompleteType(Var->getLocation(), 06678 ArrayT->getElementType(), 06679 diag::err_illegal_decl_array_incomplete_type)) 06680 Var->setInvalidDecl(); 06681 } else if (Var->getStorageClass() == SC_Static) { 06682 // C99 6.9.2p3: If the declaration of an identifier for an object is 06683 // a tentative definition and has internal linkage (C99 6.2.2p3), the 06684 // declared type shall not be an incomplete type. 06685 // NOTE: code such as the following 06686 // static struct s; 06687 // struct s { int a; }; 06688 // is accepted by gcc. Hence here we issue a warning instead of 06689 // an error and we do not invalidate the static declaration. 06690 // NOTE: to avoid multiple warnings, only check the first declaration. 06691 if (Var->getPreviousDecl() == 0) 06692 RequireCompleteType(Var->getLocation(), Type, 06693 diag::ext_typecheck_decl_incomplete_type); 06694 } 06695 } 06696 06697 // Record the tentative definition; we're done. 06698 if (!Var->isInvalidDecl()) 06699 TentativeDefinitions.push_back(Var); 06700 return; 06701 } 06702 06703 // Provide a specific diagnostic for uninitialized variable 06704 // definitions with incomplete array type. 06705 if (Type->isIncompleteArrayType()) { 06706 Diag(Var->getLocation(), 06707 diag::err_typecheck_incomplete_array_needs_initializer); 06708 Var->setInvalidDecl(); 06709 return; 06710 } 06711 06712 // Provide a specific diagnostic for uninitialized variable 06713 // definitions with reference type. 06714 if (Type->isReferenceType()) { 06715 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 06716 << Var->getDeclName() 06717 << SourceRange(Var->getLocation(), Var->getLocation()); 06718 Var->setInvalidDecl(); 06719 return; 06720 } 06721 06722 // Do not attempt to type-check the default initializer for a 06723 // variable with dependent type. 06724 if (Type->isDependentType()) 06725 return; 06726 06727 if (Var->isInvalidDecl()) 06728 return; 06729 06730 if (RequireCompleteType(Var->getLocation(), 06731 Context.getBaseElementType(Type), 06732 diag::err_typecheck_decl_incomplete_type)) { 06733 Var->setInvalidDecl(); 06734 return; 06735 } 06736 06737 // The variable can not have an abstract class type. 06738 if (RequireNonAbstractType(Var->getLocation(), Type, 06739 diag::err_abstract_type_in_decl, 06740 AbstractVariableType)) { 06741 Var->setInvalidDecl(); 06742 return; 06743 } 06744 06745 // Check for jumps past the implicit initializer. C++0x 06746 // clarifies that this applies to a "variable with automatic 06747 // storage duration", not a "local variable". 06748 // C++11 [stmt.dcl]p3 06749 // A program that jumps from a point where a variable with automatic 06750 // storage duration is not in scope to a point where it is in scope is 06751 // ill-formed unless the variable has scalar type, class type with a 06752 // trivial default constructor and a trivial destructor, a cv-qualified 06753 // version of one of these types, or an array of one of the preceding 06754 // types and is declared without an initializer. 06755 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 06756 if (const RecordType *Record 06757 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 06758 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 06759 // Mark the function for further checking even if the looser rules of 06760 // C++11 do not require such checks, so that we can diagnose 06761 // incompatibilities with C++98. 06762 if (!CXXRecord->isPOD()) 06763 getCurFunction()->setHasBranchProtectedScope(); 06764 } 06765 } 06766 06767 // C++03 [dcl.init]p9: 06768 // If no initializer is specified for an object, and the 06769 // object is of (possibly cv-qualified) non-POD class type (or 06770 // array thereof), the object shall be default-initialized; if 06771 // the object is of const-qualified type, the underlying class 06772 // type shall have a user-declared default 06773 // constructor. Otherwise, if no initializer is specified for 06774 // a non- static object, the object and its subobjects, if 06775 // any, have an indeterminate initial value); if the object 06776 // or any of its subobjects are of const-qualified type, the 06777 // program is ill-formed. 06778 // C++0x [dcl.init]p11: 06779 // If no initializer is specified for an object, the object is 06780 // default-initialized; [...]. 06781 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 06782 InitializationKind Kind 06783 = InitializationKind::CreateDefault(Var->getLocation()); 06784 06785 InitializationSequence InitSeq(*this, Entity, Kind, 0, 0); 06786 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, 06787 MultiExprArg(*this, 0, 0)); 06788 if (Init.isInvalid()) 06789 Var->setInvalidDecl(); 06790 else if (Init.get()) { 06791 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 06792 // This is important for template substitution. 06793 Var->setInitStyle(VarDecl::CallInit); 06794 } 06795 06796 CheckCompleteVariableDeclaration(Var); 06797 } 06798 } 06799 06800 void Sema::ActOnCXXForRangeDecl(Decl *D) { 06801 VarDecl *VD = dyn_cast<VarDecl>(D); 06802 if (!VD) { 06803 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 06804 D->setInvalidDecl(); 06805 return; 06806 } 06807 06808 VD->setCXXForRangeDecl(true); 06809 06810 // for-range-declaration cannot be given a storage class specifier. 06811 int Error = -1; 06812 switch (VD->getStorageClassAsWritten()) { 06813 case SC_None: 06814 break; 06815 case SC_Extern: 06816 Error = 0; 06817 break; 06818 case SC_Static: 06819 Error = 1; 06820 break; 06821 case SC_PrivateExtern: 06822 Error = 2; 06823 break; 06824 case SC_Auto: 06825 Error = 3; 06826 break; 06827 case SC_Register: 06828 Error = 4; 06829 break; 06830 case SC_OpenCLWorkGroupLocal: 06831 llvm_unreachable("Unexpected storage class"); 06832 } 06833 if (VD->isConstexpr()) 06834 Error = 5; 06835 if (Error != -1) { 06836 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 06837 << VD->getDeclName() << Error; 06838 D->setInvalidDecl(); 06839 } 06840 } 06841 06842 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 06843 if (var->isInvalidDecl()) return; 06844 06845 // In ARC, don't allow jumps past the implicit initialization of a 06846 // local retaining variable. 06847 if (getLangOpts().ObjCAutoRefCount && 06848 var->hasLocalStorage()) { 06849 switch (var->getType().getObjCLifetime()) { 06850 case Qualifiers::OCL_None: 06851 case Qualifiers::OCL_ExplicitNone: 06852 case Qualifiers::OCL_Autoreleasing: 06853 break; 06854 06855 case Qualifiers::OCL_Weak: 06856 case Qualifiers::OCL_Strong: 06857 getCurFunction()->setHasBranchProtectedScope(); 06858 break; 06859 } 06860 } 06861 06862 // All the following checks are C++ only. 06863 if (!getLangOpts().CPlusPlus) return; 06864 06865 QualType baseType = Context.getBaseElementType(var->getType()); 06866 if (baseType->isDependentType()) return; 06867 06868 // __block variables might require us to capture a copy-initializer. 06869 if (var->hasAttr<BlocksAttr>()) { 06870 // It's currently invalid to ever have a __block variable with an 06871 // array type; should we diagnose that here? 06872 06873 // Regardless, we don't want to ignore array nesting when 06874 // constructing this copy. 06875 QualType type = var->getType(); 06876 06877 if (type->isStructureOrClassType()) { 06878 SourceLocation poi = var->getLocation(); 06879 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 06880 ExprResult result = 06881 PerformCopyInitialization( 06882 InitializedEntity::InitializeBlock(poi, type, false), 06883 poi, Owned(varRef)); 06884 if (!result.isInvalid()) { 06885 result = MaybeCreateExprWithCleanups(result); 06886 Expr *init = result.takeAs<Expr>(); 06887 Context.setBlockVarCopyInits(var, init); 06888 } 06889 } 06890 } 06891 06892 Expr *Init = var->getInit(); 06893 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 06894 06895 if (!var->getDeclContext()->isDependentContext() && Init) { 06896 if (IsGlobal && !var->isConstexpr() && 06897 getDiagnostics().getDiagnosticLevel(diag::warn_global_constructor, 06898 var->getLocation()) 06899 != DiagnosticsEngine::Ignored && 06900 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 06901 Diag(var->getLocation(), diag::warn_global_constructor) 06902 << Init->getSourceRange(); 06903 06904 if (var->isConstexpr()) { 06905 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 06906 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 06907 SourceLocation DiagLoc = var->getLocation(); 06908 // If the note doesn't add any useful information other than a source 06909 // location, fold it into the primary diagnostic. 06910 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 06911 diag::note_invalid_subexpr_in_const_expr) { 06912 DiagLoc = Notes[0].first; 06913 Notes.clear(); 06914 } 06915 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 06916 << var << Init->getSourceRange(); 06917 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 06918 Diag(Notes[I].first, Notes[I].second); 06919 } 06920 } else if (var->isUsableInConstantExpressions(Context)) { 06921 // Check whether the initializer of a const variable of integral or 06922 // enumeration type is an ICE now, since we can't tell whether it was 06923 // initialized by a constant expression if we check later. 06924 var->checkInitIsICE(); 06925 } 06926 } 06927 06928 // Require the destructor. 06929 if (const RecordType *recordType = baseType->getAs<RecordType>()) 06930 FinalizeVarWithDestructor(var, recordType); 06931 } 06932 06933 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 06934 /// any semantic actions necessary after any initializer has been attached. 06935 void 06936 Sema::FinalizeDeclaration(Decl *ThisDecl) { 06937 // Note that we are no longer parsing the initializer for this declaration. 06938 ParsingInitForAutoVars.erase(ThisDecl); 06939 } 06940 06941 Sema::DeclGroupPtrTy 06942 Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 06943 Decl **Group, unsigned NumDecls) { 06944 SmallVector<Decl*, 8> Decls; 06945 06946 if (DS.isTypeSpecOwned()) 06947 Decls.push_back(DS.getRepAsDecl()); 06948 06949 for (unsigned i = 0; i != NumDecls; ++i) 06950 if (Decl *D = Group[i]) 06951 Decls.push_back(D); 06952 06953 return BuildDeclaratorGroup(Decls.data(), Decls.size(), 06954 DS.getTypeSpecType() == DeclSpec::TST_auto); 06955 } 06956 06957 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 06958 /// group, performing any necessary semantic checking. 06959 Sema::DeclGroupPtrTy 06960 Sema::BuildDeclaratorGroup(Decl **Group, unsigned NumDecls, 06961 bool TypeMayContainAuto) { 06962 // C++0x [dcl.spec.auto]p7: 06963 // If the type deduced for the template parameter U is not the same in each 06964 // deduction, the program is ill-formed. 06965 // FIXME: When initializer-list support is added, a distinction is needed 06966 // between the deduced type U and the deduced type which 'auto' stands for. 06967 // auto a = 0, b = { 1, 2, 3 }; 06968 // is legal because the deduced type U is 'int' in both cases. 06969 if (TypeMayContainAuto && NumDecls > 1) { 06970 QualType Deduced; 06971 CanQualType DeducedCanon; 06972 VarDecl *DeducedDecl = 0; 06973 for (unsigned i = 0; i != NumDecls; ++i) { 06974 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 06975 AutoType *AT = D->getType()->getContainedAutoType(); 06976 // Don't reissue diagnostics when instantiating a template. 06977 if (AT && D->isInvalidDecl()) 06978 break; 06979 if (AT && AT->isDeduced()) { 06980 QualType U = AT->getDeducedType(); 06981 CanQualType UCanon = Context.getCanonicalType(U); 06982 if (Deduced.isNull()) { 06983 Deduced = U; 06984 DeducedCanon = UCanon; 06985 DeducedDecl = D; 06986 } else if (DeducedCanon != UCanon) { 06987 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 06988 diag::err_auto_different_deductions) 06989 << Deduced << DeducedDecl->getDeclName() 06990 << U << D->getDeclName() 06991 << DeducedDecl->getInit()->getSourceRange() 06992 << D->getInit()->getSourceRange(); 06993 D->setInvalidDecl(); 06994 break; 06995 } 06996 } 06997 } 06998 } 06999 } 07000 07001 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, NumDecls)); 07002 } 07003 07004 07005 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 07006 /// to introduce parameters into function prototype scope. 07007 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 07008 const DeclSpec &DS = D.getDeclSpec(); 07009 07010 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 07011 // C++03 [dcl.stc]p2 also permits 'auto'. 07012 VarDecl::StorageClass StorageClass = SC_None; 07013 VarDecl::StorageClass StorageClassAsWritten = SC_None; 07014 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 07015 StorageClass = SC_Register; 07016 StorageClassAsWritten = SC_Register; 07017 } else if (getLangOpts().CPlusPlus && 07018 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 07019 StorageClass = SC_Auto; 07020 StorageClassAsWritten = SC_Auto; 07021 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 07022 Diag(DS.getStorageClassSpecLoc(), 07023 diag::err_invalid_storage_class_in_func_decl); 07024 D.getMutableDeclSpec().ClearStorageClassSpecs(); 07025 } 07026 07027 if (D.getDeclSpec().isThreadSpecified()) 07028 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 07029 if (D.getDeclSpec().isConstexprSpecified()) 07030 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 07031 << 0; 07032 07033 DiagnoseFunctionSpecifiers(D); 07034 07035 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 07036 QualType parmDeclType = TInfo->getType(); 07037 07038 if (getLangOpts().CPlusPlus) { 07039 // Check that there are no default arguments inside the type of this 07040 // parameter. 07041 CheckExtraCXXDefaultArguments(D); 07042 07043 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 07044 if (D.getCXXScopeSpec().isSet()) { 07045 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 07046 << D.getCXXScopeSpec().getRange(); 07047 D.getCXXScopeSpec().clear(); 07048 } 07049 } 07050 07051 // Ensure we have a valid name 07052 IdentifierInfo *II = 0; 07053 if (D.hasName()) { 07054 II = D.getIdentifier(); 07055 if (!II) { 07056 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 07057 << GetNameForDeclarator(D).getName().getAsString(); 07058 D.setInvalidType(true); 07059 } 07060 } 07061 07062 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 07063 if (II) { 07064 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 07065 ForRedeclaration); 07066 LookupName(R, S); 07067 if (R.isSingleResult()) { 07068 NamedDecl *PrevDecl = R.getFoundDecl(); 07069 if (PrevDecl->isTemplateParameter()) { 07070 // Maybe we will complain about the shadowed template parameter. 07071 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 07072 // Just pretend that we didn't see the previous declaration. 07073 PrevDecl = 0; 07074 } else if (S->isDeclScope(PrevDecl)) { 07075 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 07076 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 07077 07078 // Recover by removing the name 07079 II = 0; 07080 D.SetIdentifier(0, D.getIdentifierLoc()); 07081 D.setInvalidType(true); 07082 } 07083 } 07084 } 07085 07086 // Temporarily put parameter variables in the translation unit, not 07087 // the enclosing context. This prevents them from accidentally 07088 // looking like class members in C++. 07089 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 07090 D.getLocStart(), 07091 D.getIdentifierLoc(), II, 07092 parmDeclType, TInfo, 07093 StorageClass, StorageClassAsWritten); 07094 07095 if (D.isInvalidType()) 07096 New->setInvalidDecl(); 07097 07098 assert(S->isFunctionPrototypeScope()); 07099 assert(S->getFunctionPrototypeDepth() >= 1); 07100 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 07101 S->getNextFunctionPrototypeIndex()); 07102 07103 // Add the parameter declaration into this scope. 07104 S->AddDecl(New); 07105 if (II) 07106 IdResolver.AddDecl(New); 07107 07108 ProcessDeclAttributes(S, New, D); 07109 07110 if (D.getDeclSpec().isModulePrivateSpecified()) 07111 Diag(New->getLocation(), diag::err_module_private_local) 07112 << 1 << New->getDeclName() 07113 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 07114 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 07115 07116 if (New->hasAttr<BlocksAttr>()) { 07117 Diag(New->getLocation(), diag::err_block_on_nonlocal); 07118 } 07119 return New; 07120 } 07121 07122 /// \brief Synthesizes a variable for a parameter arising from a 07123 /// typedef. 07124 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 07125 SourceLocation Loc, 07126 QualType T) { 07127 /* FIXME: setting StartLoc == Loc. 07128 Would it be worth to modify callers so as to provide proper source 07129 location for the unnamed parameters, embedding the parameter's type? */ 07130 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, 0, 07131 T, Context.getTrivialTypeSourceInfo(T, Loc), 07132 SC_None, SC_None, 0); 07133 Param->setImplicit(); 07134 return Param; 07135 } 07136 07137 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 07138 ParmVarDecl * const *ParamEnd) { 07139 // Don't diagnose unused-parameter errors in template instantiations; we 07140 // will already have done so in the template itself. 07141 if (!ActiveTemplateInstantiations.empty()) 07142 return; 07143 07144 for (; Param != ParamEnd; ++Param) { 07145 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 07146 !(*Param)->hasAttr<UnusedAttr>()) { 07147 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 07148 << (*Param)->getDeclName(); 07149 } 07150 } 07151 } 07152 07153 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 07154 ParmVarDecl * const *ParamEnd, 07155 QualType ReturnTy, 07156 NamedDecl *D) { 07157 if (LangOpts.NumLargeByValueCopy == 0) // No check. 07158 return; 07159 07160 // Warn if the return value is pass-by-value and larger than the specified 07161 // threshold. 07162 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 07163 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 07164 if (Size > LangOpts.NumLargeByValueCopy) 07165 Diag(D->getLocation(), diag::warn_return_value_size) 07166 << D->getDeclName() << Size; 07167 } 07168 07169 // Warn if any parameter is pass-by-value and larger than the specified 07170 // threshold. 07171 for (; Param != ParamEnd; ++Param) { 07172 QualType T = (*Param)->getType(); 07173 if (T->isDependentType() || !T.isPODType(Context)) 07174 continue; 07175 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 07176 if (Size > LangOpts.NumLargeByValueCopy) 07177 Diag((*Param)->getLocation(), diag::warn_parameter_size) 07178 << (*Param)->getDeclName() << Size; 07179 } 07180 } 07181 07182 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 07183 SourceLocation NameLoc, IdentifierInfo *Name, 07184 QualType T, TypeSourceInfo *TSInfo, 07185 VarDecl::StorageClass StorageClass, 07186 VarDecl::StorageClass StorageClassAsWritten) { 07187 // In ARC, infer a lifetime qualifier for appropriate parameter types. 07188 if (getLangOpts().ObjCAutoRefCount && 07189 T.getObjCLifetime() == Qualifiers::OCL_None && 07190 T->isObjCLifetimeType()) { 07191 07192 Qualifiers::ObjCLifetime lifetime; 07193 07194 // Special cases for arrays: 07195 // - if it's const, use __unsafe_unretained 07196 // - otherwise, it's an error 07197 if (T->isArrayType()) { 07198 if (!T.isConstQualified()) { 07199 DelayedDiagnostics.add( 07200 sema::DelayedDiagnostic::makeForbiddenType( 07201 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 07202 } 07203 lifetime = Qualifiers::OCL_ExplicitNone; 07204 } else { 07205 lifetime = T->getObjCARCImplicitLifetime(); 07206 } 07207 T = Context.getLifetimeQualifiedType(T, lifetime); 07208 } 07209 07210 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 07211 Context.getAdjustedParameterType(T), 07212 TSInfo, 07213 StorageClass, StorageClassAsWritten, 07214 0); 07215 07216 // Parameters can not be abstract class types. 07217 // For record types, this is done by the AbstractClassUsageDiagnoser once 07218 // the class has been completely parsed. 07219 if (!CurContext->isRecord() && 07220 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 07221 AbstractParamType)) 07222 New->setInvalidDecl(); 07223 07224 // Parameter declarators cannot be interface types. All ObjC objects are 07225 // passed by reference. 07226 if (T->isObjCObjectType()) { 07227 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 07228 Diag(NameLoc, 07229 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 07230 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 07231 T = Context.getObjCObjectPointerType(T); 07232 New->setType(T); 07233 } 07234 07235 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 07236 // duration shall not be qualified by an address-space qualifier." 07237 // Since all parameters have automatic store duration, they can not have 07238 // an address space. 07239 if (T.getAddressSpace() != 0) { 07240 Diag(NameLoc, diag::err_arg_with_address_space); 07241 New->setInvalidDecl(); 07242 } 07243 07244 return New; 07245 } 07246 07247 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 07248 SourceLocation LocAfterDecls) { 07249 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 07250 07251 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 07252 // for a K&R function. 07253 if (!FTI.hasPrototype) { 07254 for (int i = FTI.NumArgs; i != 0; /* decrement in loop */) { 07255 --i; 07256 if (FTI.ArgInfo[i].Param == 0) { 07257 SmallString<256> Code; 07258 llvm::raw_svector_ostream(Code) << " int " 07259 << FTI.ArgInfo[i].Ident->getName() 07260 << ";\n"; 07261 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared) 07262 << FTI.ArgInfo[i].Ident 07263 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 07264 07265 // Implicitly declare the argument as type 'int' for lack of a better 07266 // type. 07267 AttributeFactory attrs; 07268 DeclSpec DS(attrs); 07269 const char* PrevSpec; // unused 07270 unsigned DiagID; // unused 07271 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc, 07272 PrevSpec, DiagID); 07273 Declarator ParamD(DS, Declarator::KNRTypeListContext); 07274 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc); 07275 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD); 07276 } 07277 } 07278 } 07279 } 07280 07281 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 07282 assert(getCurFunctionDecl() == 0 && "Function parsing confused"); 07283 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 07284 Scope *ParentScope = FnBodyScope->getParent(); 07285 07286 D.setFunctionDefinitionKind(FDK_Definition); 07287 Decl *DP = HandleDeclarator(ParentScope, D, 07288 MultiTemplateParamsArg(*this)); 07289 return ActOnStartOfFunctionDef(FnBodyScope, DP); 07290 } 07291 07292 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD) { 07293 // Don't warn about invalid declarations. 07294 if (FD->isInvalidDecl()) 07295 return false; 07296 07297 // Or declarations that aren't global. 07298 if (!FD->isGlobal()) 07299 return false; 07300 07301 // Don't warn about C++ member functions. 07302 if (isa<CXXMethodDecl>(FD)) 07303 return false; 07304 07305 // Don't warn about 'main'. 07306 if (FD->isMain()) 07307 return false; 07308 07309 // Don't warn about inline functions. 07310 if (FD->isInlined()) 07311 return false; 07312 07313 // Don't warn about function templates. 07314 if (FD->getDescribedFunctionTemplate()) 07315 return false; 07316 07317 // Don't warn about function template specializations. 07318 if (FD->isFunctionTemplateSpecialization()) 07319 return false; 07320 07321 bool MissingPrototype = true; 07322 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 07323 Prev; Prev = Prev->getPreviousDecl()) { 07324 // Ignore any declarations that occur in function or method 07325 // scope, because they aren't visible from the header. 07326 if (Prev->getDeclContext()->isFunctionOrMethod()) 07327 continue; 07328 07329 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 07330 break; 07331 } 07332 07333 return MissingPrototype; 07334 } 07335 07336 void Sema::CheckForFunctionRedefinition(FunctionDecl *FD) { 07337 // Don't complain if we're in GNU89 mode and the previous definition 07338 // was an extern inline function. 07339 const FunctionDecl *Definition; 07340 if (FD->isDefined(Definition) && 07341 !canRedefineFunction(Definition, getLangOpts())) { 07342 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 07343 Definition->getStorageClass() == SC_Extern) 07344 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 07345 << FD->getDeclName() << getLangOpts().CPlusPlus; 07346 else 07347 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 07348 Diag(Definition->getLocation(), diag::note_previous_definition); 07349 } 07350 } 07351 07352 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 07353 // Clear the last template instantiation error context. 07354 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 07355 07356 if (!D) 07357 return D; 07358 FunctionDecl *FD = 0; 07359 07360 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 07361 FD = FunTmpl->getTemplatedDecl(); 07362 else 07363 FD = cast<FunctionDecl>(D); 07364 07365 // Enter a new function scope 07366 PushFunctionScope(); 07367 07368 // See if this is a redefinition. 07369 if (!FD->isLateTemplateParsed()) 07370 CheckForFunctionRedefinition(FD); 07371 07372 // Builtin functions cannot be defined. 07373 if (unsigned BuiltinID = FD->getBuiltinID()) { 07374 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 07375 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 07376 FD->setInvalidDecl(); 07377 } 07378 } 07379 07380 // The return type of a function definition must be complete 07381 // (C99 6.9.1p3, C++ [dcl.fct]p6). 07382 QualType ResultType = FD->getResultType(); 07383 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 07384 !FD->isInvalidDecl() && 07385 RequireCompleteType(FD->getLocation(), ResultType, 07386 diag::err_func_def_incomplete_result)) 07387 FD->setInvalidDecl(); 07388 07389 // GNU warning -Wmissing-prototypes: 07390 // Warn if a global function is defined without a previous 07391 // prototype declaration. This warning is issued even if the 07392 // definition itself provides a prototype. The aim is to detect 07393 // global functions that fail to be declared in header files. 07394 if (ShouldWarnAboutMissingPrototype(FD)) 07395 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 07396 07397 if (FnBodyScope) 07398 PushDeclContext(FnBodyScope, FD); 07399 07400 // Check the validity of our function parameters 07401 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 07402 /*CheckParameterNames=*/true); 07403 07404 // Introduce our parameters into the function scope 07405 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) { 07406 ParmVarDecl *Param = FD->getParamDecl(p); 07407 Param->setOwningFunction(FD); 07408 07409 // If this has an identifier, add it to the scope stack. 07410 if (Param->getIdentifier() && FnBodyScope) { 07411 CheckShadow(FnBodyScope, Param); 07412 07413 PushOnScopeChains(Param, FnBodyScope); 07414 } 07415 } 07416 07417 // If we had any tags defined in the function prototype, 07418 // introduce them into the function scope. 07419 if (FnBodyScope) { 07420 for (llvm::ArrayRef<NamedDecl*>::iterator I = FD->getDeclsInPrototypeScope().begin(), 07421 E = FD->getDeclsInPrototypeScope().end(); I != E; ++I) { 07422 NamedDecl *D = *I; 07423 07424 // Some of these decls (like enums) may have been pinned to the translation unit 07425 // for lack of a real context earlier. If so, remove from the translation unit 07426 // and reattach to the current context. 07427 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 07428 // Is the decl actually in the context? 07429 for (DeclContext::decl_iterator DI = Context.getTranslationUnitDecl()->decls_begin(), 07430 DE = Context.getTranslationUnitDecl()->decls_end(); DI != DE; ++DI) { 07431 if (*DI == D) { 07432 Context.getTranslationUnitDecl()->removeDecl(D); 07433 break; 07434 } 07435 } 07436 // Either way, reassign the lexical decl context to our FunctionDecl. 07437 D->setLexicalDeclContext(CurContext); 07438 } 07439 07440 // If the decl has a non-null name, make accessible in the current scope. 07441 if (!D->getName().empty()) 07442 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 07443 07444 // Similarly, dive into enums and fish their constants out, making them 07445 // accessible in this scope. 07446 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 07447 for (EnumDecl::enumerator_iterator EI = ED->enumerator_begin(), 07448 EE = ED->enumerator_end(); EI != EE; ++EI) 07449 PushOnScopeChains(&*EI, FnBodyScope, /*AddToContext=*/false); 07450 } 07451 } 07452 } 07453 07454 // Ensure that the function's exception specification is instantiated. 07455 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 07456 ResolveExceptionSpec(D->getLocation(), FPT); 07457 07458 // Checking attributes of current function definition 07459 // dllimport attribute. 07460 DLLImportAttr *DA = FD->getAttr<DLLImportAttr>(); 07461 if (DA && (!FD->getAttr<DLLExportAttr>())) { 07462 // dllimport attribute cannot be directly applied to definition. 07463 // Microsoft accepts dllimport for functions defined within class scope. 07464 if (!DA->isInherited() && 07465 !(LangOpts.MicrosoftExt && FD->getLexicalDeclContext()->isRecord())) { 07466 Diag(FD->getLocation(), 07467 diag::err_attribute_can_be_applied_only_to_symbol_declaration) 07468 << "dllimport"; 07469 FD->setInvalidDecl(); 07470 return FD; 07471 } 07472 07473 // Visual C++ appears to not think this is an issue, so only issue 07474 // a warning when Microsoft extensions are disabled. 07475 if (!LangOpts.MicrosoftExt) { 07476 // If a symbol previously declared dllimport is later defined, the 07477 // attribute is ignored in subsequent references, and a warning is 07478 // emitted. 07479 Diag(FD->getLocation(), 07480 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 07481 << FD->getName() << "dllimport"; 07482 } 07483 } 07484 return FD; 07485 } 07486 07487 /// \brief Given the set of return statements within a function body, 07488 /// compute the variables that are subject to the named return value 07489 /// optimization. 07490 /// 07491 /// Each of the variables that is subject to the named return value 07492 /// optimization will be marked as NRVO variables in the AST, and any 07493 /// return statement that has a marked NRVO variable as its NRVO candidate can 07494 /// use the named return value optimization. 07495 /// 07496 /// This function applies a very simplistic algorithm for NRVO: if every return 07497 /// statement in the function has the same NRVO candidate, that candidate is 07498 /// the NRVO variable. 07499 /// 07500 /// FIXME: Employ a smarter algorithm that accounts for multiple return 07501 /// statements and the lifetimes of the NRVO candidates. We should be able to 07502 /// find a maximal set of NRVO variables. 07503 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 07504 ReturnStmt **Returns = Scope->Returns.data(); 07505 07506 const VarDecl *NRVOCandidate = 0; 07507 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 07508 if (!Returns[I]->getNRVOCandidate()) 07509 return; 07510 07511 if (!NRVOCandidate) 07512 NRVOCandidate = Returns[I]->getNRVOCandidate(); 07513 else if (NRVOCandidate != Returns[I]->getNRVOCandidate()) 07514 return; 07515 } 07516 07517 if (NRVOCandidate) 07518 const_cast<VarDecl*>(NRVOCandidate)->setNRVOVariable(true); 07519 } 07520 07521 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 07522 return ActOnFinishFunctionBody(D, move(BodyArg), false); 07523 } 07524 07525 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 07526 bool IsInstantiation) { 07527 FunctionDecl *FD = 0; 07528 FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(dcl); 07529 if (FunTmpl) 07530 FD = FunTmpl->getTemplatedDecl(); 07531 else 07532 FD = dyn_cast_or_null<FunctionDecl>(dcl); 07533 07534 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 07535 sema::AnalysisBasedWarnings::Policy *ActivePolicy = 0; 07536 07537 if (FD) { 07538 FD->setBody(Body); 07539 07540 // If the function implicitly returns zero (like 'main') or is naked, 07541 // don't complain about missing return statements. 07542 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 07543 WP.disableCheckFallThrough(); 07544 07545 // MSVC permits the use of pure specifier (=0) on function definition, 07546 // defined at class scope, warn about this non standard construct. 07547 if (getLangOpts().MicrosoftExt && FD->isPure()) 07548 Diag(FD->getLocation(), diag::warn_pure_function_definition); 07549 07550 if (!FD->isInvalidDecl()) { 07551 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 07552 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 07553 FD->getResultType(), FD); 07554 07555 // If this is a constructor, we need a vtable. 07556 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 07557 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 07558 07559 computeNRVO(Body, getCurFunction()); 07560 } 07561 07562 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 07563 "Function parsing confused"); 07564 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 07565 assert(MD == getCurMethodDecl() && "Method parsing confused"); 07566 MD->setBody(Body); 07567 if (Body) 07568 MD->setEndLoc(Body->getLocEnd()); 07569 if (!MD->isInvalidDecl()) { 07570 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 07571 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 07572 MD->getResultType(), MD); 07573 07574 if (Body) 07575 computeNRVO(Body, getCurFunction()); 07576 } 07577 if (ObjCShouldCallSuperDealloc) { 07578 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_dealloc); 07579 ObjCShouldCallSuperDealloc = false; 07580 } 07581 if (ObjCShouldCallSuperFinalize) { 07582 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_finalize); 07583 ObjCShouldCallSuperFinalize = false; 07584 } 07585 } else { 07586 return 0; 07587 } 07588 07589 assert(!ObjCShouldCallSuperDealloc && "This should only be set for " 07590 "ObjC methods, which should have been handled in the block above."); 07591 assert(!ObjCShouldCallSuperFinalize && "This should only be set for " 07592 "ObjC methods, which should have been handled in the block above."); 07593 07594 // Verify and clean out per-function state. 07595 if (Body) { 07596 // C++ constructors that have function-try-blocks can't have return 07597 // statements in the handlers of that block. (C++ [except.handle]p14) 07598 // Verify this. 07599 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 07600 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 07601 07602 // Verify that gotos and switch cases don't jump into scopes illegally. 07603 if (getCurFunction()->NeedsScopeChecking() && 07604 !dcl->isInvalidDecl() && 07605 !hasAnyUnrecoverableErrorsInThisFunction()) 07606 DiagnoseInvalidJumps(Body); 07607 07608 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 07609 if (!Destructor->getParent()->isDependentType()) 07610 CheckDestructor(Destructor); 07611 07612 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 07613 Destructor->getParent()); 07614 } 07615 07616 // If any errors have occurred, clear out any temporaries that may have 07617 // been leftover. This ensures that these temporaries won't be picked up for 07618 // deletion in some later function. 07619 if (PP.getDiagnostics().hasErrorOccurred() || 07620 PP.getDiagnostics().getSuppressAllDiagnostics()) { 07621 DiscardCleanupsInEvaluationContext(); 07622 } else if (!isa<FunctionTemplateDecl>(dcl)) { 07623 // Since the body is valid, issue any analysis-based warnings that are 07624 // enabled. 07625 ActivePolicy = &WP; 07626 } 07627 07628 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 07629 (!CheckConstexprFunctionDecl(FD) || 07630 !CheckConstexprFunctionBody(FD, Body))) 07631 FD->setInvalidDecl(); 07632 07633 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 07634 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 07635 assert(MaybeODRUseExprs.empty() && 07636 "Leftover expressions for odr-use checking"); 07637 } 07638 07639 if (!IsInstantiation) 07640 PopDeclContext(); 07641 07642 PopFunctionScopeInfo(ActivePolicy, dcl); 07643 07644 // If any errors have occurred, clear out any temporaries that may have 07645 // been leftover. This ensures that these temporaries won't be picked up for 07646 // deletion in some later function. 07647 if (getDiagnostics().hasErrorOccurred()) { 07648 DiscardCleanupsInEvaluationContext(); 07649 } 07650 07651 return dcl; 07652 } 07653 07654 07655 /// When we finish delayed parsing of an attribute, we must attach it to the 07656 /// relevant Decl. 07657 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 07658 ParsedAttributes &Attrs) { 07659 // Always attach attributes to the underlying decl. 07660 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 07661 D = TD->getTemplatedDecl(); 07662 ProcessDeclAttributeList(S, D, Attrs.getList()); 07663 07664 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 07665 if (Method->isStatic()) 07666 checkThisInStaticMemberFunctionAttributes(Method); 07667 } 07668 07669 07670 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 07671 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 07672 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 07673 IdentifierInfo &II, Scope *S) { 07674 // Before we produce a declaration for an implicitly defined 07675 // function, see whether there was a locally-scoped declaration of 07676 // this name as a function or variable. If so, use that 07677 // (non-visible) declaration, and complain about it. 07678 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 07679 = findLocallyScopedExternalDecl(&II); 07680 if (Pos != LocallyScopedExternalDecls.end()) { 07681 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second; 07682 Diag(Pos->second->getLocation(), diag::note_previous_declaration); 07683 return Pos->second; 07684 } 07685 07686 // Extension in C99. Legal in C90, but warn about it. 07687 unsigned diag_id; 07688 if (II.getName().startswith("__builtin_")) 07689 diag_id = diag::warn_builtin_unknown; 07690 else if (getLangOpts().C99) 07691 diag_id = diag::ext_implicit_function_decl; 07692 else 07693 diag_id = diag::warn_implicit_function_decl; 07694 Diag(Loc, diag_id) << &II; 07695 07696 // Because typo correction is expensive, only do it if the implicit 07697 // function declaration is going to be treated as an error. 07698 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 07699 TypoCorrection Corrected; 07700 DeclFilterCCC<FunctionDecl> Validator; 07701 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 07702 LookupOrdinaryName, S, 0, Validator))) { 07703 std::string CorrectedStr = Corrected.getAsString(getLangOpts()); 07704 std::string CorrectedQuotedStr = Corrected.getQuoted(getLangOpts()); 07705 FunctionDecl *Func = Corrected.getCorrectionDeclAs<FunctionDecl>(); 07706 07707 Diag(Loc, diag::note_function_suggestion) << CorrectedQuotedStr 07708 << FixItHint::CreateReplacement(Loc, CorrectedStr); 07709 07710 if (Func->getLocation().isValid() 07711 && !II.getName().startswith("__builtin_")) 07712 Diag(Func->getLocation(), diag::note_previous_decl) 07713 << CorrectedQuotedStr; 07714 } 07715 } 07716 07717 // Set a Declarator for the implicit definition: int foo(); 07718 const char *Dummy; 07719 AttributeFactory attrFactory; 07720 DeclSpec DS(attrFactory); 07721 unsigned DiagID; 07722 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID); 07723 (void)Error; // Silence warning. 07724 assert(!Error && "Error setting up implicit decl!"); 07725 Declarator D(DS, Declarator::BlockContext); 07726 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(), 0, 07727 0, 0, true, SourceLocation(), 07728 SourceLocation(), SourceLocation(), 07729 SourceLocation(), 07730 EST_None, SourceLocation(), 07731 0, 0, 0, 0, Loc, Loc, D), 07732 DS.getAttributes(), 07733 SourceLocation()); 07734 D.SetIdentifier(&II, Loc); 07735 07736 // Insert this function into translation-unit scope. 07737 07738 DeclContext *PrevDC = CurContext; 07739 CurContext = Context.getTranslationUnitDecl(); 07740 07741 FunctionDecl *FD = dyn_cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 07742 FD->setImplicit(); 07743 07744 CurContext = PrevDC; 07745 07746 AddKnownFunctionAttributes(FD); 07747 07748 return FD; 07749 } 07750 07751 /// \brief Adds any function attributes that we know a priori based on 07752 /// the declaration of this function. 07753 /// 07754 /// These attributes can apply both to implicitly-declared builtins 07755 /// (like __builtin___printf_chk) or to library-declared functions 07756 /// like NSLog or printf. 07757 /// 07758 /// We need to check for duplicate attributes both here and where user-written 07759 /// attributes are applied to declarations. 07760 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 07761 if (FD->isInvalidDecl()) 07762 return; 07763 07764 // If this is a built-in function, map its builtin attributes to 07765 // actual attributes. 07766 if (unsigned BuiltinID = FD->getBuiltinID()) { 07767 // Handle printf-formatting attributes. 07768 unsigned FormatIdx; 07769 bool HasVAListArg; 07770 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 07771 if (!FD->getAttr<FormatAttr>()) { 07772 const char *fmt = "printf"; 07773 unsigned int NumParams = FD->getNumParams(); 07774 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 07775 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 07776 fmt = "NSString"; 07777 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 07778 fmt, FormatIdx+1, 07779 HasVAListArg ? 0 : FormatIdx+2)); 07780 } 07781 } 07782 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 07783 HasVAListArg)) { 07784 if (!FD->getAttr<FormatAttr>()) 07785 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 07786 "scanf", FormatIdx+1, 07787 HasVAListArg ? 0 : FormatIdx+2)); 07788 } 07789 07790 // Mark const if we don't care about errno and that is the only 07791 // thing preventing the function from being const. This allows 07792 // IRgen to use LLVM intrinsics for such functions. 07793 if (!getLangOpts().MathErrno && 07794 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 07795 if (!FD->getAttr<ConstAttr>()) 07796 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 07797 } 07798 07799 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 07800 !FD->getAttr<ReturnsTwiceAttr>()) 07801 FD->addAttr(::new (Context) ReturnsTwiceAttr(FD->getLocation(), Context)); 07802 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->getAttr<NoThrowAttr>()) 07803 FD->addAttr(::new (Context) NoThrowAttr(FD->getLocation(), Context)); 07804 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->getAttr<ConstAttr>()) 07805 FD->addAttr(::new (Context) ConstAttr(FD->getLocation(), Context)); 07806 } 07807 07808 IdentifierInfo *Name = FD->getIdentifier(); 07809 if (!Name) 07810 return; 07811 if ((!getLangOpts().CPlusPlus && 07812 FD->getDeclContext()->isTranslationUnit()) || 07813 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 07814 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 07815 LinkageSpecDecl::lang_c)) { 07816 // Okay: this could be a libc/libm/Objective-C function we know 07817 // about. 07818 } else 07819 return; 07820 07821 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 07822 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 07823 // target-specific builtins, perhaps? 07824 if (!FD->getAttr<FormatAttr>()) 07825 FD->addAttr(::new (Context) FormatAttr(FD->getLocation(), Context, 07826 "printf", 2, 07827 Name->isStr("vasprintf") ? 0 : 3)); 07828 } 07829 } 07830 07831 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 07832 TypeSourceInfo *TInfo) { 07833 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 07834 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 07835 07836 if (!TInfo) { 07837 assert(D.isInvalidType() && "no declarator info for valid type"); 07838 TInfo = Context.getTrivialTypeSourceInfo(T); 07839 } 07840 07841 // Scope manipulation handled by caller. 07842 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 07843 D.getLocStart(), 07844 D.getIdentifierLoc(), 07845 D.getIdentifier(), 07846 TInfo); 07847 07848 // Bail out immediately if we have an invalid declaration. 07849 if (D.isInvalidType()) { 07850 NewTD->setInvalidDecl(); 07851 return NewTD; 07852 } 07853 07854 if (D.getDeclSpec().isModulePrivateSpecified()) { 07855 if (CurContext->isFunctionOrMethod()) 07856 Diag(NewTD->getLocation(), diag::err_module_private_local) 07857 << 2 << NewTD->getDeclName() 07858 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 07859 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 07860 else 07861 NewTD->setModulePrivate(); 07862 } 07863 07864 // C++ [dcl.typedef]p8: 07865 // If the typedef declaration defines an unnamed class (or 07866 // enum), the first typedef-name declared by the declaration 07867 // to be that class type (or enum type) is used to denote the 07868 // class type (or enum type) for linkage purposes only. 07869 // We need to check whether the type was declared in the declaration. 07870 switch (D.getDeclSpec().getTypeSpecType()) { 07871 case TST_enum: 07872 case TST_struct: 07873 case TST_union: 07874 case TST_class: { 07875 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 07876 07877 // Do nothing if the tag is not anonymous or already has an 07878 // associated typedef (from an earlier typedef in this decl group). 07879 if (tagFromDeclSpec->getIdentifier()) break; 07880 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 07881 07882 // A well-formed anonymous tag must always be a TUK_Definition. 07883 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 07884 07885 // The type must match the tag exactly; no qualifiers allowed. 07886 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 07887 break; 07888 07889 // Otherwise, set this is the anon-decl typedef for the tag. 07890 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 07891 break; 07892 } 07893 07894 default: 07895 break; 07896 } 07897 07898 return NewTD; 07899 } 07900 07901 07902 /// \brief Check that this is a valid underlying type for an enum declaration. 07903 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 07904 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 07905 QualType T = TI->getType(); 07906 07907 if (T->isDependentType() || T->isIntegralType(Context)) 07908 return false; 07909 07910 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 07911 return true; 07912 } 07913 07914 /// Check whether this is a valid redeclaration of a previous enumeration. 07915 /// \return true if the redeclaration was invalid. 07916 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 07917 QualType EnumUnderlyingTy, 07918 const EnumDecl *Prev) { 07919 bool IsFixed = !EnumUnderlyingTy.isNull(); 07920 07921 if (IsScoped != Prev->isScoped()) { 07922 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 07923 << Prev->isScoped(); 07924 Diag(Prev->getLocation(), diag::note_previous_use); 07925 return true; 07926 } 07927 07928 if (IsFixed && Prev->isFixed()) { 07929 if (!EnumUnderlyingTy->isDependentType() && 07930 !Prev->getIntegerType()->isDependentType() && 07931 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 07932 Prev->getIntegerType())) { 07933 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 07934 << EnumUnderlyingTy << Prev->getIntegerType(); 07935 Diag(Prev->getLocation(), diag::note_previous_use); 07936 return true; 07937 } 07938 } else if (IsFixed != Prev->isFixed()) { 07939 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 07940 << Prev->isFixed(); 07941 Diag(Prev->getLocation(), diag::note_previous_use); 07942 return true; 07943 } 07944 07945 return false; 07946 } 07947 07948 /// \brief Determine whether a tag with a given kind is acceptable 07949 /// as a redeclaration of the given tag declaration. 07950 /// 07951 /// \returns true if the new tag kind is acceptable, false otherwise. 07952 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 07953 TagTypeKind NewTag, bool isDefinition, 07954 SourceLocation NewTagLoc, 07955 const IdentifierInfo &Name) { 07956 // C++ [dcl.type.elab]p3: 07957 // The class-key or enum keyword present in the 07958 // elaborated-type-specifier shall agree in kind with the 07959 // declaration to which the name in the elaborated-type-specifier 07960 // refers. This rule also applies to the form of 07961 // elaborated-type-specifier that declares a class-name or 07962 // friend class since it can be construed as referring to the 07963 // definition of the class. Thus, in any 07964 // elaborated-type-specifier, the enum keyword shall be used to 07965 // refer to an enumeration (7.2), the union class-key shall be 07966 // used to refer to a union (clause 9), and either the class or 07967 // struct class-key shall be used to refer to a class (clause 9) 07968 // declared using the class or struct class-key. 07969 TagTypeKind OldTag = Previous->getTagKind(); 07970 if (!isDefinition || (NewTag != TTK_Class && NewTag != TTK_Struct)) 07971 if (OldTag == NewTag) 07972 return true; 07973 07974 if ((OldTag == TTK_Struct || OldTag == TTK_Class) && 07975 (NewTag == TTK_Struct || NewTag == TTK_Class)) { 07976 // Warn about the struct/class tag mismatch. 07977 bool isTemplate = false; 07978 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 07979 isTemplate = Record->getDescribedClassTemplate(); 07980 07981 if (!ActiveTemplateInstantiations.empty()) { 07982 // In a template instantiation, do not offer fix-its for tag mismatches 07983 // since they usually mess up the template instead of fixing the problem. 07984 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 07985 << (NewTag == TTK_Class) << isTemplate << &Name; 07986 return true; 07987 } 07988 07989 if (isDefinition) { 07990 // On definitions, check previous tags and issue a fix-it for each 07991 // one that doesn't match the current tag. 07992 if (Previous->getDefinition()) { 07993 // Don't suggest fix-its for redefinitions. 07994 return true; 07995 } 07996 07997 bool previousMismatch = false; 07998 for (TagDecl::redecl_iterator I(Previous->redecls_begin()), 07999 E(Previous->redecls_end()); I != E; ++I) { 08000 if (I->getTagKind() != NewTag) { 08001 if (!previousMismatch) { 08002 previousMismatch = true; 08003 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 08004 << (NewTag == TTK_Class) << isTemplate << &Name; 08005 } 08006 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 08007 << (NewTag == TTK_Class) 08008 << FixItHint::CreateReplacement(I->getInnerLocStart(), 08009 NewTag == TTK_Class? 08010 "class" : "struct"); 08011 } 08012 } 08013 return true; 08014 } 08015 08016 // Check for a previous definition. If current tag and definition 08017 // are same type, do nothing. If no definition, but disagree with 08018 // with previous tag type, give a warning, but no fix-it. 08019 const TagDecl *Redecl = Previous->getDefinition() ? 08020 Previous->getDefinition() : Previous; 08021 if (Redecl->getTagKind() == NewTag) { 08022 return true; 08023 } 08024 08025 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 08026 << (NewTag == TTK_Class) 08027 << isTemplate << &Name; 08028 Diag(Redecl->getLocation(), diag::note_previous_use); 08029 08030 // If there is a previous defintion, suggest a fix-it. 08031 if (Previous->getDefinition()) { 08032 Diag(NewTagLoc, diag::note_struct_class_suggestion) 08033 << (Redecl->getTagKind() == TTK_Class) 08034 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 08035 Redecl->getTagKind() == TTK_Class? "class" : "struct"); 08036 } 08037 08038 return true; 08039 } 08040 return false; 08041 } 08042 08043 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 08044 /// former case, Name will be non-null. In the later case, Name will be null. 08045 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 08046 /// reference/declaration/definition of a tag. 08047 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 08048 SourceLocation KWLoc, CXXScopeSpec &SS, 08049 IdentifierInfo *Name, SourceLocation NameLoc, 08050 AttributeList *Attr, AccessSpecifier AS, 08051 SourceLocation ModulePrivateLoc, 08052 MultiTemplateParamsArg TemplateParameterLists, 08053 bool &OwnedDecl, bool &IsDependent, 08054 SourceLocation ScopedEnumKWLoc, 08055 bool ScopedEnumUsesClassTag, 08056 TypeResult UnderlyingType) { 08057 // If this is not a definition, it must have a name. 08058 IdentifierInfo *OrigName = Name; 08059 assert((Name != 0 || TUK == TUK_Definition) && 08060 "Nameless record must be a definition!"); 08061 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 08062 08063 OwnedDecl = false; 08064 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 08065 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 08066 08067 // FIXME: Check explicit specializations more carefully. 08068 bool isExplicitSpecialization = false; 08069 bool Invalid = false; 08070 08071 // We only need to do this matching if we have template parameters 08072 // or a scope specifier, which also conveniently avoids this work 08073 // for non-C++ cases. 08074 if (TemplateParameterLists.size() > 0 || 08075 (SS.isNotEmpty() && TUK != TUK_Reference)) { 08076 if (TemplateParameterList *TemplateParams 08077 = MatchTemplateParametersToScopeSpecifier(KWLoc, NameLoc, SS, 08078 TemplateParameterLists.get(), 08079 TemplateParameterLists.size(), 08080 TUK == TUK_Friend, 08081 isExplicitSpecialization, 08082 Invalid)) { 08083 if (TemplateParams->size() > 0) { 08084 // This is a declaration or definition of a class template (which may 08085 // be a member of another template). 08086 08087 if (Invalid) 08088 return 0; 08089 08090 OwnedDecl = false; 08091 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 08092 SS, Name, NameLoc, Attr, 08093 TemplateParams, AS, 08094 ModulePrivateLoc, 08095 TemplateParameterLists.size() - 1, 08096 (TemplateParameterList**) TemplateParameterLists.release()); 08097 return Result.get(); 08098 } else { 08099 // The "template<>" header is extraneous. 08100 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 08101 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 08102 isExplicitSpecialization = true; 08103 } 08104 } 08105 } 08106 08107 // Figure out the underlying type if this a enum declaration. We need to do 08108 // this early, because it's needed to detect if this is an incompatible 08109 // redeclaration. 08110 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 08111 08112 if (Kind == TTK_Enum) { 08113 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 08114 // No underlying type explicitly specified, or we failed to parse the 08115 // type, default to int. 08116 EnumUnderlying = Context.IntTy.getTypePtr(); 08117 else if (UnderlyingType.get()) { 08118 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 08119 // integral type; any cv-qualification is ignored. 08120 TypeSourceInfo *TI = 0; 08121 GetTypeFromParser(UnderlyingType.get(), &TI); 08122 EnumUnderlying = TI; 08123 08124 if (CheckEnumUnderlyingType(TI)) 08125 // Recover by falling back to int. 08126 EnumUnderlying = Context.IntTy.getTypePtr(); 08127 08128 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 08129 UPPC_FixedUnderlyingType)) 08130 EnumUnderlying = Context.IntTy.getTypePtr(); 08131 08132 } else if (getLangOpts().MicrosoftMode) 08133 // Microsoft enums are always of int type. 08134 EnumUnderlying = Context.IntTy.getTypePtr(); 08135 } 08136 08137 DeclContext *SearchDC = CurContext; 08138 DeclContext *DC = CurContext; 08139 bool isStdBadAlloc = false; 08140 08141 RedeclarationKind Redecl = ForRedeclaration; 08142 if (TUK == TUK_Friend || TUK == TUK_Reference) 08143 Redecl = NotForRedeclaration; 08144 08145 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 08146 08147 if (Name && SS.isNotEmpty()) { 08148 // We have a nested-name tag ('struct foo::bar'). 08149 08150 // Check for invalid 'foo::'. 08151 if (SS.isInvalid()) { 08152 Name = 0; 08153 goto CreateNewDecl; 08154 } 08155 08156 // If this is a friend or a reference to a class in a dependent 08157 // context, don't try to make a decl for it. 08158 if (TUK == TUK_Friend || TUK == TUK_Reference) { 08159 DC = computeDeclContext(SS, false); 08160 if (!DC) { 08161 IsDependent = true; 08162 return 0; 08163 } 08164 } else { 08165 DC = computeDeclContext(SS, true); 08166 if (!DC) { 08167 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 08168 << SS.getRange(); 08169 return 0; 08170 } 08171 } 08172 08173 if (RequireCompleteDeclContext(SS, DC)) 08174 return 0; 08175 08176 SearchDC = DC; 08177 // Look-up name inside 'foo::'. 08178 LookupQualifiedName(Previous, DC); 08179 08180 if (Previous.isAmbiguous()) 08181 return 0; 08182 08183 if (Previous.empty()) { 08184 // Name lookup did not find anything. However, if the 08185 // nested-name-specifier refers to the current instantiation, 08186 // and that current instantiation has any dependent base 08187 // classes, we might find something at instantiation time: treat 08188 // this as a dependent elaborated-type-specifier. 08189 // But this only makes any sense for reference-like lookups. 08190 if (Previous.wasNotFoundInCurrentInstantiation() && 08191 (TUK == TUK_Reference || TUK == TUK_Friend)) { 08192 IsDependent = true; 08193 return 0; 08194 } 08195 08196 // A tag 'foo::bar' must already exist. 08197 Diag(NameLoc, diag::err_not_tag_in_scope) 08198 << Kind << Name << DC << SS.getRange(); 08199 Name = 0; 08200 Invalid = true; 08201 goto CreateNewDecl; 08202 } 08203 } else if (Name) { 08204 // If this is a named struct, check to see if there was a previous forward 08205 // declaration or definition. 08206 // FIXME: We're looking into outer scopes here, even when we 08207 // shouldn't be. Doing so can result in ambiguities that we 08208 // shouldn't be diagnosing. 08209 LookupName(Previous, S); 08210 08211 if (Previous.isAmbiguous() && 08212 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 08213 LookupResult::Filter F = Previous.makeFilter(); 08214 while (F.hasNext()) { 08215 NamedDecl *ND = F.next(); 08216 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 08217 F.erase(); 08218 } 08219 F.done(); 08220 } 08221 08222 // Note: there used to be some attempt at recovery here. 08223 if (Previous.isAmbiguous()) 08224 return 0; 08225 08226 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 08227 // FIXME: This makes sure that we ignore the contexts associated 08228 // with C structs, unions, and enums when looking for a matching 08229 // tag declaration or definition. See the similar lookup tweak 08230 // in Sema::LookupName; is there a better way to deal with this? 08231 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 08232 SearchDC = SearchDC->getParent(); 08233 } 08234 } else if (S->isFunctionPrototypeScope()) { 08235 // If this is an enum declaration in function prototype scope, set its 08236 // initial context to the translation unit. 08237 // FIXME: [citation needed] 08238 SearchDC = Context.getTranslationUnitDecl(); 08239 } 08240 08241 if (Previous.isSingleResult() && 08242 Previous.getFoundDecl()->isTemplateParameter()) { 08243 // Maybe we will complain about the shadowed template parameter. 08244 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 08245 // Just pretend that we didn't see the previous declaration. 08246 Previous.clear(); 08247 } 08248 08249 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 08250 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 08251 // This is a declaration of or a reference to "std::bad_alloc". 08252 isStdBadAlloc = true; 08253 08254 if (Previous.empty() && StdBadAlloc) { 08255 // std::bad_alloc has been implicitly declared (but made invisible to 08256 // name lookup). Fill in this implicit declaration as the previous 08257 // declaration, so that the declarations get chained appropriately. 08258 Previous.addDecl(getStdBadAlloc()); 08259 } 08260 } 08261 08262 // If we didn't find a previous declaration, and this is a reference 08263 // (or friend reference), move to the correct scope. In C++, we 08264 // also need to do a redeclaration lookup there, just in case 08265 // there's a shadow friend decl. 08266 if (Name && Previous.empty() && 08267 (TUK == TUK_Reference || TUK == TUK_Friend)) { 08268 if (Invalid) goto CreateNewDecl; 08269 assert(SS.isEmpty()); 08270 08271 if (TUK == TUK_Reference) { 08272 // C++ [basic.scope.pdecl]p5: 08273 // -- for an elaborated-type-specifier of the form 08274 // 08275 // class-key identifier 08276 // 08277 // if the elaborated-type-specifier is used in the 08278 // decl-specifier-seq or parameter-declaration-clause of a 08279 // function defined in namespace scope, the identifier is 08280 // declared as a class-name in the namespace that contains 08281 // the declaration; otherwise, except as a friend 08282 // declaration, the identifier is declared in the smallest 08283 // non-class, non-function-prototype scope that contains the 08284 // declaration. 08285 // 08286 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 08287 // C structs and unions. 08288 // 08289 // It is an error in C++ to declare (rather than define) an enum 08290 // type, including via an elaborated type specifier. We'll 08291 // diagnose that later; for now, declare the enum in the same 08292 // scope as we would have picked for any other tag type. 08293 // 08294 // GNU C also supports this behavior as part of its incomplete 08295 // enum types extension, while GNU C++ does not. 08296 // 08297 // Find the context where we'll be declaring the tag. 08298 // FIXME: We would like to maintain the current DeclContext as the 08299 // lexical context, 08300 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 08301 SearchDC = SearchDC->getParent(); 08302 08303 // Find the scope where we'll be declaring the tag. 08304 while (S->isClassScope() || 08305 (getLangOpts().CPlusPlus && 08306 S->isFunctionPrototypeScope()) || 08307 ((S->getFlags() & Scope::DeclScope) == 0) || 08308 (S->getEntity() && 08309 ((DeclContext *)S->getEntity())->isTransparentContext())) 08310 S = S->getParent(); 08311 } else { 08312 assert(TUK == TUK_Friend); 08313 // C++ [namespace.memdef]p3: 08314 // If a friend declaration in a non-local class first declares a 08315 // class or function, the friend class or function is a member of 08316 // the innermost enclosing namespace. 08317 SearchDC = SearchDC->getEnclosingNamespaceContext(); 08318 } 08319 08320 // In C++, we need to do a redeclaration lookup to properly 08321 // diagnose some problems. 08322 if (getLangOpts().CPlusPlus) { 08323 Previous.setRedeclarationKind(ForRedeclaration); 08324 LookupQualifiedName(Previous, SearchDC); 08325 } 08326 } 08327 08328 if (!Previous.empty()) { 08329 NamedDecl *PrevDecl = (*Previous.begin())->getUnderlyingDecl(); 08330 08331 // It's okay to have a tag decl in the same scope as a typedef 08332 // which hides a tag decl in the same scope. Finding this 08333 // insanity with a redeclaration lookup can only actually happen 08334 // in C++. 08335 // 08336 // This is also okay for elaborated-type-specifiers, which is 08337 // technically forbidden by the current standard but which is 08338 // okay according to the likely resolution of an open issue; 08339 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 08340 if (getLangOpts().CPlusPlus) { 08341 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 08342 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 08343 TagDecl *Tag = TT->getDecl(); 08344 if (Tag->getDeclName() == Name && 08345 Tag->getDeclContext()->getRedeclContext() 08346 ->Equals(TD->getDeclContext()->getRedeclContext())) { 08347 PrevDecl = Tag; 08348 Previous.clear(); 08349 Previous.addDecl(Tag); 08350 Previous.resolveKind(); 08351 } 08352 } 08353 } 08354 } 08355 08356 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 08357 // If this is a use of a previous tag, or if the tag is already declared 08358 // in the same scope (so that the definition/declaration completes or 08359 // rementions the tag), reuse the decl. 08360 if (TUK == TUK_Reference || TUK == TUK_Friend || 08361 isDeclInScope(PrevDecl, SearchDC, S, isExplicitSpecialization)) { 08362 // Make sure that this wasn't declared as an enum and now used as a 08363 // struct or something similar. 08364 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 08365 TUK == TUK_Definition, KWLoc, 08366 *Name)) { 08367 bool SafeToContinue 08368 = (PrevTagDecl->getTagKind() != TTK_Enum && 08369 Kind != TTK_Enum); 08370 if (SafeToContinue) 08371 Diag(KWLoc, diag::err_use_with_wrong_tag) 08372 << Name 08373 << FixItHint::CreateReplacement(SourceRange(KWLoc), 08374 PrevTagDecl->getKindName()); 08375 else 08376 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 08377 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 08378 08379 if (SafeToContinue) 08380 Kind = PrevTagDecl->getTagKind(); 08381 else { 08382 // Recover by making this an anonymous redefinition. 08383 Name = 0; 08384 Previous.clear(); 08385 Invalid = true; 08386 } 08387 } 08388 08389 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 08390 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 08391 08392 // If this is an elaborated-type-specifier for a scoped enumeration, 08393 // the 'class' keyword is not necessary and not permitted. 08394 if (TUK == TUK_Reference || TUK == TUK_Friend) { 08395 if (ScopedEnum) 08396 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 08397 << PrevEnum->isScoped() 08398 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 08399 return PrevTagDecl; 08400 } 08401 08402 QualType EnumUnderlyingTy; 08403 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 08404 EnumUnderlyingTy = TI->getType(); 08405 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 08406 EnumUnderlyingTy = QualType(T, 0); 08407 08408 // All conflicts with previous declarations are recovered by 08409 // returning the previous declaration, unless this is a definition, 08410 // in which case we want the caller to bail out. 08411 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 08412 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 08413 return TUK == TUK_Declaration ? PrevTagDecl : 0; 08414 } 08415 08416 if (!Invalid) { 08417 // If this is a use, just return the declaration we found. 08418 08419 // FIXME: In the future, return a variant or some other clue 08420 // for the consumer of this Decl to know it doesn't own it. 08421 // For our current ASTs this shouldn't be a problem, but will 08422 // need to be changed with DeclGroups. 08423 if ((TUK == TUK_Reference && (!PrevTagDecl->getFriendObjectKind() || 08424 getLangOpts().MicrosoftExt)) || TUK == TUK_Friend) 08425 return PrevTagDecl; 08426 08427 // Diagnose attempts to redefine a tag. 08428 if (TUK == TUK_Definition) { 08429 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 08430 // If we're defining a specialization and the previous definition 08431 // is from an implicit instantiation, don't emit an error 08432 // here; we'll catch this in the general case below. 08433 bool IsExplicitSpecializationAfterInstantiation = false; 08434 if (isExplicitSpecialization) { 08435 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 08436 IsExplicitSpecializationAfterInstantiation = 08437 RD->getTemplateSpecializationKind() != 08438 TSK_ExplicitSpecialization; 08439 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 08440 IsExplicitSpecializationAfterInstantiation = 08441 ED->getTemplateSpecializationKind() != 08442 TSK_ExplicitSpecialization; 08443 } 08444 08445 if (!IsExplicitSpecializationAfterInstantiation) { 08446 // A redeclaration in function prototype scope in C isn't 08447 // visible elsewhere, so merely issue a warning. 08448 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 08449 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 08450 else 08451 Diag(NameLoc, diag::err_redefinition) << Name; 08452 Diag(Def->getLocation(), diag::note_previous_definition); 08453 // If this is a redefinition, recover by making this 08454 // struct be anonymous, which will make any later 08455 // references get the previous definition. 08456 Name = 0; 08457 Previous.clear(); 08458 Invalid = true; 08459 } 08460 } else { 08461 // If the type is currently being defined, complain 08462 // about a nested redefinition. 08463 const TagType *Tag 08464 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 08465 if (Tag->isBeingDefined()) { 08466 Diag(NameLoc, diag::err_nested_redefinition) << Name; 08467 Diag(PrevTagDecl->getLocation(), 08468 diag::note_previous_definition); 08469 Name = 0; 08470 Previous.clear(); 08471 Invalid = true; 08472 } 08473 } 08474 08475 // Okay, this is definition of a previously declared or referenced 08476 // tag PrevDecl. We're going to create a new Decl for it. 08477 } 08478 } 08479 // If we get here we have (another) forward declaration or we 08480 // have a definition. Just create a new decl. 08481 08482 } else { 08483 // If we get here, this is a definition of a new tag type in a nested 08484 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 08485 // new decl/type. We set PrevDecl to NULL so that the entities 08486 // have distinct types. 08487 Previous.clear(); 08488 } 08489 // If we get here, we're going to create a new Decl. If PrevDecl 08490 // is non-NULL, it's a definition of the tag declared by 08491 // PrevDecl. If it's NULL, we have a new definition. 08492 08493 08494 // Otherwise, PrevDecl is not a tag, but was found with tag 08495 // lookup. This is only actually possible in C++, where a few 08496 // things like templates still live in the tag namespace. 08497 } else { 08498 // Use a better diagnostic if an elaborated-type-specifier 08499 // found the wrong kind of type on the first 08500 // (non-redeclaration) lookup. 08501 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 08502 !Previous.isForRedeclaration()) { 08503 unsigned Kind = 0; 08504 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 08505 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 08506 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 08507 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 08508 Diag(PrevDecl->getLocation(), diag::note_declared_at); 08509 Invalid = true; 08510 08511 // Otherwise, only diagnose if the declaration is in scope. 08512 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 08513 isExplicitSpecialization)) { 08514 // do nothing 08515 08516 // Diagnose implicit declarations introduced by elaborated types. 08517 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 08518 unsigned Kind = 0; 08519 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 08520 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 08521 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 08522 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 08523 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 08524 Invalid = true; 08525 08526 // Otherwise it's a declaration. Call out a particularly common 08527 // case here. 08528 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 08529 unsigned Kind = 0; 08530 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 08531 Diag(NameLoc, diag::err_tag_definition_of_typedef) 08532 << Name << Kind << TND->getUnderlyingType(); 08533 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 08534 Invalid = true; 08535 08536 // Otherwise, diagnose. 08537 } else { 08538 // The tag name clashes with something else in the target scope, 08539 // issue an error and recover by making this tag be anonymous. 08540 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 08541 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 08542 Name = 0; 08543 Invalid = true; 08544 } 08545 08546 // The existing declaration isn't relevant to us; we're in a 08547 // new scope, so clear out the previous declaration. 08548 Previous.clear(); 08549 } 08550 } 08551 08552 CreateNewDecl: 08553 08554 TagDecl *PrevDecl = 0; 08555 if (Previous.isSingleResult()) 08556 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 08557 08558 // If there is an identifier, use the location of the identifier as the 08559 // location of the decl, otherwise use the location of the struct/union 08560 // keyword. 08561 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 08562 08563 // Otherwise, create a new declaration. If there is a previous 08564 // declaration of the same entity, the two will be linked via 08565 // PrevDecl. 08566 TagDecl *New; 08567 08568 bool IsForwardReference = false; 08569 if (Kind == TTK_Enum) { 08570 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 08571 // enum X { A, B, C } D; D should chain to X. 08572 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 08573 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 08574 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 08575 // If this is an undefined enum, warn. 08576 if (TUK != TUK_Definition && !Invalid) { 08577 TagDecl *Def; 08578 if (getLangOpts().CPlusPlus0x && cast<EnumDecl>(New)->isFixed()) { 08579 // C++0x: 7.2p2: opaque-enum-declaration. 08580 // Conflicts are diagnosed above. Do nothing. 08581 } 08582 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 08583 Diag(Loc, diag::ext_forward_ref_enum_def) 08584 << New; 08585 Diag(Def->getLocation(), diag::note_previous_definition); 08586 } else { 08587 unsigned DiagID = diag::ext_forward_ref_enum; 08588 if (getLangOpts().MicrosoftMode) 08589 DiagID = diag::ext_ms_forward_ref_enum; 08590 else if (getLangOpts().CPlusPlus) 08591 DiagID = diag::err_forward_ref_enum; 08592 Diag(Loc, DiagID); 08593 08594 // If this is a forward-declared reference to an enumeration, make a 08595 // note of it; we won't actually be introducing the declaration into 08596 // the declaration context. 08597 if (TUK == TUK_Reference) 08598 IsForwardReference = true; 08599 } 08600 } 08601 08602 if (EnumUnderlying) { 08603 EnumDecl *ED = cast<EnumDecl>(New); 08604 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 08605 ED->setIntegerTypeSourceInfo(TI); 08606 else 08607 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 08608 ED->setPromotionType(ED->getIntegerType()); 08609 } 08610 08611 } else { 08612 // struct/union/class 08613 08614 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 08615 // struct X { int A; } D; D should chain to X. 08616 if (getLangOpts().CPlusPlus) { 08617 // FIXME: Look for a way to use RecordDecl for simple structs. 08618 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 08619 cast_or_null<CXXRecordDecl>(PrevDecl)); 08620 08621 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 08622 StdBadAlloc = cast<CXXRecordDecl>(New); 08623 } else 08624 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 08625 cast_or_null<RecordDecl>(PrevDecl)); 08626 } 08627 08628 // Maybe add qualifier info. 08629 if (SS.isNotEmpty()) { 08630 if (SS.isSet()) { 08631 // If this is either a declaration or a definition, check the 08632 // nested-name-specifier against the current context. We don't do this 08633 // for explicit specializations, because they have similar checking 08634 // (with more specific diagnostics) in the call to 08635 // CheckMemberSpecialization, below. 08636 if (!isExplicitSpecialization && 08637 (TUK == TUK_Definition || TUK == TUK_Declaration) && 08638 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 08639 Invalid = true; 08640 08641 New->setQualifierInfo(SS.getWithLocInContext(Context)); 08642 if (TemplateParameterLists.size() > 0) { 08643 New->setTemplateParameterListsInfo(Context, 08644 TemplateParameterLists.size(), 08645 (TemplateParameterList**) TemplateParameterLists.release()); 08646 } 08647 } 08648 else 08649 Invalid = true; 08650 } 08651 08652 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 08653 // Add alignment attributes if necessary; these attributes are checked when 08654 // the ASTContext lays out the structure. 08655 // 08656 // It is important for implementing the correct semantics that this 08657 // happen here (in act on tag decl). The #pragma pack stack is 08658 // maintained as a result of parser callbacks which can occur at 08659 // many points during the parsing of a struct declaration (because 08660 // the #pragma tokens are effectively skipped over during the 08661 // parsing of the struct). 08662 AddAlignmentAttributesForRecord(RD); 08663 08664 AddMsStructLayoutForRecord(RD); 08665 } 08666 08667 if (ModulePrivateLoc.isValid()) { 08668 if (isExplicitSpecialization) 08669 Diag(New->getLocation(), diag::err_module_private_specialization) 08670 << 2 08671 << FixItHint::CreateRemoval(ModulePrivateLoc); 08672 // __module_private__ does not apply to local classes. However, we only 08673 // diagnose this as an error when the declaration specifiers are 08674 // freestanding. Here, we just ignore the __module_private__. 08675 else if (!SearchDC->isFunctionOrMethod()) 08676 New->setModulePrivate(); 08677 } 08678 08679 // If this is a specialization of a member class (of a class template), 08680 // check the specialization. 08681 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 08682 Invalid = true; 08683 08684 if (Invalid) 08685 New->setInvalidDecl(); 08686 08687 if (Attr) 08688 ProcessDeclAttributeList(S, New, Attr); 08689 08690 // If we're declaring or defining a tag in function prototype scope 08691 // in C, note that this type can only be used within the function. 08692 if (Name && S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus) 08693 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 08694 08695 // Set the lexical context. If the tag has a C++ scope specifier, the 08696 // lexical context will be different from the semantic context. 08697 New->setLexicalDeclContext(CurContext); 08698 08699 // Mark this as a friend decl if applicable. 08700 // In Microsoft mode, a friend declaration also acts as a forward 08701 // declaration so we always pass true to setObjectOfFriendDecl to make 08702 // the tag name visible. 08703 if (TUK == TUK_Friend) 08704 New->setObjectOfFriendDecl(/* PreviouslyDeclared = */ !Previous.empty() || 08705 getLangOpts().MicrosoftExt); 08706 08707 // Set the access specifier. 08708 if (!Invalid && SearchDC->isRecord()) 08709 SetMemberAccessSpecifier(New, PrevDecl, AS); 08710 08711 if (TUK == TUK_Definition) 08712 New->startDefinition(); 08713 08714 // If this has an identifier, add it to the scope stack. 08715 if (TUK == TUK_Friend) { 08716 // We might be replacing an existing declaration in the lookup tables; 08717 // if so, borrow its access specifier. 08718 if (PrevDecl) 08719 New->setAccess(PrevDecl->getAccess()); 08720 08721 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 08722 DC->makeDeclVisibleInContext(New); 08723 if (Name) // can be null along some error paths 08724 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 08725 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 08726 } else if (Name) { 08727 S = getNonFieldDeclScope(S); 08728 PushOnScopeChains(New, S, !IsForwardReference); 08729 if (IsForwardReference) 08730 SearchDC->makeDeclVisibleInContext(New); 08731 08732 } else { 08733 CurContext->addDecl(New); 08734 } 08735 08736 // If this is the C FILE type, notify the AST context. 08737 if (IdentifierInfo *II = New->getIdentifier()) 08738 if (!New->isInvalidDecl() && 08739 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 08740 II->isStr("FILE")) 08741 Context.setFILEDecl(New); 08742 08743 // If we were in function prototype scope (and not in C++ mode), add this 08744 // tag to the list of decls to inject into the function definition scope. 08745 if (S->isFunctionPrototypeScope() && !getLangOpts().CPlusPlus && 08746 InFunctionDeclarator && Name) 08747 DeclsInPrototypeScope.push_back(New); 08748 08749 if (PrevDecl) 08750 mergeDeclAttributes(New, PrevDecl); 08751 08752 OwnedDecl = true; 08753 return New; 08754 } 08755 08756 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 08757 AdjustDeclIfTemplate(TagD); 08758 TagDecl *Tag = cast<TagDecl>(TagD); 08759 08760 // Enter the tag context. 08761 PushDeclContext(S, Tag); 08762 } 08763 08764 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 08765 assert(isa<ObjCContainerDecl>(IDecl) && 08766 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 08767 DeclContext *OCD = cast<DeclContext>(IDecl); 08768 assert(getContainingDC(OCD) == CurContext && 08769 "The next DeclContext should be lexically contained in the current one."); 08770 CurContext = OCD; 08771 return IDecl; 08772 } 08773 08774 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 08775 SourceLocation FinalLoc, 08776 SourceLocation LBraceLoc) { 08777 AdjustDeclIfTemplate(TagD); 08778 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 08779 08780 FieldCollector->StartClass(); 08781 08782 if (!Record->getIdentifier()) 08783 return; 08784 08785 if (FinalLoc.isValid()) 08786 Record->addAttr(new (Context) FinalAttr(FinalLoc, Context)); 08787 08788 // C++ [class]p2: 08789 // [...] The class-name is also inserted into the scope of the 08790 // class itself; this is known as the injected-class-name. For 08791 // purposes of access checking, the injected-class-name is treated 08792 // as if it were a public member name. 08793 CXXRecordDecl *InjectedClassName 08794 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 08795 Record->getLocStart(), Record->getLocation(), 08796 Record->getIdentifier(), 08797 /*PrevDecl=*/0, 08798 /*DelayTypeCreation=*/true); 08799 Context.getTypeDeclType(InjectedClassName, Record); 08800 InjectedClassName->setImplicit(); 08801 InjectedClassName->setAccess(AS_public); 08802 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 08803 InjectedClassName->setDescribedClassTemplate(Template); 08804 PushOnScopeChains(InjectedClassName, S); 08805 assert(InjectedClassName->isInjectedClassName() && 08806 "Broken injected-class-name"); 08807 } 08808 08809 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 08810 SourceLocation RBraceLoc) { 08811 AdjustDeclIfTemplate(TagD); 08812 TagDecl *Tag = cast<TagDecl>(TagD); 08813 Tag->setRBraceLoc(RBraceLoc); 08814 08815 // Make sure we "complete" the definition even it is invalid. 08816 if (Tag->isBeingDefined()) { 08817 assert(Tag->isInvalidDecl() && "We should already have completed it"); 08818 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 08819 RD->completeDefinition(); 08820 } 08821 08822 if (isa<CXXRecordDecl>(Tag)) 08823 FieldCollector->FinishClass(); 08824 08825 // Exit this scope of this tag's definition. 08826 PopDeclContext(); 08827 08828 // Notify the consumer that we've defined a tag. 08829 Consumer.HandleTagDeclDefinition(Tag); 08830 } 08831 08832 void Sema::ActOnObjCContainerFinishDefinition() { 08833 // Exit this scope of this interface definition. 08834 PopDeclContext(); 08835 } 08836 08837 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 08838 assert(DC == CurContext && "Mismatch of container contexts"); 08839 OriginalLexicalContext = DC; 08840 ActOnObjCContainerFinishDefinition(); 08841 } 08842 08843 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 08844 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 08845 OriginalLexicalContext = 0; 08846 } 08847 08848 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 08849 AdjustDeclIfTemplate(TagD); 08850 TagDecl *Tag = cast<TagDecl>(TagD); 08851 Tag->setInvalidDecl(); 08852 08853 // Make sure we "complete" the definition even it is invalid. 08854 if (Tag->isBeingDefined()) { 08855 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 08856 RD->completeDefinition(); 08857 } 08858 08859 // We're undoing ActOnTagStartDefinition here, not 08860 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 08861 // the FieldCollector. 08862 08863 PopDeclContext(); 08864 } 08865 08866 // Note that FieldName may be null for anonymous bitfields. 08867 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 08868 IdentifierInfo *FieldName, 08869 QualType FieldTy, Expr *BitWidth, 08870 bool *ZeroWidth) { 08871 // Default to true; that shouldn't confuse checks for emptiness 08872 if (ZeroWidth) 08873 *ZeroWidth = true; 08874 08875 // C99 6.7.2.1p4 - verify the field type. 08876 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 08877 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 08878 // Handle incomplete types with specific error. 08879 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 08880 return ExprError(); 08881 if (FieldName) 08882 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 08883 << FieldName << FieldTy << BitWidth->getSourceRange(); 08884 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 08885 << FieldTy << BitWidth->getSourceRange(); 08886 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 08887 UPPC_BitFieldWidth)) 08888 return ExprError(); 08889 08890 // If the bit-width is type- or value-dependent, don't try to check 08891 // it now. 08892 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 08893 return Owned(BitWidth); 08894 08895 llvm::APSInt Value; 08896 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 08897 if (ICE.isInvalid()) 08898 return ICE; 08899 BitWidth = ICE.take(); 08900 08901 if (Value != 0 && ZeroWidth) 08902 *ZeroWidth = false; 08903 08904 // Zero-width bitfield is ok for anonymous field. 08905 if (Value == 0 && FieldName) 08906 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 08907 08908 if (Value.isSigned() && Value.isNegative()) { 08909 if (FieldName) 08910 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 08911 << FieldName << Value.toString(10); 08912 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 08913 << Value.toString(10); 08914 } 08915 08916 if (!FieldTy->isDependentType()) { 08917 uint64_t TypeSize = Context.getTypeSize(FieldTy); 08918 if (Value.getZExtValue() > TypeSize) { 08919 if (!getLangOpts().CPlusPlus) { 08920 if (FieldName) 08921 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 08922 << FieldName << (unsigned)Value.getZExtValue() 08923 << (unsigned)TypeSize; 08924 08925 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 08926 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 08927 } 08928 08929 if (FieldName) 08930 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 08931 << FieldName << (unsigned)Value.getZExtValue() 08932 << (unsigned)TypeSize; 08933 else 08934 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 08935 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 08936 } 08937 } 08938 08939 return Owned(BitWidth); 08940 } 08941 08942 /// ActOnField - Each field of a C struct/union is passed into this in order 08943 /// to create a FieldDecl object for it. 08944 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 08945 Declarator &D, Expr *BitfieldWidth) { 08946 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 08947 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 08948 /*HasInit=*/false, AS_public); 08949 return Res; 08950 } 08951 08952 /// HandleField - Analyze a field of a C struct or a C++ data member. 08953 /// 08954 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 08955 SourceLocation DeclStart, 08956 Declarator &D, Expr *BitWidth, bool HasInit, 08957 AccessSpecifier AS) { 08958 IdentifierInfo *II = D.getIdentifier(); 08959 SourceLocation Loc = DeclStart; 08960 if (II) Loc = D.getIdentifierLoc(); 08961 08962 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 08963 QualType T = TInfo->getType(); 08964 if (getLangOpts().CPlusPlus) { 08965 CheckExtraCXXDefaultArguments(D); 08966 08967 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 08968 UPPC_DataMemberType)) { 08969 D.setInvalidType(); 08970 T = Context.IntTy; 08971 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 08972 } 08973 } 08974 08975 DiagnoseFunctionSpecifiers(D); 08976 08977 if (D.getDeclSpec().isThreadSpecified()) 08978 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 08979 if (D.getDeclSpec().isConstexprSpecified()) 08980 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 08981 << 2; 08982 08983 // Check to see if this name was declared as a member previously 08984 NamedDecl *PrevDecl = 0; 08985 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 08986 LookupName(Previous, S); 08987 switch (Previous.getResultKind()) { 08988 case LookupResult::Found: 08989 case LookupResult::FoundUnresolvedValue: 08990 PrevDecl = Previous.getAsSingle<NamedDecl>(); 08991 break; 08992 08993 case LookupResult::FoundOverloaded: 08994 PrevDecl = Previous.getRepresentativeDecl(); 08995 break; 08996 08997 case LookupResult::NotFound: 08998 case LookupResult::NotFoundInCurrentInstantiation: 08999 case LookupResult::Ambiguous: 09000 break; 09001 } 09002 Previous.suppressDiagnostics(); 09003 09004 if (PrevDecl && PrevDecl->isTemplateParameter()) { 09005 // Maybe we will complain about the shadowed template parameter. 09006 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 09007 // Just pretend that we didn't see the previous declaration. 09008 PrevDecl = 0; 09009 } 09010 09011 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 09012 PrevDecl = 0; 09013 09014 bool Mutable 09015 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 09016 SourceLocation TSSL = D.getLocStart(); 09017 FieldDecl *NewFD 09018 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, HasInit, 09019 TSSL, AS, PrevDecl, &D); 09020 09021 if (NewFD->isInvalidDecl()) 09022 Record->setInvalidDecl(); 09023 09024 if (D.getDeclSpec().isModulePrivateSpecified()) 09025 NewFD->setModulePrivate(); 09026 09027 if (NewFD->isInvalidDecl() && PrevDecl) { 09028 // Don't introduce NewFD into scope; there's already something 09029 // with the same name in the same scope. 09030 } else if (II) { 09031 PushOnScopeChains(NewFD, S); 09032 } else 09033 Record->addDecl(NewFD); 09034 09035 return NewFD; 09036 } 09037 09038 /// \brief Build a new FieldDecl and check its well-formedness. 09039 /// 09040 /// This routine builds a new FieldDecl given the fields name, type, 09041 /// record, etc. \p PrevDecl should refer to any previous declaration 09042 /// with the same name and in the same scope as the field to be 09043 /// created. 09044 /// 09045 /// \returns a new FieldDecl. 09046 /// 09047 /// \todo The Declarator argument is a hack. It will be removed once 09048 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 09049 TypeSourceInfo *TInfo, 09050 RecordDecl *Record, SourceLocation Loc, 09051 bool Mutable, Expr *BitWidth, bool HasInit, 09052 SourceLocation TSSL, 09053 AccessSpecifier AS, NamedDecl *PrevDecl, 09054 Declarator *D) { 09055 IdentifierInfo *II = Name.getAsIdentifierInfo(); 09056 bool InvalidDecl = false; 09057 if (D) InvalidDecl = D->isInvalidType(); 09058 09059 // If we receive a broken type, recover by assuming 'int' and 09060 // marking this declaration as invalid. 09061 if (T.isNull()) { 09062 InvalidDecl = true; 09063 T = Context.IntTy; 09064 } 09065 09066 QualType EltTy = Context.getBaseElementType(T); 09067 if (!EltTy->isDependentType()) { 09068 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 09069 // Fields of incomplete type force their record to be invalid. 09070 Record->setInvalidDecl(); 09071 InvalidDecl = true; 09072 } else { 09073 NamedDecl *Def; 09074 EltTy->isIncompleteType(&Def); 09075 if (Def && Def->isInvalidDecl()) { 09076 Record->setInvalidDecl(); 09077 InvalidDecl = true; 09078 } 09079 } 09080 } 09081 09082 // C99 6.7.2.1p8: A member of a structure or union may have any type other 09083 // than a variably modified type. 09084 if (!InvalidDecl && T->isVariablyModifiedType()) { 09085 bool SizeIsNegative; 09086 llvm::APSInt Oversized; 09087 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context, 09088 SizeIsNegative, 09089 Oversized); 09090 if (!FixedTy.isNull()) { 09091 Diag(Loc, diag::warn_illegal_constant_array_size); 09092 T = FixedTy; 09093 } else { 09094 if (SizeIsNegative) 09095 Diag(Loc, diag::err_typecheck_negative_array_size); 09096 else if (Oversized.getBoolValue()) 09097 Diag(Loc, diag::err_array_too_large) 09098 << Oversized.toString(10); 09099 else 09100 Diag(Loc, diag::err_typecheck_field_variable_size); 09101 InvalidDecl = true; 09102 } 09103 } 09104 09105 // Fields can not have abstract class types 09106 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 09107 diag::err_abstract_type_in_decl, 09108 AbstractFieldType)) 09109 InvalidDecl = true; 09110 09111 bool ZeroWidth = false; 09112 // If this is declared as a bit-field, check the bit-field. 09113 if (!InvalidDecl && BitWidth) { 09114 BitWidth = VerifyBitField(Loc, II, T, BitWidth, &ZeroWidth).take(); 09115 if (!BitWidth) { 09116 InvalidDecl = true; 09117 BitWidth = 0; 09118 ZeroWidth = false; 09119 } 09120 } 09121 09122 // Check that 'mutable' is consistent with the type of the declaration. 09123 if (!InvalidDecl && Mutable) { 09124 unsigned DiagID = 0; 09125 if (T->isReferenceType()) 09126 DiagID = diag::err_mutable_reference; 09127 else if (T.isConstQualified()) 09128 DiagID = diag::err_mutable_const; 09129 09130 if (DiagID) { 09131 SourceLocation ErrLoc = Loc; 09132 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 09133 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 09134 Diag(ErrLoc, DiagID); 09135 Mutable = false; 09136 InvalidDecl = true; 09137 } 09138 } 09139 09140 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 09141 BitWidth, Mutable, HasInit); 09142 if (InvalidDecl) 09143 NewFD->setInvalidDecl(); 09144 09145 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 09146 Diag(Loc, diag::err_duplicate_member) << II; 09147 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 09148 NewFD->setInvalidDecl(); 09149 } 09150 09151 if (!InvalidDecl && getLangOpts().CPlusPlus) { 09152 if (Record->isUnion()) { 09153 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 09154 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 09155 if (RDecl->getDefinition()) { 09156 // C++ [class.union]p1: An object of a class with a non-trivial 09157 // constructor, a non-trivial copy constructor, a non-trivial 09158 // destructor, or a non-trivial copy assignment operator 09159 // cannot be a member of a union, nor can an array of such 09160 // objects. 09161 if (CheckNontrivialField(NewFD)) 09162 NewFD->setInvalidDecl(); 09163 } 09164 } 09165 09166 // C++ [class.union]p1: If a union contains a member of reference type, 09167 // the program is ill-formed. 09168 if (EltTy->isReferenceType()) { 09169 Diag(NewFD->getLocation(), diag::err_union_member_of_reference_type) 09170 << NewFD->getDeclName() << EltTy; 09171 NewFD->setInvalidDecl(); 09172 } 09173 } 09174 } 09175 09176 // FIXME: We need to pass in the attributes given an AST 09177 // representation, not a parser representation. 09178 if (D) 09179 // FIXME: What to pass instead of TUScope? 09180 ProcessDeclAttributes(TUScope, NewFD, *D); 09181 09182 // In auto-retain/release, infer strong retension for fields of 09183 // retainable type. 09184 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 09185 NewFD->setInvalidDecl(); 09186 09187 if (T.isObjCGCWeak()) 09188 Diag(Loc, diag::warn_attribute_weak_on_field); 09189 09190 NewFD->setAccess(AS); 09191 return NewFD; 09192 } 09193 09194 bool Sema::CheckNontrivialField(FieldDecl *FD) { 09195 assert(FD); 09196 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 09197 09198 if (FD->isInvalidDecl()) 09199 return true; 09200 09201 QualType EltTy = Context.getBaseElementType(FD->getType()); 09202 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 09203 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 09204 if (RDecl->getDefinition()) { 09205 // We check for copy constructors before constructors 09206 // because otherwise we'll never get complaints about 09207 // copy constructors. 09208 09209 CXXSpecialMember member = CXXInvalid; 09210 if (!RDecl->hasTrivialCopyConstructor()) 09211 member = CXXCopyConstructor; 09212 else if (!RDecl->hasTrivialDefaultConstructor()) 09213 member = CXXDefaultConstructor; 09214 else if (!RDecl->hasTrivialCopyAssignment()) 09215 member = CXXCopyAssignment; 09216 else if (!RDecl->hasTrivialDestructor()) 09217 member = CXXDestructor; 09218 09219 if (member != CXXInvalid) { 09220 if (!getLangOpts().CPlusPlus0x && 09221 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 09222 // Objective-C++ ARC: it is an error to have a non-trivial field of 09223 // a union. However, system headers in Objective-C programs 09224 // occasionally have Objective-C lifetime objects within unions, 09225 // and rather than cause the program to fail, we make those 09226 // members unavailable. 09227 SourceLocation Loc = FD->getLocation(); 09228 if (getSourceManager().isInSystemHeader(Loc)) { 09229 if (!FD->hasAttr<UnavailableAttr>()) 09230 FD->addAttr(new (Context) UnavailableAttr(Loc, Context, 09231 "this system field has retaining ownership")); 09232 return false; 09233 } 09234 } 09235 09236 Diag(FD->getLocation(), getLangOpts().CPlusPlus0x ? 09237 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 09238 diag::err_illegal_union_or_anon_struct_member) 09239 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 09240 DiagnoseNontrivial(RT, member); 09241 return !getLangOpts().CPlusPlus0x; 09242 } 09243 } 09244 } 09245 09246 return false; 09247 } 09248 09249 /// If the given constructor is user-provided, produce a diagnostic explaining 09250 /// that it makes the class non-trivial. 09251 static bool DiagnoseNontrivialUserProvidedCtor(Sema &S, QualType QT, 09252 CXXConstructorDecl *CD, 09253 Sema::CXXSpecialMember CSM) { 09254 if (!CD->isUserProvided()) 09255 return false; 09256 09257 SourceLocation CtorLoc = CD->getLocation(); 09258 S.Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << CSM; 09259 return true; 09260 } 09261 09262 /// DiagnoseNontrivial - Given that a class has a non-trivial 09263 /// special member, figure out why. 09264 void Sema::DiagnoseNontrivial(const RecordType* T, CXXSpecialMember member) { 09265 QualType QT(T, 0U); 09266 CXXRecordDecl* RD = cast<CXXRecordDecl>(T->getDecl()); 09267 09268 // Check whether the member was user-declared. 09269 switch (member) { 09270 case CXXInvalid: 09271 break; 09272 09273 case CXXDefaultConstructor: 09274 if (RD->hasUserDeclaredConstructor()) { 09275 typedef CXXRecordDecl::ctor_iterator ctor_iter; 09276 for (ctor_iter CI = RD->ctor_begin(), CE = RD->ctor_end(); CI != CE; ++CI) 09277 if (DiagnoseNontrivialUserProvidedCtor(*this, QT, &*CI, member)) 09278 return; 09279 09280 // No user-provided constructors; look for constructor templates. 09281 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> 09282 tmpl_iter; 09283 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); 09284 TI != TE; ++TI) { 09285 CXXConstructorDecl *CD = 09286 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()); 09287 if (CD && DiagnoseNontrivialUserProvidedCtor(*this, QT, CD, member)) 09288 return; 09289 } 09290 } 09291 break; 09292 09293 case CXXCopyConstructor: 09294 if (RD->hasUserDeclaredCopyConstructor()) { 09295 SourceLocation CtorLoc = 09296 RD->getCopyConstructor(0)->getLocation(); 09297 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 09298 return; 09299 } 09300 break; 09301 09302 case CXXMoveConstructor: 09303 if (RD->hasUserDeclaredMoveConstructor()) { 09304 SourceLocation CtorLoc = RD->getMoveConstructor()->getLocation(); 09305 Diag(CtorLoc, diag::note_nontrivial_user_defined) << QT << member; 09306 return; 09307 } 09308 break; 09309 09310 case CXXCopyAssignment: 09311 if (RD->hasUserDeclaredCopyAssignment()) { 09312 // FIXME: this should use the location of the copy 09313 // assignment, not the type. 09314 SourceLocation TyLoc = RD->getLocStart(); 09315 Diag(TyLoc, diag::note_nontrivial_user_defined) << QT << member; 09316 return; 09317 } 09318 break; 09319 09320 case CXXMoveAssignment: 09321 if (RD->hasUserDeclaredMoveAssignment()) { 09322 SourceLocation AssignLoc = RD->getMoveAssignmentOperator()->getLocation(); 09323 Diag(AssignLoc, diag::note_nontrivial_user_defined) << QT << member; 09324 return; 09325 } 09326 break; 09327 09328 case CXXDestructor: 09329 if (RD->hasUserDeclaredDestructor()) { 09330 SourceLocation DtorLoc = LookupDestructor(RD)->getLocation(); 09331 Diag(DtorLoc, diag::note_nontrivial_user_defined) << QT << member; 09332 return; 09333 } 09334 break; 09335 } 09336 09337 typedef CXXRecordDecl::base_class_iterator base_iter; 09338 09339 // Virtual bases and members inhibit trivial copying/construction, 09340 // but not trivial destruction. 09341 if (member != CXXDestructor) { 09342 // Check for virtual bases. vbases includes indirect virtual bases, 09343 // so we just iterate through the direct bases. 09344 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) 09345 if (bi->isVirtual()) { 09346 SourceLocation BaseLoc = bi->getLocStart(); 09347 Diag(BaseLoc, diag::note_nontrivial_has_virtual) << QT << 1; 09348 return; 09349 } 09350 09351 // Check for virtual methods. 09352 typedef CXXRecordDecl::method_iterator meth_iter; 09353 for (meth_iter mi = RD->method_begin(), me = RD->method_end(); mi != me; 09354 ++mi) { 09355 if (mi->isVirtual()) { 09356 SourceLocation MLoc = mi->getLocStart(); 09357 Diag(MLoc, diag::note_nontrivial_has_virtual) << QT << 0; 09358 return; 09359 } 09360 } 09361 } 09362 09363 bool (CXXRecordDecl::*hasTrivial)() const; 09364 switch (member) { 09365 case CXXDefaultConstructor: 09366 hasTrivial = &CXXRecordDecl::hasTrivialDefaultConstructor; break; 09367 case CXXCopyConstructor: 09368 hasTrivial = &CXXRecordDecl::hasTrivialCopyConstructor; break; 09369 case CXXCopyAssignment: 09370 hasTrivial = &CXXRecordDecl::hasTrivialCopyAssignment; break; 09371 case CXXDestructor: 09372 hasTrivial = &CXXRecordDecl::hasTrivialDestructor; break; 09373 default: 09374 llvm_unreachable("unexpected special member"); 09375 } 09376 09377 // Check for nontrivial bases (and recurse). 09378 for (base_iter bi = RD->bases_begin(), be = RD->bases_end(); bi != be; ++bi) { 09379 const RecordType *BaseRT = bi->getType()->getAs<RecordType>(); 09380 assert(BaseRT && "Don't know how to handle dependent bases"); 09381 CXXRecordDecl *BaseRecTy = cast<CXXRecordDecl>(BaseRT->getDecl()); 09382 if (!(BaseRecTy->*hasTrivial)()) { 09383 SourceLocation BaseLoc = bi->getLocStart(); 09384 Diag(BaseLoc, diag::note_nontrivial_has_nontrivial) << QT << 1 << member; 09385 DiagnoseNontrivial(BaseRT, member); 09386 return; 09387 } 09388 } 09389 09390 // Check for nontrivial members (and recurse). 09391 typedef RecordDecl::field_iterator field_iter; 09392 for (field_iter fi = RD->field_begin(), fe = RD->field_end(); fi != fe; 09393 ++fi) { 09394 QualType EltTy = Context.getBaseElementType(fi->getType()); 09395 if (const RecordType *EltRT = EltTy->getAs<RecordType>()) { 09396 CXXRecordDecl* EltRD = cast<CXXRecordDecl>(EltRT->getDecl()); 09397 09398 if (!(EltRD->*hasTrivial)()) { 09399 SourceLocation FLoc = fi->getLocation(); 09400 Diag(FLoc, diag::note_nontrivial_has_nontrivial) << QT << 0 << member; 09401 DiagnoseNontrivial(EltRT, member); 09402 return; 09403 } 09404 } 09405 09406 if (EltTy->isObjCLifetimeType()) { 09407 switch (EltTy.getObjCLifetime()) { 09408 case Qualifiers::OCL_None: 09409 case Qualifiers::OCL_ExplicitNone: 09410 break; 09411 09412 case Qualifiers::OCL_Autoreleasing: 09413 case Qualifiers::OCL_Weak: 09414 case Qualifiers::OCL_Strong: 09415 Diag(fi->getLocation(), diag::note_nontrivial_objc_ownership) 09416 << QT << EltTy.getObjCLifetime(); 09417 return; 09418 } 09419 } 09420 } 09421 09422 llvm_unreachable("found no explanation for non-trivial member"); 09423 } 09424 09425 /// TranslateIvarVisibility - Translate visibility from a token ID to an 09426 /// AST enum value. 09427 static ObjCIvarDecl::AccessControl 09428 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 09429 switch (ivarVisibility) { 09430 default: llvm_unreachable("Unknown visitibility kind"); 09431 case tok::objc_private: return ObjCIvarDecl::Private; 09432 case tok::objc_public: return ObjCIvarDecl::Public; 09433 case tok::objc_protected: return ObjCIvarDecl::Protected; 09434 case tok::objc_package: return ObjCIvarDecl::Package; 09435 } 09436 } 09437 09438 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 09439 /// in order to create an IvarDecl object for it. 09440 Decl *Sema::ActOnIvar(Scope *S, 09441 SourceLocation DeclStart, 09442 Declarator &D, Expr *BitfieldWidth, 09443 tok::ObjCKeywordKind Visibility) { 09444 09445 IdentifierInfo *II = D.getIdentifier(); 09446 Expr *BitWidth = (Expr*)BitfieldWidth; 09447 SourceLocation Loc = DeclStart; 09448 if (II) Loc = D.getIdentifierLoc(); 09449 09450 // FIXME: Unnamed fields can be handled in various different ways, for 09451 // example, unnamed unions inject all members into the struct namespace! 09452 09453 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 09454 QualType T = TInfo->getType(); 09455 09456 if (BitWidth) { 09457 // 6.7.2.1p3, 6.7.2.1p4 09458 BitWidth = VerifyBitField(Loc, II, T, BitWidth).take(); 09459 if (!BitWidth) 09460 D.setInvalidType(); 09461 } else { 09462 // Not a bitfield. 09463 09464 // validate II. 09465 09466 } 09467 if (T->isReferenceType()) { 09468 Diag(Loc, diag::err_ivar_reference_type); 09469 D.setInvalidType(); 09470 } 09471 // C99 6.7.2.1p8: A member of a structure or union may have any type other 09472 // than a variably modified type. 09473 else if (T->isVariablyModifiedType()) { 09474 Diag(Loc, diag::err_typecheck_ivar_variable_size); 09475 D.setInvalidType(); 09476 } 09477 09478 // Get the visibility (access control) for this ivar. 09479 ObjCIvarDecl::AccessControl ac = 09480 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 09481 : ObjCIvarDecl::None; 09482 // Must set ivar's DeclContext to its enclosing interface. 09483 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 09484 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 09485 return 0; 09486 ObjCContainerDecl *EnclosingContext; 09487 if (ObjCImplementationDecl *IMPDecl = 09488 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 09489 if (!LangOpts.ObjCNonFragileABI2) { 09490 // Case of ivar declared in an implementation. Context is that of its class. 09491 EnclosingContext = IMPDecl->getClassInterface(); 09492 assert(EnclosingContext && "Implementation has no class interface!"); 09493 } 09494 else 09495 EnclosingContext = EnclosingDecl; 09496 } else { 09497 if (ObjCCategoryDecl *CDecl = 09498 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 09499 if (!LangOpts.ObjCNonFragileABI2 || !CDecl->IsClassExtension()) { 09500 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 09501 return 0; 09502 } 09503 } 09504 EnclosingContext = EnclosingDecl; 09505 } 09506 09507 // Construct the decl. 09508 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 09509 DeclStart, Loc, II, T, 09510 TInfo, ac, (Expr *)BitfieldWidth); 09511 09512 if (II) { 09513 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 09514 ForRedeclaration); 09515 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 09516 && !isa<TagDecl>(PrevDecl)) { 09517 Diag(Loc, diag::err_duplicate_member) << II; 09518 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 09519 NewID->setInvalidDecl(); 09520 } 09521 } 09522 09523 // Process attributes attached to the ivar. 09524 ProcessDeclAttributes(S, NewID, D); 09525 09526 if (D.isInvalidType()) 09527 NewID->setInvalidDecl(); 09528 09529 // In ARC, infer 'retaining' for ivars of retainable type. 09530 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 09531 NewID->setInvalidDecl(); 09532 09533 if (D.getDeclSpec().isModulePrivateSpecified()) 09534 NewID->setModulePrivate(); 09535 09536 if (II) { 09537 // FIXME: When interfaces are DeclContexts, we'll need to add 09538 // these to the interface. 09539 S->AddDecl(NewID); 09540 IdResolver.AddDecl(NewID); 09541 } 09542 09543 if (LangOpts.ObjCNonFragileABI2 && 09544 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 09545 Diag(Loc, diag::warn_ivars_in_interface); 09546 09547 return NewID; 09548 } 09549 09550 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 09551 /// class and class extensions. For every class @interface and class 09552 /// extension @interface, if the last ivar is a bitfield of any type, 09553 /// then add an implicit `char :0` ivar to the end of that interface. 09554 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 09555 SmallVectorImpl<Decl *> &AllIvarDecls) { 09556 if (!LangOpts.ObjCNonFragileABI2 || AllIvarDecls.empty()) 09557 return; 09558 09559 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 09560 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 09561 09562 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 09563 return; 09564 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 09565 if (!ID) { 09566 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 09567 if (!CD->IsClassExtension()) 09568 return; 09569 } 09570 // No need to add this to end of @implementation. 09571 else 09572 return; 09573 } 09574 // All conditions are met. Add a new bitfield to the tail end of ivars. 09575 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 09576 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 09577 09578 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 09579 DeclLoc, DeclLoc, 0, 09580 Context.CharTy, 09581 Context.getTrivialTypeSourceInfo(Context.CharTy, 09582 DeclLoc), 09583 ObjCIvarDecl::Private, BW, 09584 true); 09585 AllIvarDecls.push_back(Ivar); 09586 } 09587 09588 void Sema::ActOnFields(Scope* S, 09589 SourceLocation RecLoc, Decl *EnclosingDecl, 09590 llvm::ArrayRef<Decl *> Fields, 09591 SourceLocation LBrac, SourceLocation RBrac, 09592 AttributeList *Attr) { 09593 assert(EnclosingDecl && "missing record or interface decl"); 09594 09595 // If the decl this is being inserted into is invalid, then it may be a 09596 // redeclaration or some other bogus case. Don't try to add fields to it. 09597 if (EnclosingDecl->isInvalidDecl()) 09598 return; 09599 09600 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 09601 09602 // Start counting up the number of named members; make sure to include 09603 // members of anonymous structs and unions in the total. 09604 unsigned NumNamedMembers = 0; 09605 if (Record) { 09606 for (RecordDecl::decl_iterator i = Record->decls_begin(), 09607 e = Record->decls_end(); i != e; i++) { 09608 if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(*i)) 09609 if (IFD->getDeclName()) 09610 ++NumNamedMembers; 09611 } 09612 } 09613 09614 // Verify that all the fields are okay. 09615 SmallVector<FieldDecl*, 32> RecFields; 09616 09617 bool ARCErrReported = false; 09618 for (llvm::ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 09619 i != end; ++i) { 09620 FieldDecl *FD = cast<FieldDecl>(*i); 09621 09622 // Get the type for the field. 09623 const Type *FDTy = FD->getType().getTypePtr(); 09624 09625 if (!FD->isAnonymousStructOrUnion()) { 09626 // Remember all fields written by the user. 09627 RecFields.push_back(FD); 09628 } 09629 09630 // If the field is already invalid for some reason, don't emit more 09631 // diagnostics about it. 09632 if (FD->isInvalidDecl()) { 09633 EnclosingDecl->setInvalidDecl(); 09634 continue; 09635 } 09636 09637 // C99 6.7.2.1p2: 09638 // A structure or union shall not contain a member with 09639 // incomplete or function type (hence, a structure shall not 09640 // contain an instance of itself, but may contain a pointer to 09641 // an instance of itself), except that the last member of a 09642 // structure with more than one named member may have incomplete 09643 // array type; such a structure (and any union containing, 09644 // possibly recursively, a member that is such a structure) 09645 // shall not be a member of a structure or an element of an 09646 // array. 09647 if (FDTy->isFunctionType()) { 09648 // Field declared as a function. 09649 Diag(FD->getLocation(), diag::err_field_declared_as_function) 09650 << FD->getDeclName(); 09651 FD->setInvalidDecl(); 09652 EnclosingDecl->setInvalidDecl(); 09653 continue; 09654 } else if (FDTy->isIncompleteArrayType() && Record && 09655 ((i + 1 == Fields.end() && !Record->isUnion()) || 09656 ((getLangOpts().MicrosoftExt || 09657 getLangOpts().CPlusPlus) && 09658 (i + 1 == Fields.end() || Record->isUnion())))) { 09659 // Flexible array member. 09660 // Microsoft and g++ is more permissive regarding flexible array. 09661 // It will accept flexible array in union and also 09662 // as the sole element of a struct/class. 09663 if (getLangOpts().MicrosoftExt) { 09664 if (Record->isUnion()) 09665 Diag(FD->getLocation(), diag::ext_flexible_array_union_ms) 09666 << FD->getDeclName(); 09667 else if (Fields.size() == 1) 09668 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_ms) 09669 << FD->getDeclName() << Record->getTagKind(); 09670 } else if (getLangOpts().CPlusPlus) { 09671 if (Record->isUnion()) 09672 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 09673 << FD->getDeclName(); 09674 else if (Fields.size() == 1) 09675 Diag(FD->getLocation(), diag::ext_flexible_array_empty_aggregate_gnu) 09676 << FD->getDeclName() << Record->getTagKind(); 09677 } else if (!getLangOpts().C99) { 09678 if (Record->isUnion()) 09679 Diag(FD->getLocation(), diag::ext_flexible_array_union_gnu) 09680 << FD->getDeclName(); 09681 else 09682 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 09683 << FD->getDeclName() << Record->getTagKind(); 09684 } else if (NumNamedMembers < 1) { 09685 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct) 09686 << FD->getDeclName(); 09687 FD->setInvalidDecl(); 09688 EnclosingDecl->setInvalidDecl(); 09689 continue; 09690 } 09691 if (!FD->getType()->isDependentType() && 09692 !Context.getBaseElementType(FD->getType()).isPODType(Context)) { 09693 Diag(FD->getLocation(), diag::err_flexible_array_has_nonpod_type) 09694 << FD->getDeclName() << FD->getType(); 09695 FD->setInvalidDecl(); 09696 EnclosingDecl->setInvalidDecl(); 09697 continue; 09698 } 09699 // Okay, we have a legal flexible array member at the end of the struct. 09700 if (Record) 09701 Record->setHasFlexibleArrayMember(true); 09702 } else if (!FDTy->isDependentType() && 09703 RequireCompleteType(FD->getLocation(), FD->getType(), 09704 diag::err_field_incomplete)) { 09705 // Incomplete type 09706 FD->setInvalidDecl(); 09707 EnclosingDecl->setInvalidDecl(); 09708 continue; 09709 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 09710 if (FDTTy->getDecl()->hasFlexibleArrayMember()) { 09711 // If this is a member of a union, then entire union becomes "flexible". 09712 if (Record && Record->isUnion()) { 09713 Record->setHasFlexibleArrayMember(true); 09714 } else { 09715 // If this is a struct/class and this is not the last element, reject 09716 // it. Note that GCC supports variable sized arrays in the middle of 09717 // structures. 09718 if (i + 1 != Fields.end()) 09719 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 09720 << FD->getDeclName() << FD->getType(); 09721 else { 09722 // We support flexible arrays at the end of structs in 09723 // other structs as an extension. 09724 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 09725 << FD->getDeclName(); 09726 if (Record) 09727 Record->setHasFlexibleArrayMember(true); 09728 } 09729 } 09730 } 09731 if (Record && FDTTy->getDecl()->hasObjectMember()) 09732 Record->setHasObjectMember(true); 09733 } else if (FDTy->isObjCObjectType()) { 09734 /// A field cannot be an Objective-c object 09735 Diag(FD->getLocation(), diag::err_statically_allocated_object) 09736 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 09737 QualType T = Context.getObjCObjectPointerType(FD->getType()); 09738 FD->setType(T); 09739 } 09740 else if (!getLangOpts().CPlusPlus) { 09741 if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported) { 09742 // It's an error in ARC if a field has lifetime. 09743 // We don't want to report this in a system header, though, 09744 // so we just make the field unavailable. 09745 // FIXME: that's really not sufficient; we need to make the type 09746 // itself invalid to, say, initialize or copy. 09747 QualType T = FD->getType(); 09748 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 09749 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 09750 SourceLocation loc = FD->getLocation(); 09751 if (getSourceManager().isInSystemHeader(loc)) { 09752 if (!FD->hasAttr<UnavailableAttr>()) { 09753 FD->addAttr(new (Context) UnavailableAttr(loc, Context, 09754 "this system field has retaining ownership")); 09755 } 09756 } else { 09757 Diag(FD->getLocation(), diag::err_arc_objc_object_in_struct) 09758 << T->isBlockPointerType(); 09759 } 09760 ARCErrReported = true; 09761 } 09762 } 09763 else if (getLangOpts().ObjC1 && 09764 getLangOpts().getGC() != LangOptions::NonGC && 09765 Record && !Record->hasObjectMember()) { 09766 if (FD->getType()->isObjCObjectPointerType() || 09767 FD->getType().isObjCGCStrong()) 09768 Record->setHasObjectMember(true); 09769 else if (Context.getAsArrayType(FD->getType())) { 09770 QualType BaseType = Context.getBaseElementType(FD->getType()); 09771 if (BaseType->isRecordType() && 09772 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 09773 Record->setHasObjectMember(true); 09774 else if (BaseType->isObjCObjectPointerType() || 09775 BaseType.isObjCGCStrong()) 09776 Record->setHasObjectMember(true); 09777 } 09778 } 09779 } 09780 // Keep track of the number of named members. 09781 if (FD->getIdentifier()) 09782 ++NumNamedMembers; 09783 } 09784 09785 // Okay, we successfully defined 'Record'. 09786 if (Record) { 09787 bool Completed = false; 09788 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 09789 if (!CXXRecord->isInvalidDecl()) { 09790 // Set access bits correctly on the directly-declared conversions. 09791 UnresolvedSetImpl *Convs = CXXRecord->getConversionFunctions(); 09792 for (UnresolvedSetIterator I = Convs->begin(), E = Convs->end(); 09793 I != E; ++I) 09794 Convs->setAccess(I, (*I)->getAccess()); 09795 09796 if (!CXXRecord->isDependentType()) { 09797 // Objective-C Automatic Reference Counting: 09798 // If a class has a non-static data member of Objective-C pointer 09799 // type (or array thereof), it is a non-POD type and its 09800 // default constructor (if any), copy constructor, copy assignment 09801 // operator, and destructor are non-trivial. 09802 // 09803 // This rule is also handled by CXXRecordDecl::completeDefinition(). 09804 // However, here we check whether this particular class is only 09805 // non-POD because of the presence of an Objective-C pointer member. 09806 // If so, objects of this type cannot be shared between code compiled 09807 // with instant objects and code compiled with manual retain/release. 09808 if (getLangOpts().ObjCAutoRefCount && 09809 CXXRecord->hasObjectMember() && 09810 CXXRecord->getLinkage() == ExternalLinkage) { 09811 if (CXXRecord->isPOD()) { 09812 Diag(CXXRecord->getLocation(), 09813 diag::warn_arc_non_pod_class_with_object_member) 09814 << CXXRecord; 09815 } else { 09816 // FIXME: Fix-Its would be nice here, but finding a good location 09817 // for them is going to be tricky. 09818 if (CXXRecord->hasTrivialCopyConstructor()) 09819 Diag(CXXRecord->getLocation(), 09820 diag::warn_arc_trivial_member_function_with_object_member) 09821 << CXXRecord << 0; 09822 if (CXXRecord->hasTrivialCopyAssignment()) 09823 Diag(CXXRecord->getLocation(), 09824 diag::warn_arc_trivial_member_function_with_object_member) 09825 << CXXRecord << 1; 09826 if (CXXRecord->hasTrivialDestructor()) 09827 Diag(CXXRecord->getLocation(), 09828 diag::warn_arc_trivial_member_function_with_object_member) 09829 << CXXRecord << 2; 09830 } 09831 } 09832 09833 // Adjust user-defined destructor exception spec. 09834 if (getLangOpts().CPlusPlus0x && 09835 CXXRecord->hasUserDeclaredDestructor()) 09836 AdjustDestructorExceptionSpec(CXXRecord,CXXRecord->getDestructor()); 09837 09838 // Add any implicitly-declared members to this class. 09839 AddImplicitlyDeclaredMembersToClass(CXXRecord); 09840 09841 // If we have virtual base classes, we may end up finding multiple 09842 // final overriders for a given virtual function. Check for this 09843 // problem now. 09844 if (CXXRecord->getNumVBases()) { 09845 CXXFinalOverriderMap FinalOverriders; 09846 CXXRecord->getFinalOverriders(FinalOverriders); 09847 09848 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 09849 MEnd = FinalOverriders.end(); 09850 M != MEnd; ++M) { 09851 for (OverridingMethods::iterator SO = M->second.begin(), 09852 SOEnd = M->second.end(); 09853 SO != SOEnd; ++SO) { 09854 assert(SO->second.size() > 0 && 09855 "Virtual function without overridding functions?"); 09856 if (SO->second.size() == 1) 09857 continue; 09858 09859 // C++ [class.virtual]p2: 09860 // In a derived class, if a virtual member function of a base 09861 // class subobject has more than one final overrider the 09862 // program is ill-formed. 09863 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 09864 << (NamedDecl *)M->first << Record; 09865 Diag(M->first->getLocation(), 09866 diag::note_overridden_virtual_function); 09867 for (OverridingMethods::overriding_iterator 09868 OM = SO->second.begin(), 09869 OMEnd = SO->second.end(); 09870 OM != OMEnd; ++OM) 09871 Diag(OM->Method->getLocation(), diag::note_final_overrider) 09872 << (NamedDecl *)M->first << OM->Method->getParent(); 09873 09874 Record->setInvalidDecl(); 09875 } 09876 } 09877 CXXRecord->completeDefinition(&FinalOverriders); 09878 Completed = true; 09879 } 09880 } 09881 } 09882 } 09883 09884 if (!Completed) 09885 Record->completeDefinition(); 09886 09887 } else { 09888 ObjCIvarDecl **ClsFields = 09889 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 09890 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 09891 ID->setEndOfDefinitionLoc(RBrac); 09892 // Add ivar's to class's DeclContext. 09893 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 09894 ClsFields[i]->setLexicalDeclContext(ID); 09895 ID->addDecl(ClsFields[i]); 09896 } 09897 // Must enforce the rule that ivars in the base classes may not be 09898 // duplicates. 09899 if (ID->getSuperClass()) 09900 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 09901 } else if (ObjCImplementationDecl *IMPDecl = 09902 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 09903 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 09904 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 09905 // Ivar declared in @implementation never belongs to the implementation. 09906 // Only it is in implementation's lexical context. 09907 ClsFields[I]->setLexicalDeclContext(IMPDecl); 09908 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 09909 IMPDecl->setIvarLBraceLoc(LBrac); 09910 IMPDecl->setIvarRBraceLoc(RBrac); 09911 } else if (ObjCCategoryDecl *CDecl = 09912 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 09913 // case of ivars in class extension; all other cases have been 09914 // reported as errors elsewhere. 09915 // FIXME. Class extension does not have a LocEnd field. 09916 // CDecl->setLocEnd(RBrac); 09917 // Add ivar's to class extension's DeclContext. 09918 // Diagnose redeclaration of private ivars. 09919 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 09920 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 09921 if (IDecl) { 09922 if (const ObjCIvarDecl *ClsIvar = 09923 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 09924 Diag(ClsFields[i]->getLocation(), 09925 diag::err_duplicate_ivar_declaration); 09926 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 09927 continue; 09928 } 09929 for (const ObjCCategoryDecl *ClsExtDecl = 09930 IDecl->getFirstClassExtension(); 09931 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) { 09932 if (const ObjCIvarDecl *ClsExtIvar = 09933 ClsExtDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 09934 Diag(ClsFields[i]->getLocation(), 09935 diag::err_duplicate_ivar_declaration); 09936 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 09937 continue; 09938 } 09939 } 09940 } 09941 ClsFields[i]->setLexicalDeclContext(CDecl); 09942 CDecl->addDecl(ClsFields[i]); 09943 } 09944 CDecl->setIvarLBraceLoc(LBrac); 09945 CDecl->setIvarRBraceLoc(RBrac); 09946 } 09947 } 09948 09949 if (Attr) 09950 ProcessDeclAttributeList(S, Record, Attr); 09951 09952 // If there's a #pragma GCC visibility in scope, and this isn't a subclass, 09953 // set the visibility of this record. 09954 if (Record && !Record->getDeclContext()->isRecord()) 09955 AddPushedVisibilityAttribute(Record); 09956 } 09957 09958 /// \brief Determine whether the given integral value is representable within 09959 /// the given type T. 09960 static bool isRepresentableIntegerValue(ASTContext &Context, 09961 llvm::APSInt &Value, 09962 QualType T) { 09963 assert(T->isIntegralType(Context) && "Integral type required!"); 09964 unsigned BitWidth = Context.getIntWidth(T); 09965 09966 if (Value.isUnsigned() || Value.isNonNegative()) { 09967 if (T->isSignedIntegerOrEnumerationType()) 09968 --BitWidth; 09969 return Value.getActiveBits() <= BitWidth; 09970 } 09971 return Value.getMinSignedBits() <= BitWidth; 09972 } 09973 09974 // \brief Given an integral type, return the next larger integral type 09975 // (or a NULL type of no such type exists). 09976 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 09977 // FIXME: Int128/UInt128 support, which also needs to be introduced into 09978 // enum checking below. 09979 assert(T->isIntegralType(Context) && "Integral type required!"); 09980 const unsigned NumTypes = 4; 09981 QualType SignedIntegralTypes[NumTypes] = { 09982 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 09983 }; 09984 QualType UnsignedIntegralTypes[NumTypes] = { 09985 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 09986 Context.UnsignedLongLongTy 09987 }; 09988 09989 unsigned BitWidth = Context.getTypeSize(T); 09990 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 09991 : UnsignedIntegralTypes; 09992 for (unsigned I = 0; I != NumTypes; ++I) 09993 if (Context.getTypeSize(Types[I]) > BitWidth) 09994 return Types[I]; 09995 09996 return QualType(); 09997 } 09998 09999 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 10000 EnumConstantDecl *LastEnumConst, 10001 SourceLocation IdLoc, 10002 IdentifierInfo *Id, 10003 Expr *Val) { 10004 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 10005 llvm::APSInt EnumVal(IntWidth); 10006 QualType EltTy; 10007 10008 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 10009 Val = 0; 10010 10011 if (Val) 10012 Val = DefaultLvalueConversion(Val).take(); 10013 10014 if (Val) { 10015 if (Enum->isDependentType() || Val->isTypeDependent()) 10016 EltTy = Context.DependentTy; 10017 else { 10018 SourceLocation ExpLoc; 10019 if (getLangOpts().CPlusPlus0x && Enum->isFixed() && 10020 !getLangOpts().MicrosoftMode) { 10021 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 10022 // constant-expression in the enumerator-definition shall be a converted 10023 // constant expression of the underlying type. 10024 EltTy = Enum->getIntegerType(); 10025 ExprResult Converted = 10026 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 10027 CCEK_Enumerator); 10028 if (Converted.isInvalid()) 10029 Val = 0; 10030 else 10031 Val = Converted.take(); 10032 } else if (!Val->isValueDependent() && 10033 !(Val = VerifyIntegerConstantExpression(Val, 10034 &EnumVal).take())) { 10035 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 10036 } else { 10037 if (Enum->isFixed()) { 10038 EltTy = Enum->getIntegerType(); 10039 10040 // In Obj-C and Microsoft mode, require the enumeration value to be 10041 // representable in the underlying type of the enumeration. In C++11, 10042 // we perform a non-narrowing conversion as part of converted constant 10043 // expression checking. 10044 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 10045 if (getLangOpts().MicrosoftMode) { 10046 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 10047 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 10048 } else 10049 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 10050 } else 10051 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).take(); 10052 } else if (getLangOpts().CPlusPlus) { 10053 // C++11 [dcl.enum]p5: 10054 // If the underlying type is not fixed, the type of each enumerator 10055 // is the type of its initializing value: 10056 // - If an initializer is specified for an enumerator, the 10057 // initializing value has the same type as the expression. 10058 EltTy = Val->getType(); 10059 } else { 10060 // C99 6.7.2.2p2: 10061 // The expression that defines the value of an enumeration constant 10062 // shall be an integer constant expression that has a value 10063 // representable as an int. 10064 10065 // Complain if the value is not representable in an int. 10066 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 10067 Diag(IdLoc, diag::ext_enum_value_not_int) 10068 << EnumVal.toString(10) << Val->getSourceRange() 10069 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 10070 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 10071 // Force the type of the expression to 'int'. 10072 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).take(); 10073 } 10074 EltTy = Val->getType(); 10075 } 10076 } 10077 } 10078 } 10079 10080 if (!Val) { 10081 if (Enum->isDependentType()) 10082 EltTy = Context.DependentTy; 10083 else if (!LastEnumConst) { 10084 // C++0x [dcl.enum]p5: 10085 // If the underlying type is not fixed, the type of each enumerator 10086 // is the type of its initializing value: 10087 // - If no initializer is specified for the first enumerator, the 10088 // initializing value has an unspecified integral type. 10089 // 10090 // GCC uses 'int' for its unspecified integral type, as does 10091 // C99 6.7.2.2p3. 10092 if (Enum->isFixed()) { 10093 EltTy = Enum->getIntegerType(); 10094 } 10095 else { 10096 EltTy = Context.IntTy; 10097 } 10098 } else { 10099 // Assign the last value + 1. 10100 EnumVal = LastEnumConst->getInitVal(); 10101 ++EnumVal; 10102 EltTy = LastEnumConst->getType(); 10103 10104 // Check for overflow on increment. 10105 if (EnumVal < LastEnumConst->getInitVal()) { 10106 // C++0x [dcl.enum]p5: 10107 // If the underlying type is not fixed, the type of each enumerator 10108 // is the type of its initializing value: 10109 // 10110 // - Otherwise the type of the initializing value is the same as 10111 // the type of the initializing value of the preceding enumerator 10112 // unless the incremented value is not representable in that type, 10113 // in which case the type is an unspecified integral type 10114 // sufficient to contain the incremented value. If no such type 10115 // exists, the program is ill-formed. 10116 QualType T = getNextLargerIntegralType(Context, EltTy); 10117 if (T.isNull() || Enum->isFixed()) { 10118 // There is no integral type larger enough to represent this 10119 // value. Complain, then allow the value to wrap around. 10120 EnumVal = LastEnumConst->getInitVal(); 10121 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 10122 ++EnumVal; 10123 if (Enum->isFixed()) 10124 // When the underlying type is fixed, this is ill-formed. 10125 Diag(IdLoc, diag::err_enumerator_wrapped) 10126 << EnumVal.toString(10) 10127 << EltTy; 10128 else 10129 Diag(IdLoc, diag::warn_enumerator_too_large) 10130 << EnumVal.toString(10); 10131 } else { 10132 EltTy = T; 10133 } 10134 10135 // Retrieve the last enumerator's value, extent that type to the 10136 // type that is supposed to be large enough to represent the incremented 10137 // value, then increment. 10138 EnumVal = LastEnumConst->getInitVal(); 10139 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 10140 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 10141 ++EnumVal; 10142 10143 // If we're not in C++, diagnose the overflow of enumerator values, 10144 // which in C99 means that the enumerator value is not representable in 10145 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 10146 // permits enumerator values that are representable in some larger 10147 // integral type. 10148 if (!getLangOpts().CPlusPlus && !T.isNull()) 10149 Diag(IdLoc, diag::warn_enum_value_overflow); 10150 } else if (!getLangOpts().CPlusPlus && 10151 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 10152 // Enforce C99 6.7.2.2p2 even when we compute the next value. 10153 Diag(IdLoc, diag::ext_enum_value_not_int) 10154 << EnumVal.toString(10) << 1; 10155 } 10156 } 10157 } 10158 10159 if (!EltTy->isDependentType()) { 10160 // Make the enumerator value match the signedness and size of the 10161 // enumerator's type. 10162 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 10163 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 10164 } 10165 10166 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 10167 Val, EnumVal); 10168 } 10169 10170 10171 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 10172 SourceLocation IdLoc, IdentifierInfo *Id, 10173 AttributeList *Attr, 10174 SourceLocation EqualLoc, Expr *Val) { 10175 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 10176 EnumConstantDecl *LastEnumConst = 10177 cast_or_null<EnumConstantDecl>(lastEnumConst); 10178 10179 // The scope passed in may not be a decl scope. Zip up the scope tree until 10180 // we find one that is. 10181 S = getNonFieldDeclScope(S); 10182 10183 // Verify that there isn't already something declared with this name in this 10184 // scope. 10185 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 10186 ForRedeclaration); 10187 if (PrevDecl && PrevDecl->isTemplateParameter()) { 10188 // Maybe we will complain about the shadowed template parameter. 10189 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 10190 // Just pretend that we didn't see the previous declaration. 10191 PrevDecl = 0; 10192 } 10193 10194 if (PrevDecl) { 10195 // When in C++, we may get a TagDecl with the same name; in this case the 10196 // enum constant will 'hide' the tag. 10197 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 10198 "Received TagDecl when not in C++!"); 10199 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 10200 if (isa<EnumConstantDecl>(PrevDecl)) 10201 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 10202 else 10203 Diag(IdLoc, diag::err_redefinition) << Id; 10204 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 10205 return 0; 10206 } 10207 } 10208 10209 // C++ [class.mem]p13: 10210 // If T is the name of a class, then each of the following shall have a 10211 // name different from T: 10212 // - every enumerator of every member of class T that is an enumerated 10213 // type 10214 if (CXXRecordDecl *Record 10215 = dyn_cast<CXXRecordDecl>( 10216 TheEnumDecl->getDeclContext()->getRedeclContext())) 10217 if (Record->getIdentifier() && Record->getIdentifier() == Id) 10218 Diag(IdLoc, diag::err_member_name_of_class) << Id; 10219 10220 EnumConstantDecl *New = 10221 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 10222 10223 if (New) { 10224 // Process attributes. 10225 if (Attr) ProcessDeclAttributeList(S, New, Attr); 10226 10227 // Register this decl in the current scope stack. 10228 New->setAccess(TheEnumDecl->getAccess()); 10229 PushOnScopeChains(New, S); 10230 } 10231 10232 return New; 10233 } 10234 10235 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 10236 SourceLocation RBraceLoc, Decl *EnumDeclX, 10237 Decl **Elements, unsigned NumElements, 10238 Scope *S, AttributeList *Attr) { 10239 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 10240 QualType EnumType = Context.getTypeDeclType(Enum); 10241 10242 if (Attr) 10243 ProcessDeclAttributeList(S, Enum, Attr); 10244 10245 if (Enum->isDependentType()) { 10246 for (unsigned i = 0; i != NumElements; ++i) { 10247 EnumConstantDecl *ECD = 10248 cast_or_null<EnumConstantDecl>(Elements[i]); 10249 if (!ECD) continue; 10250 10251 ECD->setType(EnumType); 10252 } 10253 10254 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 10255 return; 10256 } 10257 10258 // TODO: If the result value doesn't fit in an int, it must be a long or long 10259 // long value. ISO C does not support this, but GCC does as an extension, 10260 // emit a warning. 10261 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 10262 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 10263 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 10264 10265 // Verify that all the values are okay, compute the size of the values, and 10266 // reverse the list. 10267 unsigned NumNegativeBits = 0; 10268 unsigned NumPositiveBits = 0; 10269 10270 // Keep track of whether all elements have type int. 10271 bool AllElementsInt = true; 10272 10273 for (unsigned i = 0; i != NumElements; ++i) { 10274 EnumConstantDecl *ECD = 10275 cast_or_null<EnumConstantDecl>(Elements[i]); 10276 if (!ECD) continue; // Already issued a diagnostic. 10277 10278 const llvm::APSInt &InitVal = ECD->getInitVal(); 10279 10280 // Keep track of the size of positive and negative values. 10281 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 10282 NumPositiveBits = std::max(NumPositiveBits, 10283 (unsigned)InitVal.getActiveBits()); 10284 else 10285 NumNegativeBits = std::max(NumNegativeBits, 10286 (unsigned)InitVal.getMinSignedBits()); 10287 10288 // Keep track of whether every enum element has type int (very commmon). 10289 if (AllElementsInt) 10290 AllElementsInt = ECD->getType() == Context.IntTy; 10291 } 10292 10293 // Figure out the type that should be used for this enum. 10294 QualType BestType; 10295 unsigned BestWidth; 10296 10297 // C++0x N3000 [conv.prom]p3: 10298 // An rvalue of an unscoped enumeration type whose underlying 10299 // type is not fixed can be converted to an rvalue of the first 10300 // of the following types that can represent all the values of 10301 // the enumeration: int, unsigned int, long int, unsigned long 10302 // int, long long int, or unsigned long long int. 10303 // C99 6.4.4.3p2: 10304 // An identifier declared as an enumeration constant has type int. 10305 // The C99 rule is modified by a gcc extension 10306 QualType BestPromotionType; 10307 10308 bool Packed = Enum->getAttr<PackedAttr>() ? true : false; 10309 // -fshort-enums is the equivalent to specifying the packed attribute on all 10310 // enum definitions. 10311 if (LangOpts.ShortEnums) 10312 Packed = true; 10313 10314 if (Enum->isFixed()) { 10315 BestType = Enum->getIntegerType(); 10316 if (BestType->isPromotableIntegerType()) 10317 BestPromotionType = Context.getPromotedIntegerType(BestType); 10318 else 10319 BestPromotionType = BestType; 10320 // We don't need to set BestWidth, because BestType is going to be the type 10321 // of the enumerators, but we do anyway because otherwise some compilers 10322 // warn that it might be used uninitialized. 10323 BestWidth = CharWidth; 10324 } 10325 else if (NumNegativeBits) { 10326 // If there is a negative value, figure out the smallest integer type (of 10327 // int/long/longlong) that fits. 10328 // If it's packed, check also if it fits a char or a short. 10329 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 10330 BestType = Context.SignedCharTy; 10331 BestWidth = CharWidth; 10332 } else if (Packed && NumNegativeBits <= ShortWidth && 10333 NumPositiveBits < ShortWidth) { 10334 BestType = Context.ShortTy; 10335 BestWidth = ShortWidth; 10336 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 10337 BestType = Context.IntTy; 10338 BestWidth = IntWidth; 10339 } else { 10340 BestWidth = Context.getTargetInfo().getLongWidth(); 10341 10342 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 10343 BestType = Context.LongTy; 10344 } else { 10345 BestWidth = Context.getTargetInfo().getLongLongWidth(); 10346 10347 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 10348 Diag(Enum->getLocation(), diag::warn_enum_too_large); 10349 BestType = Context.LongLongTy; 10350 } 10351 } 10352 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 10353 } else { 10354 // If there is no negative value, figure out the smallest type that fits 10355 // all of the enumerator values. 10356 // If it's packed, check also if it fits a char or a short. 10357 if (Packed && NumPositiveBits <= CharWidth) { 10358 BestType = Context.UnsignedCharTy; 10359 BestPromotionType = Context.IntTy; 10360 BestWidth = CharWidth; 10361 } else if (Packed && NumPositiveBits <= ShortWidth) { 10362 BestType = Context.UnsignedShortTy; 10363 BestPromotionType = Context.IntTy; 10364 BestWidth = ShortWidth; 10365 } else if (NumPositiveBits <= IntWidth) { 10366 BestType = Context.UnsignedIntTy; 10367 BestWidth = IntWidth; 10368 BestPromotionType 10369 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 10370 ? Context.UnsignedIntTy : Context.IntTy; 10371 } else if (NumPositiveBits <= 10372 (BestWidth = Context.getTargetInfo().getLongWidth())) { 10373 BestType = Context.UnsignedLongTy; 10374 BestPromotionType 10375 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 10376 ? Context.UnsignedLongTy : Context.LongTy; 10377 } else { 10378 BestWidth = Context.getTargetInfo().getLongLongWidth(); 10379 assert(NumPositiveBits <= BestWidth && 10380 "How could an initializer get larger than ULL?"); 10381 BestType = Context.UnsignedLongLongTy; 10382 BestPromotionType 10383 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 10384 ? Context.UnsignedLongLongTy : Context.LongLongTy; 10385 } 10386 } 10387 10388 // Loop over all of the enumerator constants, changing their types to match 10389 // the type of the enum if needed. 10390 for (unsigned i = 0; i != NumElements; ++i) { 10391 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 10392 if (!ECD) continue; // Already issued a diagnostic. 10393 10394 // Standard C says the enumerators have int type, but we allow, as an 10395 // extension, the enumerators to be larger than int size. If each 10396 // enumerator value fits in an int, type it as an int, otherwise type it the 10397 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 10398 // that X has type 'int', not 'unsigned'. 10399 10400 // Determine whether the value fits into an int. 10401 llvm::APSInt InitVal = ECD->getInitVal(); 10402 10403 // If it fits into an integer type, force it. Otherwise force it to match 10404 // the enum decl type. 10405 QualType NewTy; 10406 unsigned NewWidth; 10407 bool NewSign; 10408 if (!getLangOpts().CPlusPlus && 10409 !Enum->isFixed() && 10410 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 10411 NewTy = Context.IntTy; 10412 NewWidth = IntWidth; 10413 NewSign = true; 10414 } else if (ECD->getType() == BestType) { 10415 // Already the right type! 10416 if (getLangOpts().CPlusPlus) 10417 // C++ [dcl.enum]p4: Following the closing brace of an 10418 // enum-specifier, each enumerator has the type of its 10419 // enumeration. 10420 ECD->setType(EnumType); 10421 continue; 10422 } else { 10423 NewTy = BestType; 10424 NewWidth = BestWidth; 10425 NewSign = BestType->isSignedIntegerOrEnumerationType(); 10426 } 10427 10428 // Adjust the APSInt value. 10429 InitVal = InitVal.extOrTrunc(NewWidth); 10430 InitVal.setIsSigned(NewSign); 10431 ECD->setInitVal(InitVal); 10432 10433 // Adjust the Expr initializer and type. 10434 if (ECD->getInitExpr() && 10435 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 10436 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 10437 CK_IntegralCast, 10438 ECD->getInitExpr(), 10439 /*base paths*/ 0, 10440 VK_RValue)); 10441 if (getLangOpts().CPlusPlus) 10442 // C++ [dcl.enum]p4: Following the closing brace of an 10443 // enum-specifier, each enumerator has the type of its 10444 // enumeration. 10445 ECD->setType(EnumType); 10446 else 10447 ECD->setType(NewTy); 10448 } 10449 10450 Enum->completeDefinition(BestType, BestPromotionType, 10451 NumPositiveBits, NumNegativeBits); 10452 10453 // If we're declaring a function, ensure this decl isn't forgotten about - 10454 // it needs to go into the function scope. 10455 if (InFunctionDeclarator) 10456 DeclsInPrototypeScope.push_back(Enum); 10457 10458 } 10459 10460 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 10461 SourceLocation StartLoc, 10462 SourceLocation EndLoc) { 10463 StringLiteral *AsmString = cast<StringLiteral>(expr); 10464 10465 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 10466 AsmString, StartLoc, 10467 EndLoc); 10468 CurContext->addDecl(New); 10469 return New; 10470 } 10471 10472 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 10473 SourceLocation ImportLoc, 10474 ModuleIdPath Path) { 10475 Module *Mod = PP.getModuleLoader().loadModule(ImportLoc, Path, 10476 Module::AllVisible, 10477 /*IsIncludeDirective=*/false); 10478 if (!Mod) 10479 return true; 10480 10481 llvm::SmallVector<SourceLocation, 2> IdentifierLocs; 10482 Module *ModCheck = Mod; 10483 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 10484 // If we've run out of module parents, just drop the remaining identifiers. 10485 // We need the length to be consistent. 10486 if (!ModCheck) 10487 break; 10488 ModCheck = ModCheck->Parent; 10489 10490 IdentifierLocs.push_back(Path[I].second); 10491 } 10492 10493 ImportDecl *Import = ImportDecl::Create(Context, 10494 Context.getTranslationUnitDecl(), 10495 AtLoc.isValid()? AtLoc : ImportLoc, 10496 Mod, IdentifierLocs); 10497 Context.getTranslationUnitDecl()->addDecl(Import); 10498 return Import; 10499 } 10500 10501 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 10502 IdentifierInfo* AliasName, 10503 SourceLocation PragmaLoc, 10504 SourceLocation NameLoc, 10505 SourceLocation AliasNameLoc) { 10506 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 10507 LookupOrdinaryName); 10508 AsmLabelAttr *Attr = 10509 ::new (Context) AsmLabelAttr(AliasNameLoc, Context, AliasName->getName()); 10510 10511 if (PrevDecl) 10512 PrevDecl->addAttr(Attr); 10513 else 10514 (void)ExtnameUndeclaredIdentifiers.insert( 10515 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 10516 } 10517 10518 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 10519 SourceLocation PragmaLoc, 10520 SourceLocation NameLoc) { 10521 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 10522 10523 if (PrevDecl) { 10524 PrevDecl->addAttr(::new (Context) WeakAttr(PragmaLoc, Context)); 10525 } else { 10526 (void)WeakUndeclaredIdentifiers.insert( 10527 std::pair<IdentifierInfo*,WeakInfo> 10528 (Name, WeakInfo((IdentifierInfo*)0, NameLoc))); 10529 } 10530 } 10531 10532 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 10533 IdentifierInfo* AliasName, 10534 SourceLocation PragmaLoc, 10535 SourceLocation NameLoc, 10536 SourceLocation AliasNameLoc) { 10537 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 10538 LookupOrdinaryName); 10539 WeakInfo W = WeakInfo(Name, NameLoc); 10540 10541 if (PrevDecl) { 10542 if (!PrevDecl->hasAttr<AliasAttr>()) 10543 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 10544 DeclApplyPragmaWeak(TUScope, ND, W); 10545 } else { 10546 (void)WeakUndeclaredIdentifiers.insert( 10547 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 10548 } 10549 } 10550 10551 Decl *Sema::getObjCDeclContext() const { 10552 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 10553 } 10554 10555 AvailabilityResult Sema::getCurContextAvailability() const { 10556 const Decl *D = cast<Decl>(getCurLexicalContext()); 10557 // A category implicitly has the availability of the interface. 10558 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D)) 10559 D = CatD->getClassInterface(); 10560 10561 return D->getAvailability(); 10562 }