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