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