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