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