Sema.cpp revision 4dfd02a17c6d604c72e6936527c5e1c56d3ecb7a
1//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the actions class which performs semantic analysis and 11// builds an AST out of a parse stream. 12// 13//===----------------------------------------------------------------------===// 14 15#include "clang/Sema/SemaInternal.h" 16#include "clang/Sema/DelayedDiagnostic.h" 17#include "TargetAttributesSema.h" 18#include "llvm/ADT/DenseMap.h" 19#include "llvm/ADT/SmallSet.h" 20#include "llvm/ADT/APFloat.h" 21#include "clang/Sema/CXXFieldCollector.h" 22#include "clang/Sema/TemplateDeduction.h" 23#include "clang/Sema/ExternalSemaSource.h" 24#include "clang/Sema/ObjCMethodList.h" 25#include "clang/Sema/PrettyDeclStackTrace.h" 26#include "clang/Sema/Scope.h" 27#include "clang/Sema/ScopeInfo.h" 28#include "clang/Sema/SemaConsumer.h" 29#include "clang/AST/ASTContext.h" 30#include "clang/AST/ASTDiagnostic.h" 31#include "clang/AST/DeclCXX.h" 32#include "clang/AST/DeclObjC.h" 33#include "clang/AST/Expr.h" 34#include "clang/AST/ExprCXX.h" 35#include "clang/AST/StmtCXX.h" 36#include "clang/Lex/Preprocessor.h" 37#include "clang/Basic/PartialDiagnostic.h" 38#include "clang/Basic/TargetInfo.h" 39using namespace clang; 40using namespace sema; 41 42FunctionScopeInfo::~FunctionScopeInfo() { } 43 44void FunctionScopeInfo::Clear() { 45 HasBranchProtectedScope = false; 46 HasBranchIntoScope = false; 47 HasIndirectGoto = false; 48 49 SwitchStack.clear(); 50 Returns.clear(); 51 ErrorTrap.reset(); 52 PossiblyUnreachableDiags.clear(); 53} 54 55BlockScopeInfo::~BlockScopeInfo() { } 56 57void Sema::ActOnTranslationUnitScope(Scope *S) { 58 TUScope = S; 59 PushDeclContext(S, Context.getTranslationUnitDecl()); 60 61 VAListTagName = PP.getIdentifierInfo("__va_list_tag"); 62 63 if (!Context.isInt128Installed() && // May be set by ASTReader. 64 PP.getTargetInfo().getPointerWidth(0) >= 64) { 65 TypeSourceInfo *TInfo; 66 67 // Install [u]int128_t for 64-bit targets. 68 TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty); 69 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 70 SourceLocation(), 71 SourceLocation(), 72 &Context.Idents.get("__int128_t"), 73 TInfo), TUScope); 74 75 TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty); 76 PushOnScopeChains(TypedefDecl::Create(Context, CurContext, 77 SourceLocation(), 78 SourceLocation(), 79 &Context.Idents.get("__uint128_t"), 80 TInfo), TUScope); 81 Context.setInt128Installed(); 82 } 83 84 85 if (!PP.getLangOptions().ObjC1) return; 86 87 // Built-in ObjC types may already be set by ASTReader (hence isNull checks). 88 if (Context.getObjCSelType().isNull()) { 89 // Create the built-in typedef for 'SEL'. 90 QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy); 91 TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT); 92 TypedefDecl *SelTypedef 93 = TypedefDecl::Create(Context, CurContext, 94 SourceLocation(), SourceLocation(), 95 &Context.Idents.get("SEL"), SelInfo); 96 PushOnScopeChains(SelTypedef, TUScope); 97 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef)); 98 } 99 100 // Synthesize "@class Protocol; 101 if (Context.getObjCProtoType().isNull()) { 102 ObjCInterfaceDecl *ProtocolDecl = 103 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(), 104 &Context.Idents.get("Protocol"), 105 SourceLocation(), true); 106 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl)); 107 PushOnScopeChains(ProtocolDecl, TUScope, false); 108 } 109 110 // Create the built-in typedef for 'Class'. 111 if (Context.getObjCClassType().isNull()) { 112 QualType T = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 0, 0); 113 T = Context.getObjCObjectPointerType(T); 114 TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(T); 115 TypedefDecl *ClassTypedef 116 = TypedefDecl::Create(Context, CurContext, 117 SourceLocation(), SourceLocation(), 118 &Context.Idents.get("Class"), ClassInfo); 119 PushOnScopeChains(ClassTypedef, TUScope); 120 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef)); 121 } 122} 123 124Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 125 bool CompleteTranslationUnit, 126 CodeCompleteConsumer *CodeCompleter) 127 : TheTargetAttributesSema(0), FPFeatures(pp.getLangOptions()), 128 LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer), 129 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()), 130 CollectStats(false), ExternalSource(0), CodeCompleter(CodeCompleter), 131 CurContext(0), PackContext(0), MSStructPragmaOn(false), VisContext(0), 132 ExprNeedsCleanups(0), LateTemplateParser(0), OpaqueParser(0), 133 IdResolver(pp.getLangOptions()), CXXTypeInfoDecl(0), MSVCGuidDecl(0), 134 GlobalNewDeleteDeclared(false), 135 CompleteTranslationUnit(CompleteTranslationUnit), 136 NumSFINAEErrors(0), SuppressAccessChecking(false), 137 AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false), 138 NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1), 139 CurrentInstantiationScope(0), TyposCorrected(0), 140 AnalysisWarnings(*this) 141{ 142 TUScope = 0; 143 LoadedExternalKnownNamespaces = false; 144 145 if (getLangOptions().CPlusPlus) 146 FieldCollector.reset(new CXXFieldCollector()); 147 148 // Tell diagnostics how to render things from the AST library. 149 PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument, 150 &Context); 151 152 ExprEvalContexts.push_back( 153 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0, false)); 154 155 FunctionScopes.push_back(new FunctionScopeInfo(Diags)); 156} 157 158void Sema::Initialize() { 159 // Tell the AST consumer about this Sema object. 160 Consumer.Initialize(Context); 161 162 // FIXME: Isn't this redundant with the initialization above? 163 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 164 SC->InitializeSema(*this); 165 166 // Tell the external Sema source about this Sema object. 167 if (ExternalSemaSource *ExternalSema 168 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 169 ExternalSema->InitializeSema(*this); 170 171 // Initialize predefined Objective-C types: 172 if (PP.getLangOptions().ObjC1) { 173 // If 'id' does not yet refer to any declarations, make it refer to the 174 // predefined 'id'. 175 DeclarationName Id = &Context.Idents.get("id"); 176 if (IdentifierResolver::begin(Id) == IdentifierResolver::end()) 177 PushOnScopeChains(Context.getObjCIdDecl(), TUScope); 178 } 179} 180 181Sema::~Sema() { 182 if (PackContext) FreePackedContext(); 183 if (VisContext) FreeVisContext(); 184 delete TheTargetAttributesSema; 185 MSStructPragmaOn = false; 186 // Kill all the active scopes. 187 for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I) 188 delete FunctionScopes[I]; 189 if (FunctionScopes.size() == 1) 190 delete FunctionScopes[0]; 191 192 // Tell the SemaConsumer to forget about us; we're going out of scope. 193 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 194 SC->ForgetSema(); 195 196 // Detach from the external Sema source. 197 if (ExternalSemaSource *ExternalSema 198 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 199 ExternalSema->ForgetSema(); 200} 201 202 203/// makeUnavailableInSystemHeader - There is an error in the current 204/// context. If we're still in a system header, and we can plausibly 205/// make the relevant declaration unavailable instead of erroring, do 206/// so and return true. 207bool Sema::makeUnavailableInSystemHeader(SourceLocation loc, 208 StringRef msg) { 209 // If we're not in a function, it's an error. 210 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext); 211 if (!fn) return false; 212 213 // If we're in template instantiation, it's an error. 214 if (!ActiveTemplateInstantiations.empty()) 215 return false; 216 217 // If that function's not in a system header, it's an error. 218 if (!Context.getSourceManager().isInSystemHeader(loc)) 219 return false; 220 221 // If the function is already unavailable, it's not an error. 222 if (fn->hasAttr<UnavailableAttr>()) return true; 223 224 fn->addAttr(new (Context) UnavailableAttr(loc, Context, msg)); 225 return true; 226} 227 228ASTMutationListener *Sema::getASTMutationListener() const { 229 return getASTConsumer().GetASTMutationListener(); 230} 231 232/// \brief Print out statistics about the semantic analysis. 233void Sema::PrintStats() const { 234 llvm::errs() << "\n*** Semantic Analysis Stats:\n"; 235 llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n"; 236 237 BumpAlloc.PrintStats(); 238 AnalysisWarnings.PrintStats(); 239} 240 241/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 242/// If there is already an implicit cast, merge into the existing one. 243/// The result is of the given category. 244ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty, 245 CastKind Kind, ExprValueKind VK, 246 const CXXCastPath *BasePath, 247 CheckedConversionKind CCK) { 248 QualType ExprTy = Context.getCanonicalType(E->getType()); 249 QualType TypeTy = Context.getCanonicalType(Ty); 250 251 if (ExprTy == TypeTy) 252 return Owned(E); 253 254 if (getLangOptions().ObjCAutoRefCount) 255 CheckObjCARCConversion(SourceRange(), Ty, E, CCK); 256 257 // If this is a derived-to-base cast to a through a virtual base, we 258 // need a vtable. 259 if (Kind == CK_DerivedToBase && 260 BasePathInvolvesVirtualBase(*BasePath)) { 261 QualType T = E->getType(); 262 if (const PointerType *Pointer = T->getAs<PointerType>()) 263 T = Pointer->getPointeeType(); 264 if (const RecordType *RecordTy = T->getAs<RecordType>()) 265 MarkVTableUsed(E->getLocStart(), 266 cast<CXXRecordDecl>(RecordTy->getDecl())); 267 } 268 269 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) { 270 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) { 271 ImpCast->setType(Ty); 272 ImpCast->setValueKind(VK); 273 return Owned(E); 274 } 275 } 276 277 return Owned(ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK)); 278} 279 280/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 281/// to the conversion from scalar type ScalarTy to the Boolean type. 282CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) { 283 switch (ScalarTy->getScalarTypeKind()) { 284 case Type::STK_Bool: return CK_NoOp; 285 case Type::STK_Pointer: return CK_PointerToBoolean; 286 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean; 287 case Type::STK_Integral: return CK_IntegralToBoolean; 288 case Type::STK_Floating: return CK_FloatingToBoolean; 289 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean; 290 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean; 291 } 292 return CK_Invalid; 293} 294 295ExprValueKind Sema::CastCategory(Expr *E) { 296 Expr::Classification Classification = E->Classify(Context); 297 return Classification.isRValue() ? VK_RValue : 298 (Classification.isLValue() ? VK_LValue : VK_XValue); 299} 300 301/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector. 302static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) { 303 if (D->isUsed()) 304 return true; 305 306 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 307 // UnusedFileScopedDecls stores the first declaration. 308 // The declaration may have become definition so check again. 309 const FunctionDecl *DeclToCheck; 310 if (FD->hasBody(DeclToCheck)) 311 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 312 313 // Later redecls may add new information resulting in not having to warn, 314 // so check again. 315 DeclToCheck = FD->getMostRecentDeclaration(); 316 if (DeclToCheck != FD) 317 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 318 } 319 320 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 321 // UnusedFileScopedDecls stores the first declaration. 322 // The declaration may have become definition so check again. 323 const VarDecl *DeclToCheck = VD->getDefinition(); 324 if (DeclToCheck) 325 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 326 327 // Later redecls may add new information resulting in not having to warn, 328 // so check again. 329 DeclToCheck = VD->getMostRecentDeclaration(); 330 if (DeclToCheck != VD) 331 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 332 } 333 334 return false; 335} 336 337namespace { 338 struct UndefinedInternal { 339 NamedDecl *decl; 340 FullSourceLoc useLoc; 341 342 UndefinedInternal(NamedDecl *decl, FullSourceLoc useLoc) 343 : decl(decl), useLoc(useLoc) {} 344 }; 345 346 bool operator<(const UndefinedInternal &l, const UndefinedInternal &r) { 347 return l.useLoc.isBeforeInTranslationUnitThan(r.useLoc); 348 } 349} 350 351/// checkUndefinedInternals - Check for undefined objects with internal linkage. 352static void checkUndefinedInternals(Sema &S) { 353 if (S.UndefinedInternals.empty()) return; 354 355 // Collect all the still-undefined entities with internal linkage. 356 SmallVector<UndefinedInternal, 16> undefined; 357 for (llvm::DenseMap<NamedDecl*,SourceLocation>::iterator 358 i = S.UndefinedInternals.begin(), e = S.UndefinedInternals.end(); 359 i != e; ++i) { 360 NamedDecl *decl = i->first; 361 362 // Ignore attributes that have become invalid. 363 if (decl->isInvalidDecl()) continue; 364 365 // __attribute__((weakref)) is basically a definition. 366 if (decl->hasAttr<WeakRefAttr>()) continue; 367 368 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) { 369 if (fn->isPure() || fn->hasBody()) 370 continue; 371 } else { 372 if (cast<VarDecl>(decl)->hasDefinition() != VarDecl::DeclarationOnly) 373 continue; 374 } 375 376 // We build a FullSourceLoc so that we can sort with array_pod_sort. 377 FullSourceLoc loc(i->second, S.Context.getSourceManager()); 378 undefined.push_back(UndefinedInternal(decl, loc)); 379 } 380 381 if (undefined.empty()) return; 382 383 // Sort (in order of use site) so that we're not (as) dependent on 384 // the iteration order through an llvm::DenseMap. 385 llvm::array_pod_sort(undefined.begin(), undefined.end()); 386 387 for (SmallVectorImpl<UndefinedInternal>::iterator 388 i = undefined.begin(), e = undefined.end(); i != e; ++i) { 389 NamedDecl *decl = i->decl; 390 S.Diag(decl->getLocation(), diag::warn_undefined_internal) 391 << isa<VarDecl>(decl) << decl; 392 S.Diag(i->useLoc, diag::note_used_here); 393 } 394} 395 396void Sema::LoadExternalWeakUndeclaredIdentifiers() { 397 if (!ExternalSource) 398 return; 399 400 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs; 401 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs); 402 for (unsigned I = 0, N = WeakIDs.size(); I != N; ++I) { 403 llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator Pos 404 = WeakUndeclaredIdentifiers.find(WeakIDs[I].first); 405 if (Pos != WeakUndeclaredIdentifiers.end()) 406 continue; 407 408 WeakUndeclaredIdentifiers.insert(WeakIDs[I]); 409 } 410} 411 412/// ActOnEndOfTranslationUnit - This is called at the very end of the 413/// translation unit when EOF is reached and all but the top-level scope is 414/// popped. 415void Sema::ActOnEndOfTranslationUnit() { 416 // At PCH writing, implicit instantiations and VTable handling info are 417 // stored and performed when the PCH is included. 418 if (CompleteTranslationUnit) { 419 // If any dynamic classes have their key function defined within 420 // this translation unit, then those vtables are considered "used" and must 421 // be emitted. 422 for (DynamicClassesType::iterator I = DynamicClasses.begin(ExternalSource), 423 E = DynamicClasses.end(); 424 I != E; ++I) { 425 assert(!(*I)->isDependentType() && 426 "Should not see dependent types here!"); 427 if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(*I)) { 428 const FunctionDecl *Definition = 0; 429 if (KeyFunction->hasBody(Definition)) 430 MarkVTableUsed(Definition->getLocation(), *I, true); 431 } 432 } 433 434 // If DefinedUsedVTables ends up marking any virtual member functions it 435 // might lead to more pending template instantiations, which we then need 436 // to instantiate. 437 DefineUsedVTables(); 438 439 // C++: Perform implicit template instantiations. 440 // 441 // FIXME: When we perform these implicit instantiations, we do not 442 // carefully keep track of the point of instantiation (C++ [temp.point]). 443 // This means that name lookup that occurs within the template 444 // instantiation will always happen at the end of the translation unit, 445 // so it will find some names that should not be found. Although this is 446 // common behavior for C++ compilers, it is technically wrong. In the 447 // future, we either need to be able to filter the results of name lookup 448 // or we need to perform template instantiations earlier. 449 PerformPendingInstantiations(); 450 } 451 452 // Remove file scoped decls that turned out to be used. 453 UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(0, 454 true), 455 UnusedFileScopedDecls.end(), 456 std::bind1st(std::ptr_fun(ShouldRemoveFromUnused), 457 this)), 458 UnusedFileScopedDecls.end()); 459 460 if (!CompleteTranslationUnit) { 461 TUScope = 0; 462 return; 463 } 464 465 // Check for #pragma weak identifiers that were never declared 466 // FIXME: This will cause diagnostics to be emitted in a non-determinstic 467 // order! Iterating over a densemap like this is bad. 468 LoadExternalWeakUndeclaredIdentifiers(); 469 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 470 I = WeakUndeclaredIdentifiers.begin(), 471 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) { 472 if (I->second.getUsed()) continue; 473 474 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared) 475 << I->first; 476 } 477 478 // C99 6.9.2p2: 479 // A declaration of an identifier for an object that has file 480 // scope without an initializer, and without a storage-class 481 // specifier or with the storage-class specifier static, 482 // constitutes a tentative definition. If a translation unit 483 // contains one or more tentative definitions for an identifier, 484 // and the translation unit contains no external definition for 485 // that identifier, then the behavior is exactly as if the 486 // translation unit contains a file scope declaration of that 487 // identifier, with the composite type as of the end of the 488 // translation unit, with an initializer equal to 0. 489 llvm::SmallSet<VarDecl *, 32> Seen; 490 for (TentativeDefinitionsType::iterator 491 T = TentativeDefinitions.begin(ExternalSource), 492 TEnd = TentativeDefinitions.end(); 493 T != TEnd; ++T) 494 { 495 VarDecl *VD = (*T)->getActingDefinition(); 496 497 // If the tentative definition was completed, getActingDefinition() returns 498 // null. If we've already seen this variable before, insert()'s second 499 // return value is false. 500 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD)) 501 continue; 502 503 if (const IncompleteArrayType *ArrayT 504 = Context.getAsIncompleteArrayType(VD->getType())) { 505 if (RequireCompleteType(VD->getLocation(), 506 ArrayT->getElementType(), 507 diag::err_tentative_def_incomplete_type_arr)) { 508 VD->setInvalidDecl(); 509 continue; 510 } 511 512 // Set the length of the array to 1 (C99 6.9.2p5). 513 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 514 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 515 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), 516 One, ArrayType::Normal, 0); 517 VD->setType(T); 518 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 519 diag::err_tentative_def_incomplete_type)) 520 VD->setInvalidDecl(); 521 522 // Notify the consumer that we've completed a tentative definition. 523 if (!VD->isInvalidDecl()) 524 Consumer.CompleteTentativeDefinition(VD); 525 526 } 527 528 if (LangOpts.CPlusPlus0x && 529 Diags.getDiagnosticLevel(diag::warn_delegating_ctor_cycle, 530 SourceLocation()) 531 != Diagnostic::Ignored) 532 CheckDelegatingCtorCycles(); 533 534 // If there were errors, disable 'unused' warnings since they will mostly be 535 // noise. 536 if (!Diags.hasErrorOccurred()) { 537 // Output warning for unused file scoped decls. 538 for (UnusedFileScopedDeclsType::iterator 539 I = UnusedFileScopedDecls.begin(ExternalSource), 540 E = UnusedFileScopedDecls.end(); I != E; ++I) { 541 if (ShouldRemoveFromUnused(this, *I)) 542 continue; 543 544 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 545 const FunctionDecl *DiagD; 546 if (!FD->hasBody(DiagD)) 547 DiagD = FD; 548 if (DiagD->isDeleted()) 549 continue; // Deleted functions are supposed to be unused. 550 if (DiagD->isReferenced()) { 551 if (isa<CXXMethodDecl>(DiagD)) 552 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function) 553 << DiagD->getDeclName(); 554 else 555 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 556 << /*function*/0 << DiagD->getDeclName(); 557 } else { 558 Diag(DiagD->getLocation(), 559 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function 560 : diag::warn_unused_function) 561 << DiagD->getDeclName(); 562 } 563 } else { 564 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition(); 565 if (!DiagD) 566 DiagD = cast<VarDecl>(*I); 567 if (DiagD->isReferenced()) { 568 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 569 << /*variable*/1 << DiagD->getDeclName(); 570 } else { 571 Diag(DiagD->getLocation(), diag::warn_unused_variable) 572 << DiagD->getDeclName(); 573 } 574 } 575 } 576 577 checkUndefinedInternals(*this); 578 } 579 580 // Check we've noticed that we're no longer parsing the initializer for every 581 // variable. If we miss cases, then at best we have a performance issue and 582 // at worst a rejects-valid bug. 583 assert(ParsingInitForAutoVars.empty() && 584 "Didn't unmark var as having its initializer parsed"); 585 586 TUScope = 0; 587} 588 589 590//===----------------------------------------------------------------------===// 591// Helper functions. 592//===----------------------------------------------------------------------===// 593 594DeclContext *Sema::getFunctionLevelDeclContext() { 595 DeclContext *DC = CurContext; 596 597 while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC)) 598 DC = DC->getParent(); 599 600 return DC; 601} 602 603/// getCurFunctionDecl - If inside of a function body, this returns a pointer 604/// to the function decl for the function being parsed. If we're currently 605/// in a 'block', this returns the containing context. 606FunctionDecl *Sema::getCurFunctionDecl() { 607 DeclContext *DC = getFunctionLevelDeclContext(); 608 return dyn_cast<FunctionDecl>(DC); 609} 610 611ObjCMethodDecl *Sema::getCurMethodDecl() { 612 DeclContext *DC = getFunctionLevelDeclContext(); 613 return dyn_cast<ObjCMethodDecl>(DC); 614} 615 616NamedDecl *Sema::getCurFunctionOrMethodDecl() { 617 DeclContext *DC = getFunctionLevelDeclContext(); 618 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 619 return cast<NamedDecl>(DC); 620 return 0; 621} 622 623Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() { 624 if (!isActive()) 625 return; 626 627 if (llvm::Optional<TemplateDeductionInfo*> Info = SemaRef.isSFINAEContext()) { 628 switch (DiagnosticIDs::getDiagnosticSFINAEResponse(getDiagID())) { 629 case DiagnosticIDs::SFINAE_Report: 630 // Fall through; we'll report the diagnostic below. 631 break; 632 633 case DiagnosticIDs::SFINAE_AccessControl: 634 // Per C++ Core Issue 1170, access control is part of SFINAE. 635 // Additionally, the AccessCheckingSFINAE flag can be used to temporary 636 // make access control a part of SFINAE for the purposes of checking 637 // type traits. 638 if (!SemaRef.AccessCheckingSFINAE && 639 !SemaRef.getLangOptions().CPlusPlus0x) 640 break; 641 642 case DiagnosticIDs::SFINAE_SubstitutionFailure: 643 // Count this failure so that we know that template argument deduction 644 // has failed. 645 ++SemaRef.NumSFINAEErrors; 646 SemaRef.Diags.setLastDiagnosticIgnored(); 647 SemaRef.Diags.Clear(); 648 Clear(); 649 return; 650 651 case DiagnosticIDs::SFINAE_Suppress: 652 // Make a copy of this suppressed diagnostic and store it with the 653 // template-deduction information; 654 FlushCounts(); 655 DiagnosticInfo DiagInfo(&SemaRef.Diags); 656 657 if (*Info) 658 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(), 659 PartialDiagnostic(DiagInfo, 660 SemaRef.Context.getDiagAllocator())); 661 662 // Suppress this diagnostic. 663 SemaRef.Diags.setLastDiagnosticIgnored(); 664 SemaRef.Diags.Clear(); 665 Clear(); 666 return; 667 } 668 } 669 670 // Emit the diagnostic. 671 if (!this->Emit()) 672 return; 673 674 // If this is not a note, and we're in a template instantiation 675 // that is different from the last template instantiation where 676 // we emitted an error, print a template instantiation 677 // backtrace. 678 if (!DiagnosticIDs::isBuiltinNote(DiagID) && 679 !SemaRef.ActiveTemplateInstantiations.empty() && 680 SemaRef.ActiveTemplateInstantiations.back() 681 != SemaRef.LastTemplateInstantiationErrorContext) { 682 SemaRef.PrintInstantiationStack(); 683 SemaRef.LastTemplateInstantiationErrorContext 684 = SemaRef.ActiveTemplateInstantiations.back(); 685 } 686} 687 688Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) { 689 DiagnosticBuilder DB = Diags.Report(Loc, DiagID); 690 return SemaDiagnosticBuilder(DB, *this, DiagID); 691} 692 693Sema::SemaDiagnosticBuilder 694Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 695 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 696 PD.Emit(Builder); 697 698 return Builder; 699} 700 701/// \brief Looks through the macro-expansion chain for the given 702/// location, looking for a macro expansion with the given name. 703/// If one is found, returns true and sets the location to that 704/// expansion loc. 705bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) { 706 SourceLocation loc = locref; 707 if (!loc.isMacroID()) return false; 708 709 // There's no good way right now to look at the intermediate 710 // expansions, so just jump to the expansion location. 711 loc = getSourceManager().getExpansionLoc(loc); 712 713 // If that's written with the name, stop here. 714 SmallVector<char, 16> buffer; 715 if (getPreprocessor().getSpelling(loc, buffer) == name) { 716 locref = loc; 717 return true; 718 } 719 return false; 720} 721 722/// \brief Determines the active Scope associated with the given declaration 723/// context. 724/// 725/// This routine maps a declaration context to the active Scope object that 726/// represents that declaration context in the parser. It is typically used 727/// from "scope-less" code (e.g., template instantiation, lazy creation of 728/// declarations) that injects a name for name-lookup purposes and, therefore, 729/// must update the Scope. 730/// 731/// \returns The scope corresponding to the given declaraion context, or NULL 732/// if no such scope is open. 733Scope *Sema::getScopeForContext(DeclContext *Ctx) { 734 735 if (!Ctx) 736 return 0; 737 738 Ctx = Ctx->getPrimaryContext(); 739 for (Scope *S = getCurScope(); S; S = S->getParent()) { 740 // Ignore scopes that cannot have declarations. This is important for 741 // out-of-line definitions of static class members. 742 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) 743 if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity())) 744 if (Ctx == Entity->getPrimaryContext()) 745 return S; 746 } 747 748 return 0; 749} 750 751/// \brief Enter a new function scope 752void Sema::PushFunctionScope() { 753 if (FunctionScopes.size() == 1) { 754 // Use the "top" function scope rather than having to allocate 755 // memory for a new scope. 756 FunctionScopes.back()->Clear(); 757 FunctionScopes.push_back(FunctionScopes.back()); 758 return; 759 } 760 761 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics())); 762} 763 764void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) { 765 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(), 766 BlockScope, Block)); 767} 768 769void Sema::PopFunctionOrBlockScope(const AnalysisBasedWarnings::Policy *WP, 770 const Decl *D, const BlockExpr *blkExpr) { 771 FunctionScopeInfo *Scope = FunctionScopes.pop_back_val(); 772 assert(!FunctionScopes.empty() && "mismatched push/pop!"); 773 774 // Issue any analysis-based warnings. 775 if (WP && D) 776 AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr); 777 else { 778 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator 779 i = Scope->PossiblyUnreachableDiags.begin(), 780 e = Scope->PossiblyUnreachableDiags.end(); 781 i != e; ++i) { 782 const sema::PossiblyUnreachableDiag &D = *i; 783 Diag(D.Loc, D.PD); 784 } 785 } 786 787 if (FunctionScopes.back() != Scope) { 788 delete Scope; 789 } 790} 791 792/// \brief Determine whether any errors occurred within this function/method/ 793/// block. 794bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const { 795 return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred(); 796} 797 798BlockScopeInfo *Sema::getCurBlock() { 799 if (FunctionScopes.empty()) 800 return 0; 801 802 return dyn_cast<BlockScopeInfo>(FunctionScopes.back()); 803} 804 805// Pin this vtable to this file. 806ExternalSemaSource::~ExternalSemaSource() {} 807 808std::pair<ObjCMethodList, ObjCMethodList> 809ExternalSemaSource::ReadMethodPool(Selector Sel) { 810 return std::pair<ObjCMethodList, ObjCMethodList>(); 811} 812 813void ExternalSemaSource::ReadKnownNamespaces( 814 SmallVectorImpl<NamespaceDecl *> &Namespaces) { 815} 816 817void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const { 818 SourceLocation Loc = this->Loc; 819 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation(); 820 if (Loc.isValid()) { 821 Loc.print(OS, S.getSourceManager()); 822 OS << ": "; 823 } 824 OS << Message; 825 826 if (TheDecl && isa<NamedDecl>(TheDecl)) { 827 std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString(); 828 if (!Name.empty()) 829 OS << " '" << Name << '\''; 830 } 831 832 OS << '\n'; 833} 834 835/// \brief Figure out if an expression could be turned into a call. 836/// 837/// Use this when trying to recover from an error where the programmer may have 838/// written just the name of a function instead of actually calling it. 839/// 840/// \param E - The expression to examine. 841/// \param ZeroArgCallReturnTy - If the expression can be turned into a call 842/// with no arguments, this parameter is set to the type returned by such a 843/// call; otherwise, it is set to an empty QualType. 844/// \param NonTemplateOverloads - If the expression is an overloaded function 845/// name, this parameter is populated with the decls of the various overloads. 846bool Sema::isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy, 847 UnresolvedSetImpl &NonTemplateOverloads) { 848 ZeroArgCallReturnTy = QualType(); 849 NonTemplateOverloads.clear(); 850 if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(&E)) { 851 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(), 852 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) { 853 // Our overload set may include TemplateDecls, which we'll ignore for our 854 // present purpose. 855 if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) { 856 NonTemplateOverloads.addDecl(*it); 857 if (OverloadDecl->getMinRequiredArguments() == 0) 858 ZeroArgCallReturnTy = OverloadDecl->getResultType(); 859 } 860 } 861 return true; 862 } 863 864 if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(&E)) { 865 if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) { 866 if (Fun->getMinRequiredArguments() == 0) 867 ZeroArgCallReturnTy = Fun->getResultType(); 868 return true; 869 } 870 } 871 872 // We don't have an expression that's convenient to get a FunctionDecl from, 873 // but we can at least check if the type is "function of 0 arguments". 874 QualType ExprTy = E.getType(); 875 const FunctionType *FunTy = NULL; 876 QualType PointeeTy = ExprTy->getPointeeType(); 877 if (!PointeeTy.isNull()) 878 FunTy = PointeeTy->getAs<FunctionType>(); 879 if (!FunTy) 880 FunTy = ExprTy->getAs<FunctionType>(); 881 if (!FunTy && ExprTy == Context.BoundMemberTy) { 882 // Look for the bound-member type. If it's still overloaded, give up, 883 // although we probably should have fallen into the OverloadExpr case above 884 // if we actually have an overloaded bound member. 885 QualType BoundMemberTy = Expr::findBoundMemberType(&E); 886 if (!BoundMemberTy.isNull()) 887 FunTy = BoundMemberTy->castAs<FunctionType>(); 888 } 889 890 if (const FunctionProtoType *FPT = 891 dyn_cast_or_null<FunctionProtoType>(FunTy)) { 892 if (FPT->getNumArgs() == 0) 893 ZeroArgCallReturnTy = FunTy->getResultType(); 894 return true; 895 } 896 return false; 897} 898 899/// \brief Give notes for a set of overloads. 900/// 901/// A companion to isExprCallable. In cases when the name that the programmer 902/// wrote was an overloaded function, we may be able to make some guesses about 903/// plausible overloads based on their return types; such guesses can be handed 904/// off to this method to be emitted as notes. 905/// 906/// \param Overloads - The overloads to note. 907/// \param FinalNoteLoc - If we've suppressed printing some overloads due to 908/// -fshow-overloads=best, this is the location to attach to the note about too 909/// many candidates. Typically this will be the location of the original 910/// ill-formed expression. 911void Sema::NoteOverloads(const UnresolvedSetImpl &Overloads, 912 const SourceLocation FinalNoteLoc) { 913 int ShownOverloads = 0; 914 int SuppressedOverloads = 0; 915 for (UnresolvedSetImpl::iterator It = Overloads.begin(), 916 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 917 // FIXME: Magic number for max shown overloads stolen from 918 // OverloadCandidateSet::NoteCandidates. 919 if (ShownOverloads >= 4 && 920 Diags.getShowOverloads() == Diagnostic::Ovl_Best) { 921 ++SuppressedOverloads; 922 continue; 923 } 924 Diag(cast<FunctionDecl>(*It)->getSourceRange().getBegin(), 925 diag::note_member_ref_possible_intended_overload); 926 ++ShownOverloads; 927 } 928 if (SuppressedOverloads) 929 Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates) 930 << SuppressedOverloads; 931} 932