Sema.cpp revision 12d2cc71bfeb1e7be9ce00fc52feab50941cac24
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 "llvm/Support/CrashRecoveryContext.h" 22#include "clang/Sema/CXXFieldCollector.h" 23#include "clang/Sema/TemplateDeduction.h" 24#include "clang/Sema/ExternalSemaSource.h" 25#include "clang/Sema/ObjCMethodList.h" 26#include "clang/Sema/PrettyDeclStackTrace.h" 27#include "clang/Sema/Scope.h" 28#include "clang/Sema/ScopeInfo.h" 29#include "clang/Sema/SemaConsumer.h" 30#include "clang/AST/ASTContext.h" 31#include "clang/AST/ASTDiagnostic.h" 32#include "clang/AST/DeclCXX.h" 33#include "clang/AST/DeclFriend.h" 34#include "clang/AST/DeclObjC.h" 35#include "clang/AST/Expr.h" 36#include "clang/AST/ExprCXX.h" 37#include "clang/AST/StmtCXX.h" 38#include "clang/Lex/HeaderSearch.h" 39#include "clang/Lex/Preprocessor.h" 40#include "clang/Basic/FileManager.h" 41#include "clang/Basic/PartialDiagnostic.h" 42#include "clang/Basic/TargetInfo.h" 43using namespace clang; 44using namespace sema; 45 46FunctionScopeInfo::~FunctionScopeInfo() { } 47 48void FunctionScopeInfo::Clear() { 49 HasBranchProtectedScope = false; 50 HasBranchIntoScope = false; 51 HasIndirectGoto = false; 52 53 SwitchStack.clear(); 54 Returns.clear(); 55 ErrorTrap.reset(); 56 PossiblyUnreachableDiags.clear(); 57} 58 59BlockScopeInfo::~BlockScopeInfo() { } 60LambdaScopeInfo::~LambdaScopeInfo() { } 61 62PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context, 63 const Preprocessor &PP) { 64 PrintingPolicy Policy = Context.getPrintingPolicy(); 65 Policy.Bool = Context.getLangOpts().Bool; 66 if (!Policy.Bool) { 67 if (MacroInfo *BoolMacro = PP.getMacroInfo(&Context.Idents.get("bool"))) { 68 Policy.Bool = BoolMacro->isObjectLike() && 69 BoolMacro->getNumTokens() == 1 && 70 BoolMacro->getReplacementToken(0).is(tok::kw__Bool); 71 } 72 } 73 74 return Policy; 75} 76 77void Sema::ActOnTranslationUnitScope(Scope *S) { 78 TUScope = S; 79 PushDeclContext(S, Context.getTranslationUnitDecl()); 80 81 VAListTagName = PP.getIdentifierInfo("__va_list_tag"); 82} 83 84Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 85 TranslationUnitKind TUKind, 86 CodeCompleteConsumer *CodeCompleter) 87 : TheTargetAttributesSema(0), FPFeatures(pp.getLangOpts()), 88 LangOpts(pp.getLangOpts()), PP(pp), Context(ctxt), Consumer(consumer), 89 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()), 90 CollectStats(false), ExternalSource(0), CodeCompleter(CodeCompleter), 91 CurContext(0), OriginalLexicalContext(0), 92 PackContext(0), MSStructPragmaOn(false), VisContext(0), 93 ExprNeedsCleanups(false), LateTemplateParser(0), OpaqueParser(0), 94 IdResolver(pp), StdInitializerList(0), CXXTypeInfoDecl(0), MSVCGuidDecl(0), 95 NSNumberDecl(0), 96 NSStringDecl(0), StringWithUTF8StringMethod(0), 97 NSArrayDecl(0), ArrayWithObjectsMethod(0), 98 NSDictionaryDecl(0), DictionaryWithObjectsMethod(0), 99 GlobalNewDeleteDeclared(false), 100 ObjCShouldCallSuperDealloc(false), 101 ObjCShouldCallSuperFinalize(false), 102 TUKind(TUKind), 103 NumSFINAEErrors(0), InFunctionDeclarator(0), 104 AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false), 105 NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1), 106 CurrentInstantiationScope(0), TyposCorrected(0), 107 AnalysisWarnings(*this) 108{ 109 TUScope = 0; 110 111 LoadedExternalKnownNamespaces = false; 112 for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I) 113 NSNumberLiteralMethods[I] = 0; 114 115 if (getLangOpts().ObjC1) 116 NSAPIObj.reset(new NSAPI(Context)); 117 118 if (getLangOpts().CPlusPlus) 119 FieldCollector.reset(new CXXFieldCollector()); 120 121 // Tell diagnostics how to render things from the AST library. 122 PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument, 123 &Context); 124 125 ExprEvalContexts.push_back( 126 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0, 127 false, 0, false)); 128 129 FunctionScopes.push_back(new FunctionScopeInfo(Diags)); 130} 131 132void Sema::Initialize() { 133 // Tell the AST consumer about this Sema object. 134 Consumer.Initialize(Context); 135 136 // FIXME: Isn't this redundant with the initialization above? 137 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 138 SC->InitializeSema(*this); 139 140 // Tell the external Sema source about this Sema object. 141 if (ExternalSemaSource *ExternalSema 142 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 143 ExternalSema->InitializeSema(*this); 144 145 // Initialize predefined 128-bit integer types, if needed. 146 if (PP.getTargetInfo().getPointerWidth(0) >= 64) { 147 // If either of the 128-bit integer types are unavailable to name lookup, 148 // define them now. 149 DeclarationName Int128 = &Context.Idents.get("__int128_t"); 150 if (IdResolver.begin(Int128) == IdResolver.end()) 151 PushOnScopeChains(Context.getInt128Decl(), TUScope); 152 153 DeclarationName UInt128 = &Context.Idents.get("__uint128_t"); 154 if (IdResolver.begin(UInt128) == IdResolver.end()) 155 PushOnScopeChains(Context.getUInt128Decl(), TUScope); 156 } 157 158 159 // Initialize predefined Objective-C types: 160 if (PP.getLangOpts().ObjC1) { 161 // If 'SEL' does not yet refer to any declarations, make it refer to the 162 // predefined 'SEL'. 163 DeclarationName SEL = &Context.Idents.get("SEL"); 164 if (IdResolver.begin(SEL) == IdResolver.end()) 165 PushOnScopeChains(Context.getObjCSelDecl(), TUScope); 166 167 // If 'id' does not yet refer to any declarations, make it refer to the 168 // predefined 'id'. 169 DeclarationName Id = &Context.Idents.get("id"); 170 if (IdResolver.begin(Id) == IdResolver.end()) 171 PushOnScopeChains(Context.getObjCIdDecl(), TUScope); 172 173 // Create the built-in typedef for 'Class'. 174 DeclarationName Class = &Context.Idents.get("Class"); 175 if (IdResolver.begin(Class) == IdResolver.end()) 176 PushOnScopeChains(Context.getObjCClassDecl(), TUScope); 177 178 // Create the built-in forward declaratino for 'Protocol'. 179 DeclarationName Protocol = &Context.Idents.get("Protocol"); 180 if (IdResolver.begin(Protocol) == IdResolver.end()) 181 PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope); 182 } 183 184 DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list"); 185 if (IdResolver.begin(BuiltinVaList) == IdResolver.end()) 186 PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope); 187} 188 189Sema::~Sema() { 190 if (PackContext) FreePackedContext(); 191 if (VisContext) FreeVisContext(); 192 delete TheTargetAttributesSema; 193 MSStructPragmaOn = false; 194 // Kill all the active scopes. 195 for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I) 196 delete FunctionScopes[I]; 197 if (FunctionScopes.size() == 1) 198 delete FunctionScopes[0]; 199 200 // Tell the SemaConsumer to forget about us; we're going out of scope. 201 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 202 SC->ForgetSema(); 203 204 // Detach from the external Sema source. 205 if (ExternalSemaSource *ExternalSema 206 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 207 ExternalSema->ForgetSema(); 208} 209 210/// makeUnavailableInSystemHeader - There is an error in the current 211/// context. If we're still in a system header, and we can plausibly 212/// make the relevant declaration unavailable instead of erroring, do 213/// so and return true. 214bool Sema::makeUnavailableInSystemHeader(SourceLocation loc, 215 StringRef msg) { 216 // If we're not in a function, it's an error. 217 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext); 218 if (!fn) return false; 219 220 // If we're in template instantiation, it's an error. 221 if (!ActiveTemplateInstantiations.empty()) 222 return false; 223 224 // If that function's not in a system header, it's an error. 225 if (!Context.getSourceManager().isInSystemHeader(loc)) 226 return false; 227 228 // If the function is already unavailable, it's not an error. 229 if (fn->hasAttr<UnavailableAttr>()) return true; 230 231 fn->addAttr(new (Context) UnavailableAttr(loc, Context, msg)); 232 return true; 233} 234 235ASTMutationListener *Sema::getASTMutationListener() const { 236 return getASTConsumer().GetASTMutationListener(); 237} 238 239/// \brief Print out statistics about the semantic analysis. 240void Sema::PrintStats() const { 241 llvm::errs() << "\n*** Semantic Analysis Stats:\n"; 242 llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n"; 243 244 BumpAlloc.PrintStats(); 245 AnalysisWarnings.PrintStats(); 246} 247 248/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 249/// If there is already an implicit cast, merge into the existing one. 250/// The result is of the given category. 251ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty, 252 CastKind Kind, ExprValueKind VK, 253 const CXXCastPath *BasePath, 254 CheckedConversionKind CCK) { 255#ifndef NDEBUG 256 if (VK == VK_RValue && !E->isRValue()) { 257 switch (Kind) { 258 default: 259 assert(0 && "can't implicitly cast lvalue to rvalue with this cast kind"); 260 case CK_LValueToRValue: 261 case CK_ArrayToPointerDecay: 262 case CK_FunctionToPointerDecay: 263 case CK_ToVoid: 264 break; 265 } 266 } 267 assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue"); 268#endif 269 270 QualType ExprTy = Context.getCanonicalType(E->getType()); 271 QualType TypeTy = Context.getCanonicalType(Ty); 272 273 if (ExprTy == TypeTy) 274 return Owned(E); 275 276 if (getLangOpts().ObjCAutoRefCount) 277 CheckObjCARCConversion(SourceRange(), Ty, E, CCK); 278 279 // If this is a derived-to-base cast to a through a virtual base, we 280 // need a vtable. 281 if (Kind == CK_DerivedToBase && 282 BasePathInvolvesVirtualBase(*BasePath)) { 283 QualType T = E->getType(); 284 if (const PointerType *Pointer = T->getAs<PointerType>()) 285 T = Pointer->getPointeeType(); 286 if (const RecordType *RecordTy = T->getAs<RecordType>()) 287 MarkVTableUsed(E->getLocStart(), 288 cast<CXXRecordDecl>(RecordTy->getDecl())); 289 } 290 291 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) { 292 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) { 293 ImpCast->setType(Ty); 294 ImpCast->setValueKind(VK); 295 return Owned(E); 296 } 297 } 298 299 return Owned(ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK)); 300} 301 302/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 303/// to the conversion from scalar type ScalarTy to the Boolean type. 304CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) { 305 switch (ScalarTy->getScalarTypeKind()) { 306 case Type::STK_Bool: return CK_NoOp; 307 case Type::STK_CPointer: return CK_PointerToBoolean; 308 case Type::STK_BlockPointer: return CK_PointerToBoolean; 309 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean; 310 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean; 311 case Type::STK_Integral: return CK_IntegralToBoolean; 312 case Type::STK_Floating: return CK_FloatingToBoolean; 313 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean; 314 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean; 315 } 316 return CK_Invalid; 317} 318 319/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector. 320static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) { 321 if (D->isUsed()) 322 return true; 323 324 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 325 // UnusedFileScopedDecls stores the first declaration. 326 // The declaration may have become definition so check again. 327 const FunctionDecl *DeclToCheck; 328 if (FD->hasBody(DeclToCheck)) 329 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 330 331 // Later redecls may add new information resulting in not having to warn, 332 // so check again. 333 DeclToCheck = FD->getMostRecentDecl(); 334 if (DeclToCheck != FD) 335 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 336 } 337 338 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 339 // UnusedFileScopedDecls stores the first declaration. 340 // The declaration may have become definition so check again. 341 const VarDecl *DeclToCheck = VD->getDefinition(); 342 if (DeclToCheck) 343 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 344 345 // Later redecls may add new information resulting in not having to warn, 346 // so check again. 347 DeclToCheck = VD->getMostRecentDecl(); 348 if (DeclToCheck != VD) 349 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 350 } 351 352 return false; 353} 354 355namespace { 356 struct UndefinedInternal { 357 NamedDecl *decl; 358 FullSourceLoc useLoc; 359 360 UndefinedInternal(NamedDecl *decl, FullSourceLoc useLoc) 361 : decl(decl), useLoc(useLoc) {} 362 }; 363 364 bool operator<(const UndefinedInternal &l, const UndefinedInternal &r) { 365 return l.useLoc.isBeforeInTranslationUnitThan(r.useLoc); 366 } 367} 368 369/// checkUndefinedInternals - Check for undefined objects with internal linkage. 370static void checkUndefinedInternals(Sema &S) { 371 if (S.UndefinedInternals.empty()) return; 372 373 // Collect all the still-undefined entities with internal linkage. 374 SmallVector<UndefinedInternal, 16> undefined; 375 for (llvm::DenseMap<NamedDecl*,SourceLocation>::iterator 376 i = S.UndefinedInternals.begin(), e = S.UndefinedInternals.end(); 377 i != e; ++i) { 378 NamedDecl *decl = i->first; 379 380 // Ignore attributes that have become invalid. 381 if (decl->isInvalidDecl()) continue; 382 383 // __attribute__((weakref)) is basically a definition. 384 if (decl->hasAttr<WeakRefAttr>()) continue; 385 386 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) { 387 if (fn->isPure() || fn->hasBody()) 388 continue; 389 } else { 390 if (cast<VarDecl>(decl)->hasDefinition() != VarDecl::DeclarationOnly) 391 continue; 392 } 393 394 // We build a FullSourceLoc so that we can sort with array_pod_sort. 395 FullSourceLoc loc(i->second, S.Context.getSourceManager()); 396 undefined.push_back(UndefinedInternal(decl, loc)); 397 } 398 399 if (undefined.empty()) return; 400 401 // Sort (in order of use site) so that we're not (as) dependent on 402 // the iteration order through an llvm::DenseMap. 403 llvm::array_pod_sort(undefined.begin(), undefined.end()); 404 405 for (SmallVectorImpl<UndefinedInternal>::iterator 406 i = undefined.begin(), e = undefined.end(); i != e; ++i) { 407 NamedDecl *decl = i->decl; 408 S.Diag(decl->getLocation(), diag::warn_undefined_internal) 409 << isa<VarDecl>(decl) << decl; 410 S.Diag(i->useLoc, diag::note_used_here); 411 } 412} 413 414void Sema::LoadExternalWeakUndeclaredIdentifiers() { 415 if (!ExternalSource) 416 return; 417 418 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs; 419 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs); 420 for (unsigned I = 0, N = WeakIDs.size(); I != N; ++I) { 421 llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator Pos 422 = WeakUndeclaredIdentifiers.find(WeakIDs[I].first); 423 if (Pos != WeakUndeclaredIdentifiers.end()) 424 continue; 425 426 WeakUndeclaredIdentifiers.insert(WeakIDs[I]); 427 } 428} 429 430 431typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap; 432 433/// \brief Returns true, if all methods and nested classes of the given 434/// CXXRecordDecl are defined in this translation unit. 435/// 436/// Should only be called from ActOnEndOfTranslationUnit so that all 437/// definitions are actually read. 438static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD, 439 RecordCompleteMap &MNCComplete) { 440 RecordCompleteMap::iterator Cache = MNCComplete.find(RD); 441 if (Cache != MNCComplete.end()) 442 return Cache->second; 443 if (!RD->isCompleteDefinition()) 444 return false; 445 bool Complete = true; 446 for (DeclContext::decl_iterator I = RD->decls_begin(), 447 E = RD->decls_end(); 448 I != E && Complete; ++I) { 449 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I)) 450 Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M)); 451 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I)) 452 Complete = F->getTemplatedDecl()->isDefined(); 453 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) { 454 if (R->isInjectedClassName()) 455 continue; 456 if (R->hasDefinition()) 457 Complete = MethodsAndNestedClassesComplete(R->getDefinition(), 458 MNCComplete); 459 else 460 Complete = false; 461 } 462 } 463 MNCComplete[RD] = Complete; 464 return Complete; 465} 466 467/// \brief Returns true, if the given CXXRecordDecl is fully defined in this 468/// translation unit, i.e. all methods are defined or pure virtual and all 469/// friends, friend functions and nested classes are fully defined in this 470/// translation unit. 471/// 472/// Should only be called from ActOnEndOfTranslationUnit so that all 473/// definitions are actually read. 474static bool IsRecordFullyDefined(const CXXRecordDecl *RD, 475 RecordCompleteMap &RecordsComplete, 476 RecordCompleteMap &MNCComplete) { 477 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD); 478 if (Cache != RecordsComplete.end()) 479 return Cache->second; 480 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete); 481 for (CXXRecordDecl::friend_iterator I = RD->friend_begin(), 482 E = RD->friend_end(); 483 I != E && Complete; ++I) { 484 // Check if friend classes and methods are complete. 485 if (TypeSourceInfo *TSI = (*I)->getFriendType()) { 486 // Friend classes are available as the TypeSourceInfo of the FriendDecl. 487 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl()) 488 Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete); 489 else 490 Complete = false; 491 } else { 492 // Friend functions are available through the NamedDecl of FriendDecl. 493 if (const FunctionDecl *FD = 494 dyn_cast<FunctionDecl>((*I)->getFriendDecl())) 495 Complete = FD->isDefined(); 496 else 497 // This is a template friend, give up. 498 Complete = false; 499 } 500 } 501 RecordsComplete[RD] = Complete; 502 return Complete; 503} 504 505/// ActOnEndOfTranslationUnit - This is called at the very end of the 506/// translation unit when EOF is reached and all but the top-level scope is 507/// popped. 508void Sema::ActOnEndOfTranslationUnit() { 509 assert(DelayedDiagnostics.getCurrentPool() == NULL 510 && "reached end of translation unit with a pool attached?"); 511 512 // Only complete translation units define vtables and perform implicit 513 // instantiations. 514 if (TUKind == TU_Complete) { 515 DiagnoseUseOfUnimplementedSelectors(); 516 517 // If any dynamic classes have their key function defined within 518 // this translation unit, then those vtables are considered "used" and must 519 // be emitted. 520 for (DynamicClassesType::iterator I = DynamicClasses.begin(ExternalSource), 521 E = DynamicClasses.end(); 522 I != E; ++I) { 523 assert(!(*I)->isDependentType() && 524 "Should not see dependent types here!"); 525 if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(*I)) { 526 const FunctionDecl *Definition = 0; 527 if (KeyFunction->hasBody(Definition)) 528 MarkVTableUsed(Definition->getLocation(), *I, true); 529 } 530 } 531 532 // If DefinedUsedVTables ends up marking any virtual member functions it 533 // might lead to more pending template instantiations, which we then need 534 // to instantiate. 535 DefineUsedVTables(); 536 537 // C++: Perform implicit template instantiations. 538 // 539 // FIXME: When we perform these implicit instantiations, we do not 540 // carefully keep track of the point of instantiation (C++ [temp.point]). 541 // This means that name lookup that occurs within the template 542 // instantiation will always happen at the end of the translation unit, 543 // so it will find some names that should not be found. Although this is 544 // common behavior for C++ compilers, it is technically wrong. In the 545 // future, we either need to be able to filter the results of name lookup 546 // or we need to perform template instantiations earlier. 547 PerformPendingInstantiations(); 548 } 549 550 // Remove file scoped decls that turned out to be used. 551 UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(0, 552 true), 553 UnusedFileScopedDecls.end(), 554 std::bind1st(std::ptr_fun(ShouldRemoveFromUnused), 555 this)), 556 UnusedFileScopedDecls.end()); 557 558 if (TUKind == TU_Prefix) { 559 // Translation unit prefixes don't need any of the checking below. 560 TUScope = 0; 561 return; 562 } 563 564 // Check for #pragma weak identifiers that were never declared 565 // FIXME: This will cause diagnostics to be emitted in a non-determinstic 566 // order! Iterating over a densemap like this is bad. 567 LoadExternalWeakUndeclaredIdentifiers(); 568 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator 569 I = WeakUndeclaredIdentifiers.begin(), 570 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) { 571 if (I->second.getUsed()) continue; 572 573 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared) 574 << I->first; 575 } 576 577 if (TUKind == TU_Module) { 578 // If we are building a module, resolve all of the exported declarations 579 // now. 580 if (Module *CurrentModule = PP.getCurrentModule()) { 581 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); 582 583 llvm::SmallVector<Module *, 2> Stack; 584 Stack.push_back(CurrentModule); 585 while (!Stack.empty()) { 586 Module *Mod = Stack.back(); 587 Stack.pop_back(); 588 589 // Resolve the exported declarations. 590 // FIXME: Actually complain, once we figure out how to teach the 591 // diagnostic client to deal with complains in the module map at this 592 // point. 593 ModMap.resolveExports(Mod, /*Complain=*/false); 594 595 // Queue the submodules, so their exports will also be resolved. 596 for (Module::submodule_iterator Sub = Mod->submodule_begin(), 597 SubEnd = Mod->submodule_end(); 598 Sub != SubEnd; ++Sub) { 599 Stack.push_back(*Sub); 600 } 601 } 602 } 603 604 // Modules don't need any of the checking below. 605 TUScope = 0; 606 return; 607 } 608 609 // C99 6.9.2p2: 610 // A declaration of an identifier for an object that has file 611 // scope without an initializer, and without a storage-class 612 // specifier or with the storage-class specifier static, 613 // constitutes a tentative definition. If a translation unit 614 // contains one or more tentative definitions for an identifier, 615 // and the translation unit contains no external definition for 616 // that identifier, then the behavior is exactly as if the 617 // translation unit contains a file scope declaration of that 618 // identifier, with the composite type as of the end of the 619 // translation unit, with an initializer equal to 0. 620 llvm::SmallSet<VarDecl *, 32> Seen; 621 for (TentativeDefinitionsType::iterator 622 T = TentativeDefinitions.begin(ExternalSource), 623 TEnd = TentativeDefinitions.end(); 624 T != TEnd; ++T) 625 { 626 VarDecl *VD = (*T)->getActingDefinition(); 627 628 // If the tentative definition was completed, getActingDefinition() returns 629 // null. If we've already seen this variable before, insert()'s second 630 // return value is false. 631 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD)) 632 continue; 633 634 if (const IncompleteArrayType *ArrayT 635 = Context.getAsIncompleteArrayType(VD->getType())) { 636 if (RequireCompleteType(VD->getLocation(), 637 ArrayT->getElementType(), 638 diag::err_tentative_def_incomplete_type_arr)) { 639 VD->setInvalidDecl(); 640 continue; 641 } 642 643 // Set the length of the array to 1 (C99 6.9.2p5). 644 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 645 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 646 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), 647 One, ArrayType::Normal, 0); 648 VD->setType(T); 649 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 650 diag::err_tentative_def_incomplete_type)) 651 VD->setInvalidDecl(); 652 653 // Notify the consumer that we've completed a tentative definition. 654 if (!VD->isInvalidDecl()) 655 Consumer.CompleteTentativeDefinition(VD); 656 657 } 658 659 if (LangOpts.CPlusPlus0x && 660 Diags.getDiagnosticLevel(diag::warn_delegating_ctor_cycle, 661 SourceLocation()) 662 != DiagnosticsEngine::Ignored) 663 CheckDelegatingCtorCycles(); 664 665 // If there were errors, disable 'unused' warnings since they will mostly be 666 // noise. 667 if (!Diags.hasErrorOccurred()) { 668 // Output warning for unused file scoped decls. 669 for (UnusedFileScopedDeclsType::iterator 670 I = UnusedFileScopedDecls.begin(ExternalSource), 671 E = UnusedFileScopedDecls.end(); I != E; ++I) { 672 if (ShouldRemoveFromUnused(this, *I)) 673 continue; 674 675 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 676 const FunctionDecl *DiagD; 677 if (!FD->hasBody(DiagD)) 678 DiagD = FD; 679 if (DiagD->isDeleted()) 680 continue; // Deleted functions are supposed to be unused. 681 if (DiagD->isReferenced()) { 682 if (isa<CXXMethodDecl>(DiagD)) 683 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function) 684 << DiagD->getDeclName(); 685 else { 686 if (FD->getStorageClassAsWritten() == SC_Static && 687 !FD->isInlineSpecified() && 688 !SourceMgr.isFromMainFile( 689 SourceMgr.getExpansionLoc(FD->getLocation()))) 690 Diag(DiagD->getLocation(), diag::warn_unneeded_static_internal_decl) 691 << DiagD->getDeclName(); 692 else 693 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 694 << /*function*/0 << DiagD->getDeclName(); 695 } 696 } else { 697 Diag(DiagD->getLocation(), 698 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function 699 : diag::warn_unused_function) 700 << DiagD->getDeclName(); 701 } 702 } else { 703 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition(); 704 if (!DiagD) 705 DiagD = cast<VarDecl>(*I); 706 if (DiagD->isReferenced()) { 707 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 708 << /*variable*/1 << DiagD->getDeclName(); 709 } else { 710 Diag(DiagD->getLocation(), diag::warn_unused_variable) 711 << DiagD->getDeclName(); 712 } 713 } 714 } 715 716 checkUndefinedInternals(*this); 717 } 718 719 if (Diags.getDiagnosticLevel(diag::warn_unused_private_field, 720 SourceLocation()) 721 != DiagnosticsEngine::Ignored) { 722 RecordCompleteMap RecordsComplete; 723 RecordCompleteMap MNCComplete; 724 for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(), 725 E = UnusedPrivateFields.end(); I != E; ++I) { 726 const NamedDecl *D = *I; 727 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()); 728 if (RD && !RD->isUnion() && 729 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) { 730 Diag(D->getLocation(), diag::warn_unused_private_field) 731 << D->getDeclName(); 732 } 733 } 734 } 735 736 // Check we've noticed that we're no longer parsing the initializer for every 737 // variable. If we miss cases, then at best we have a performance issue and 738 // at worst a rejects-valid bug. 739 assert(ParsingInitForAutoVars.empty() && 740 "Didn't unmark var as having its initializer parsed"); 741 742 TUScope = 0; 743} 744 745 746//===----------------------------------------------------------------------===// 747// Helper functions. 748//===----------------------------------------------------------------------===// 749 750DeclContext *Sema::getFunctionLevelDeclContext() { 751 DeclContext *DC = CurContext; 752 753 while (true) { 754 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC)) { 755 DC = DC->getParent(); 756 } else if (isa<CXXMethodDecl>(DC) && 757 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 758 cast<CXXRecordDecl>(DC->getParent())->isLambda()) { 759 DC = DC->getParent()->getParent(); 760 } 761 else break; 762 } 763 764 return DC; 765} 766 767/// getCurFunctionDecl - If inside of a function body, this returns a pointer 768/// to the function decl for the function being parsed. If we're currently 769/// in a 'block', this returns the containing context. 770FunctionDecl *Sema::getCurFunctionDecl() { 771 DeclContext *DC = getFunctionLevelDeclContext(); 772 return dyn_cast<FunctionDecl>(DC); 773} 774 775ObjCMethodDecl *Sema::getCurMethodDecl() { 776 DeclContext *DC = getFunctionLevelDeclContext(); 777 return dyn_cast<ObjCMethodDecl>(DC); 778} 779 780NamedDecl *Sema::getCurFunctionOrMethodDecl() { 781 DeclContext *DC = getFunctionLevelDeclContext(); 782 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 783 return cast<NamedDecl>(DC); 784 return 0; 785} 786 787void Sema::EmitCurrentDiagnostic(unsigned DiagID) { 788 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here 789 // and yet we also use the current diag ID on the DiagnosticsEngine. This has 790 // been made more painfully obvious by the refactor that introduced this 791 // function, but it is possible that the incoming argument can be 792 // eliminnated. If it truly cannot be (for example, there is some reentrancy 793 // issue I am not seeing yet), then there should at least be a clarifying 794 // comment somewhere. 795 if (llvm::Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) { 796 switch (DiagnosticIDs::getDiagnosticSFINAEResponse( 797 Diags.getCurrentDiagID())) { 798 case DiagnosticIDs::SFINAE_Report: 799 // We'll report the diagnostic below. 800 break; 801 802 case DiagnosticIDs::SFINAE_SubstitutionFailure: 803 // Count this failure so that we know that template argument deduction 804 // has failed. 805 ++NumSFINAEErrors; 806 807 // Make a copy of this suppressed diagnostic and store it with the 808 // template-deduction information. 809 if (*Info && !(*Info)->hasSFINAEDiagnostic()) { 810 Diagnostic DiagInfo(&Diags); 811 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(), 812 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 813 } 814 815 Diags.setLastDiagnosticIgnored(); 816 Diags.Clear(); 817 return; 818 819 case DiagnosticIDs::SFINAE_AccessControl: { 820 // Per C++ Core Issue 1170, access control is part of SFINAE. 821 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily 822 // make access control a part of SFINAE for the purposes of checking 823 // type traits. 824 if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus0x) 825 break; 826 827 SourceLocation Loc = Diags.getCurrentDiagLoc(); 828 829 // Suppress this diagnostic. 830 ++NumSFINAEErrors; 831 832 // Make a copy of this suppressed diagnostic and store it with the 833 // template-deduction information. 834 if (*Info && !(*Info)->hasSFINAEDiagnostic()) { 835 Diagnostic DiagInfo(&Diags); 836 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(), 837 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 838 } 839 840 Diags.setLastDiagnosticIgnored(); 841 Diags.Clear(); 842 843 // Now the diagnostic state is clear, produce a C++98 compatibility 844 // warning. 845 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control); 846 847 // The last diagnostic which Sema produced was ignored. Suppress any 848 // notes attached to it. 849 Diags.setLastDiagnosticIgnored(); 850 return; 851 } 852 853 case DiagnosticIDs::SFINAE_Suppress: 854 // Make a copy of this suppressed diagnostic and store it with the 855 // template-deduction information; 856 if (*Info) { 857 Diagnostic DiagInfo(&Diags); 858 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(), 859 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 860 } 861 862 // Suppress this diagnostic. 863 Diags.setLastDiagnosticIgnored(); 864 Diags.Clear(); 865 return; 866 } 867 } 868 869 // Set up the context's printing policy based on our current state. 870 Context.setPrintingPolicy(getPrintingPolicy()); 871 872 // Emit the diagnostic. 873 if (!Diags.EmitCurrentDiagnostic()) 874 return; 875 876 // If this is not a note, and we're in a template instantiation 877 // that is different from the last template instantiation where 878 // we emitted an error, print a template instantiation 879 // backtrace. 880 if (!DiagnosticIDs::isBuiltinNote(DiagID) && 881 !ActiveTemplateInstantiations.empty() && 882 ActiveTemplateInstantiations.back() 883 != LastTemplateInstantiationErrorContext) { 884 PrintInstantiationStack(); 885 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiations.back(); 886 } 887} 888 889Sema::SemaDiagnosticBuilder 890Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 891 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 892 PD.Emit(Builder); 893 894 return Builder; 895} 896 897/// \brief Looks through the macro-expansion chain for the given 898/// location, looking for a macro expansion with the given name. 899/// If one is found, returns true and sets the location to that 900/// expansion loc. 901bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) { 902 SourceLocation loc = locref; 903 if (!loc.isMacroID()) return false; 904 905 // There's no good way right now to look at the intermediate 906 // expansions, so just jump to the expansion location. 907 loc = getSourceManager().getExpansionLoc(loc); 908 909 // If that's written with the name, stop here. 910 SmallVector<char, 16> buffer; 911 if (getPreprocessor().getSpelling(loc, buffer) == name) { 912 locref = loc; 913 return true; 914 } 915 return false; 916} 917 918/// \brief Determines the active Scope associated with the given declaration 919/// context. 920/// 921/// This routine maps a declaration context to the active Scope object that 922/// represents that declaration context in the parser. It is typically used 923/// from "scope-less" code (e.g., template instantiation, lazy creation of 924/// declarations) that injects a name for name-lookup purposes and, therefore, 925/// must update the Scope. 926/// 927/// \returns The scope corresponding to the given declaraion context, or NULL 928/// if no such scope is open. 929Scope *Sema::getScopeForContext(DeclContext *Ctx) { 930 931 if (!Ctx) 932 return 0; 933 934 Ctx = Ctx->getPrimaryContext(); 935 for (Scope *S = getCurScope(); S; S = S->getParent()) { 936 // Ignore scopes that cannot have declarations. This is important for 937 // out-of-line definitions of static class members. 938 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) 939 if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity())) 940 if (Ctx == Entity->getPrimaryContext()) 941 return S; 942 } 943 944 return 0; 945} 946 947/// \brief Enter a new function scope 948void Sema::PushFunctionScope() { 949 if (FunctionScopes.size() == 1) { 950 // Use the "top" function scope rather than having to allocate 951 // memory for a new scope. 952 FunctionScopes.back()->Clear(); 953 FunctionScopes.push_back(FunctionScopes.back()); 954 return; 955 } 956 957 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics())); 958} 959 960void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) { 961 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(), 962 BlockScope, Block)); 963} 964 965void Sema::PushLambdaScope(CXXRecordDecl *Lambda, 966 CXXMethodDecl *CallOperator) { 967 FunctionScopes.push_back(new LambdaScopeInfo(getDiagnostics(), Lambda, 968 CallOperator)); 969} 970 971void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP, 972 const Decl *D, const BlockExpr *blkExpr) { 973 FunctionScopeInfo *Scope = FunctionScopes.pop_back_val(); 974 assert(!FunctionScopes.empty() && "mismatched push/pop!"); 975 976 // Issue any analysis-based warnings. 977 if (WP && D) 978 AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr); 979 else { 980 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator 981 i = Scope->PossiblyUnreachableDiags.begin(), 982 e = Scope->PossiblyUnreachableDiags.end(); 983 i != e; ++i) { 984 const sema::PossiblyUnreachableDiag &D = *i; 985 Diag(D.Loc, D.PD); 986 } 987 } 988 989 if (FunctionScopes.back() != Scope) { 990 delete Scope; 991 } 992} 993 994void Sema::PushCompoundScope() { 995 getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo()); 996} 997 998void Sema::PopCompoundScope() { 999 FunctionScopeInfo *CurFunction = getCurFunction(); 1000 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop"); 1001 1002 CurFunction->CompoundScopes.pop_back(); 1003} 1004 1005/// \brief Determine whether any errors occurred within this function/method/ 1006/// block. 1007bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const { 1008 return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred(); 1009} 1010 1011BlockScopeInfo *Sema::getCurBlock() { 1012 if (FunctionScopes.empty()) 1013 return 0; 1014 1015 return dyn_cast<BlockScopeInfo>(FunctionScopes.back()); 1016} 1017 1018LambdaScopeInfo *Sema::getCurLambda() { 1019 if (FunctionScopes.empty()) 1020 return 0; 1021 1022 return dyn_cast<LambdaScopeInfo>(FunctionScopes.back()); 1023} 1024 1025void Sema::ActOnComment(SourceRange Comment) { 1026 RawComment RC(SourceMgr, Comment); 1027 if (RC.isAlmostTrailingComment()) { 1028 SourceRange MagicMarkerRange(Comment.getBegin(), 1029 Comment.getBegin().getLocWithOffset(3)); 1030 StringRef MagicMarkerText; 1031 switch (RC.getKind()) { 1032 case RawComment::CK_OrdinaryBCPL: 1033 MagicMarkerText = "///<"; 1034 break; 1035 case RawComment::CK_OrdinaryC: 1036 MagicMarkerText = "/**<"; 1037 break; 1038 default: 1039 llvm_unreachable("if this is an almost Doxygen comment, " 1040 "it should be ordinary"); 1041 } 1042 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) << 1043 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText); 1044 } 1045 Context.addComment(RC); 1046} 1047 1048// Pin this vtable to this file. 1049ExternalSemaSource::~ExternalSemaSource() {} 1050 1051void ExternalSemaSource::ReadMethodPool(Selector Sel) { } 1052 1053void ExternalSemaSource::ReadKnownNamespaces( 1054 SmallVectorImpl<NamespaceDecl *> &Namespaces) { 1055} 1056 1057void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const { 1058 SourceLocation Loc = this->Loc; 1059 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation(); 1060 if (Loc.isValid()) { 1061 Loc.print(OS, S.getSourceManager()); 1062 OS << ": "; 1063 } 1064 OS << Message; 1065 1066 if (TheDecl && isa<NamedDecl>(TheDecl)) { 1067 std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString(); 1068 if (!Name.empty()) 1069 OS << " '" << Name << '\''; 1070 } 1071 1072 OS << '\n'; 1073} 1074 1075/// \brief Figure out if an expression could be turned into a call. 1076/// 1077/// Use this when trying to recover from an error where the programmer may have 1078/// written just the name of a function instead of actually calling it. 1079/// 1080/// \param E - The expression to examine. 1081/// \param ZeroArgCallReturnTy - If the expression can be turned into a call 1082/// with no arguments, this parameter is set to the type returned by such a 1083/// call; otherwise, it is set to an empty QualType. 1084/// \param OverloadSet - If the expression is an overloaded function 1085/// name, this parameter is populated with the decls of the various overloads. 1086bool Sema::isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy, 1087 UnresolvedSetImpl &OverloadSet) { 1088 ZeroArgCallReturnTy = QualType(); 1089 OverloadSet.clear(); 1090 1091 if (E.getType() == Context.OverloadTy) { 1092 OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E)); 1093 const OverloadExpr *Overloads = FR.Expression; 1094 1095 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(), 1096 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) { 1097 OverloadSet.addDecl(*it); 1098 1099 // Check whether the function is a non-template which takes no 1100 // arguments. 1101 if (const FunctionDecl *OverloadDecl 1102 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) { 1103 if (OverloadDecl->getMinRequiredArguments() == 0) 1104 ZeroArgCallReturnTy = OverloadDecl->getResultType(); 1105 } 1106 } 1107 1108 // Ignore overloads that are pointer-to-member constants. 1109 if (FR.HasFormOfMemberPointer) 1110 return false; 1111 1112 return true; 1113 } 1114 1115 if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) { 1116 if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) { 1117 if (Fun->getMinRequiredArguments() == 0) 1118 ZeroArgCallReturnTy = Fun->getResultType(); 1119 return true; 1120 } 1121 } 1122 1123 // We don't have an expression that's convenient to get a FunctionDecl from, 1124 // but we can at least check if the type is "function of 0 arguments". 1125 QualType ExprTy = E.getType(); 1126 const FunctionType *FunTy = NULL; 1127 QualType PointeeTy = ExprTy->getPointeeType(); 1128 if (!PointeeTy.isNull()) 1129 FunTy = PointeeTy->getAs<FunctionType>(); 1130 if (!FunTy) 1131 FunTy = ExprTy->getAs<FunctionType>(); 1132 if (!FunTy && ExprTy == Context.BoundMemberTy) { 1133 // Look for the bound-member type. If it's still overloaded, give up, 1134 // although we probably should have fallen into the OverloadExpr case above 1135 // if we actually have an overloaded bound member. 1136 QualType BoundMemberTy = Expr::findBoundMemberType(&E); 1137 if (!BoundMemberTy.isNull()) 1138 FunTy = BoundMemberTy->castAs<FunctionType>(); 1139 } 1140 1141 if (const FunctionProtoType *FPT = 1142 dyn_cast_or_null<FunctionProtoType>(FunTy)) { 1143 if (FPT->getNumArgs() == 0) 1144 ZeroArgCallReturnTy = FunTy->getResultType(); 1145 return true; 1146 } 1147 return false; 1148} 1149 1150/// \brief Give notes for a set of overloads. 1151/// 1152/// A companion to isExprCallable. In cases when the name that the programmer 1153/// wrote was an overloaded function, we may be able to make some guesses about 1154/// plausible overloads based on their return types; such guesses can be handed 1155/// off to this method to be emitted as notes. 1156/// 1157/// \param Overloads - The overloads to note. 1158/// \param FinalNoteLoc - If we've suppressed printing some overloads due to 1159/// -fshow-overloads=best, this is the location to attach to the note about too 1160/// many candidates. Typically this will be the location of the original 1161/// ill-formed expression. 1162static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, 1163 const SourceLocation FinalNoteLoc) { 1164 int ShownOverloads = 0; 1165 int SuppressedOverloads = 0; 1166 for (UnresolvedSetImpl::iterator It = Overloads.begin(), 1167 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 1168 // FIXME: Magic number for max shown overloads stolen from 1169 // OverloadCandidateSet::NoteCandidates. 1170 if (ShownOverloads >= 4 && 1171 S.Diags.getShowOverloads() == DiagnosticsEngine::Ovl_Best) { 1172 ++SuppressedOverloads; 1173 continue; 1174 } 1175 1176 NamedDecl *Fn = (*It)->getUnderlyingDecl(); 1177 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call); 1178 ++ShownOverloads; 1179 } 1180 1181 if (SuppressedOverloads) 1182 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates) 1183 << SuppressedOverloads; 1184} 1185 1186static void notePlausibleOverloads(Sema &S, SourceLocation Loc, 1187 const UnresolvedSetImpl &Overloads, 1188 bool (*IsPlausibleResult)(QualType)) { 1189 if (!IsPlausibleResult) 1190 return noteOverloads(S, Overloads, Loc); 1191 1192 UnresolvedSet<2> PlausibleOverloads; 1193 for (OverloadExpr::decls_iterator It = Overloads.begin(), 1194 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 1195 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It); 1196 QualType OverloadResultTy = OverloadDecl->getResultType(); 1197 if (IsPlausibleResult(OverloadResultTy)) 1198 PlausibleOverloads.addDecl(It.getDecl()); 1199 } 1200 noteOverloads(S, PlausibleOverloads, Loc); 1201} 1202 1203/// Determine whether the given expression can be called by just 1204/// putting parentheses after it. Notably, expressions with unary 1205/// operators can't be because the unary operator will start parsing 1206/// outside the call. 1207static bool IsCallableWithAppend(Expr *E) { 1208 E = E->IgnoreImplicit(); 1209 return (!isa<CStyleCastExpr>(E) && 1210 !isa<UnaryOperator>(E) && 1211 !isa<BinaryOperator>(E) && 1212 !isa<CXXOperatorCallExpr>(E)); 1213} 1214 1215bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 1216 bool ForceComplain, 1217 bool (*IsPlausibleResult)(QualType)) { 1218 SourceLocation Loc = E.get()->getExprLoc(); 1219 SourceRange Range = E.get()->getSourceRange(); 1220 1221 QualType ZeroArgCallTy; 1222 UnresolvedSet<4> Overloads; 1223 if (isExprCallable(*E.get(), ZeroArgCallTy, Overloads) && 1224 !ZeroArgCallTy.isNull() && 1225 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) { 1226 // At this point, we know E is potentially callable with 0 1227 // arguments and that it returns something of a reasonable type, 1228 // so we can emit a fixit and carry on pretending that E was 1229 // actually a CallExpr. 1230 SourceLocation ParenInsertionLoc = 1231 PP.getLocForEndOfToken(Range.getEnd()); 1232 Diag(Loc, PD) 1233 << /*zero-arg*/ 1 << Range 1234 << (IsCallableWithAppend(E.get()) 1235 ? FixItHint::CreateInsertion(ParenInsertionLoc, "()") 1236 : FixItHint()); 1237 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult); 1238 1239 // FIXME: Try this before emitting the fixit, and suppress diagnostics 1240 // while doing so. 1241 E = ActOnCallExpr(0, E.take(), ParenInsertionLoc, 1242 MultiExprArg(*this, 0, 0), 1243 ParenInsertionLoc.getLocWithOffset(1)); 1244 return true; 1245 } 1246 1247 if (!ForceComplain) return false; 1248 1249 Diag(Loc, PD) << /*not zero-arg*/ 0 << Range; 1250 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult); 1251 E = ExprError(); 1252 return true; 1253} 1254