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