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