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 /// Obtains a sorted list of functions and variables that are undefined but 586 /// ODR-used. 587 void Sema::getUndefinedButUsed( 588 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) { 589 for (const auto &UndefinedUse : UndefinedButUsed) { 590 NamedDecl *ND = UndefinedUse.first; 591 592 // Ignore attributes that have become invalid. 593 if (ND->isInvalidDecl()) continue; 594 595 // __attribute__((weakref)) is basically a definition. 596 if (ND->hasAttr<WeakRefAttr>()) continue; 597 598 if (isa<CXXDeductionGuideDecl>(ND)) 599 continue; 600 601 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 602 if (FD->isDefined()) 603 continue; 604 if (FD->isExternallyVisible() && 605 !FD->getMostRecentDecl()->isInlined()) 606 continue; 607 } else { 608 auto *VD = cast<VarDecl>(ND); 609 if (VD->hasDefinition() != VarDecl::DeclarationOnly) 610 continue; 611 if (VD->isExternallyVisible() && !VD->getMostRecentDecl()->isInline()) 612 continue; 613 } 614 615 Undefined.push_back(std::make_pair(ND, UndefinedUse.second)); 616 } 617 } 618 619 /// checkUndefinedButUsed - Check for undefined objects with internal linkage 620 /// or that are inline. 621 static void checkUndefinedButUsed(Sema &S) { 622 if (S.UndefinedButUsed.empty()) return; 623 624 // Collect all the still-undefined entities with internal linkage. 625 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined; 626 S.getUndefinedButUsed(Undefined); 627 if (Undefined.empty()) return; 628 629 for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator 630 I = Undefined.begin(), E = Undefined.end(); I != E; ++I) { 631 NamedDecl *ND = I->first; 632 633 if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) { 634 // An exported function will always be emitted when defined, so even if 635 // the function is inline, it doesn't have to be emitted in this TU. An 636 // imported function implies that it has been exported somewhere else. 637 continue; 638 } 639 640 if (!ND->isExternallyVisible()) { 641 S.Diag(ND->getLocation(), diag::warn_undefined_internal) 642 << isa<VarDecl>(ND) << ND; 643 } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) { 644 (void)FD; 645 assert(FD->getMostRecentDecl()->isInlined() && 646 "used object requires definition but isn't inline or internal?"); 647 // FIXME: This is ill-formed; we should reject. 648 S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND; 649 } else { 650 assert(cast<VarDecl>(ND)->getMostRecentDecl()->isInline() && 651 "used var requires definition but isn't inline or internal?"); 652 S.Diag(ND->getLocation(), diag::err_undefined_inline_var) << ND; 653 } 654 if (I->second.isValid()) 655 S.Diag(I->second, diag::note_used_here); 656 } 657 658 S.UndefinedButUsed.clear(); 659 } 660 661 void Sema::LoadExternalWeakUndeclaredIdentifiers() { 662 if (!ExternalSource) 663 return; 664 665 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs; 666 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs); 667 for (auto &WeakID : WeakIDs) 668 WeakUndeclaredIdentifiers.insert(WeakID); 669 } 670 671 672 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap; 673 674 /// \brief Returns true, if all methods and nested classes of the given 675 /// CXXRecordDecl are defined in this translation unit. 676 /// 677 /// Should only be called from ActOnEndOfTranslationUnit so that all 678 /// definitions are actually read. 679 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD, 680 RecordCompleteMap &MNCComplete) { 681 RecordCompleteMap::iterator Cache = MNCComplete.find(RD); 682 if (Cache != MNCComplete.end()) 683 return Cache->second; 684 if (!RD->isCompleteDefinition()) 685 return false; 686 bool Complete = true; 687 for (DeclContext::decl_iterator I = RD->decls_begin(), 688 E = RD->decls_end(); 689 I != E && Complete; ++I) { 690 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I)) 691 Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M)); 692 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I)) 693 // If the template function is marked as late template parsed at this 694 // point, it has not been instantiated and therefore we have not 695 // performed semantic analysis on it yet, so we cannot know if the type 696 // can be considered complete. 697 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() && 698 F->getTemplatedDecl()->isDefined(); 699 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) { 700 if (R->isInjectedClassName()) 701 continue; 702 if (R->hasDefinition()) 703 Complete = MethodsAndNestedClassesComplete(R->getDefinition(), 704 MNCComplete); 705 else 706 Complete = false; 707 } 708 } 709 MNCComplete[RD] = Complete; 710 return Complete; 711 } 712 713 /// \brief Returns true, if the given CXXRecordDecl is fully defined in this 714 /// translation unit, i.e. all methods are defined or pure virtual and all 715 /// friends, friend functions and nested classes are fully defined in this 716 /// translation unit. 717 /// 718 /// Should only be called from ActOnEndOfTranslationUnit so that all 719 /// definitions are actually read. 720 static bool IsRecordFullyDefined(const CXXRecordDecl *RD, 721 RecordCompleteMap &RecordsComplete, 722 RecordCompleteMap &MNCComplete) { 723 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD); 724 if (Cache != RecordsComplete.end()) 725 return Cache->second; 726 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete); 727 for (CXXRecordDecl::friend_iterator I = RD->friend_begin(), 728 E = RD->friend_end(); 729 I != E && Complete; ++I) { 730 // Check if friend classes and methods are complete. 731 if (TypeSourceInfo *TSI = (*I)->getFriendType()) { 732 // Friend classes are available as the TypeSourceInfo of the FriendDecl. 733 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl()) 734 Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete); 735 else 736 Complete = false; 737 } else { 738 // Friend functions are available through the NamedDecl of FriendDecl. 739 if (const FunctionDecl *FD = 740 dyn_cast<FunctionDecl>((*I)->getFriendDecl())) 741 Complete = FD->isDefined(); 742 else 743 // This is a template friend, give up. 744 Complete = false; 745 } 746 } 747 RecordsComplete[RD] = Complete; 748 return Complete; 749 } 750 751 void Sema::emitAndClearUnusedLocalTypedefWarnings() { 752 if (ExternalSource) 753 ExternalSource->ReadUnusedLocalTypedefNameCandidates( 754 UnusedLocalTypedefNameCandidates); 755 for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) { 756 if (TD->isReferenced()) 757 continue; 758 Diag(TD->getLocation(), diag::warn_unused_local_typedef) 759 << isa<TypeAliasDecl>(TD) << TD->getDeclName(); 760 } 761 UnusedLocalTypedefNameCandidates.clear(); 762 } 763 764 /// This is called before the very first declaration in the translation unit 765 /// is parsed. Note that the ASTContext may have already injected some 766 /// declarations. 767 void Sema::ActOnStartOfTranslationUnit() { 768 if (getLangOpts().ModulesTS) { 769 // We start in the global module; all those declarations are implicitly 770 // module-private (though they do not have module linkage). 771 Context.getTranslationUnitDecl()->setModuleOwnershipKind( 772 Decl::ModuleOwnershipKind::ModulePrivate); 773 } 774 } 775 776 /// ActOnEndOfTranslationUnit - This is called at the very end of the 777 /// translation unit when EOF is reached and all but the top-level scope is 778 /// popped. 779 void Sema::ActOnEndOfTranslationUnit() { 780 assert(DelayedDiagnostics.getCurrentPool() == nullptr 781 && "reached end of translation unit with a pool attached?"); 782 783 // If code completion is enabled, don't perform any end-of-translation-unit 784 // work. 785 if (PP.isCodeCompletionEnabled()) 786 return; 787 788 // Complete translation units and modules define vtables and perform implicit 789 // instantiations. PCH files do not. 790 if (TUKind != TU_Prefix) { 791 DiagnoseUseOfUnimplementedSelectors(); 792 793 // If DefinedUsedVTables ends up marking any virtual member functions it 794 // might lead to more pending template instantiations, which we then need 795 // to instantiate. 796 DefineUsedVTables(); 797 798 // C++: Perform implicit template instantiations. 799 // 800 // FIXME: When we perform these implicit instantiations, we do not 801 // carefully keep track of the point of instantiation (C++ [temp.point]). 802 // This means that name lookup that occurs within the template 803 // instantiation will always happen at the end of the translation unit, 804 // so it will find some names that are not required to be found. This is 805 // valid, but we could do better by diagnosing if an instantiation uses a 806 // name that was not visible at its first point of instantiation. 807 if (ExternalSource) { 808 // Load pending instantiations from the external source. 809 SmallVector<PendingImplicitInstantiation, 4> Pending; 810 ExternalSource->ReadPendingInstantiations(Pending); 811 for (auto PII : Pending) 812 if (auto Func = dyn_cast<FunctionDecl>(PII.first)) 813 Func->setInstantiationIsPending(true); 814 PendingInstantiations.insert(PendingInstantiations.begin(), 815 Pending.begin(), Pending.end()); 816 } 817 PerformPendingInstantiations(); 818 819 if (LateTemplateParserCleanup) 820 LateTemplateParserCleanup(OpaqueParser); 821 822 CheckDelayedMemberExceptionSpecs(); 823 } 824 825 DiagnoseUnterminatedPragmaPack(); 826 DiagnoseUnterminatedPragmaAttribute(); 827 828 // All delayed member exception specs should be checked or we end up accepting 829 // incompatible declarations. 830 // FIXME: This is wrong for TUKind == TU_Prefix. In that case, we need to 831 // write out the lists to the AST file (if any). 832 assert(DelayedDefaultedMemberExceptionSpecs.empty()); 833 assert(DelayedExceptionSpecChecks.empty()); 834 835 // All dllexport classes should have been processed already. 836 assert(DelayedDllExportClasses.empty()); 837 838 // Remove file scoped decls that turned out to be used. 839 UnusedFileScopedDecls.erase( 840 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true), 841 UnusedFileScopedDecls.end(), 842 [this](const DeclaratorDecl *DD) { 843 return ShouldRemoveFromUnused(this, DD); 844 }), 845 UnusedFileScopedDecls.end()); 846 847 if (TUKind == TU_Prefix) { 848 // Translation unit prefixes don't need any of the checking below. 849 if (!PP.isIncrementalProcessingEnabled()) 850 TUScope = nullptr; 851 return; 852 } 853 854 // Check for #pragma weak identifiers that were never declared 855 LoadExternalWeakUndeclaredIdentifiers(); 856 for (auto WeakID : WeakUndeclaredIdentifiers) { 857 if (WeakID.second.getUsed()) 858 continue; 859 860 Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(), 861 LookupOrdinaryName); 862 if (PrevDecl != nullptr && 863 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) 864 Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type) 865 << "'weak'" << ExpectedVariableOrFunction; 866 else 867 Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared) 868 << WeakID.first; 869 } 870 871 if (LangOpts.CPlusPlus11 && 872 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation())) 873 CheckDelegatingCtorCycles(); 874 875 if (!Diags.hasErrorOccurred()) { 876 if (ExternalSource) 877 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed); 878 checkUndefinedButUsed(*this); 879 } 880 881 if (TUKind == TU_Module) { 882 // If we are building a module, resolve all of the exported declarations 883 // now. 884 if (Module *CurrentModule = PP.getCurrentModule()) { 885 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); 886 887 SmallVector<Module *, 2> Stack; 888 Stack.push_back(CurrentModule); 889 while (!Stack.empty()) { 890 Module *Mod = Stack.pop_back_val(); 891 892 // Resolve the exported declarations and conflicts. 893 // FIXME: Actually complain, once we figure out how to teach the 894 // diagnostic client to deal with complaints in the module map at this 895 // point. 896 ModMap.resolveExports(Mod, /*Complain=*/false); 897 ModMap.resolveUses(Mod, /*Complain=*/false); 898 ModMap.resolveConflicts(Mod, /*Complain=*/false); 899 900 // Queue the submodules, so their exports will also be resolved. 901 Stack.append(Mod->submodule_begin(), Mod->submodule_end()); 902 } 903 } 904 905 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for 906 // modules when they are built, not every time they are used. 907 emitAndClearUnusedLocalTypedefWarnings(); 908 909 // Modules don't need any of the checking below. 910 if (!PP.isIncrementalProcessingEnabled()) 911 TUScope = nullptr; 912 return; 913 } 914 915 // C99 6.9.2p2: 916 // A declaration of an identifier for an object that has file 917 // scope without an initializer, and without a storage-class 918 // specifier or with the storage-class specifier static, 919 // constitutes a tentative definition. If a translation unit 920 // contains one or more tentative definitions for an identifier, 921 // and the translation unit contains no external definition for 922 // that identifier, then the behavior is exactly as if the 923 // translation unit contains a file scope declaration of that 924 // identifier, with the composite type as of the end of the 925 // translation unit, with an initializer equal to 0. 926 llvm::SmallSet<VarDecl *, 32> Seen; 927 for (TentativeDefinitionsType::iterator 928 T = TentativeDefinitions.begin(ExternalSource), 929 TEnd = TentativeDefinitions.end(); 930 T != TEnd; ++T) 931 { 932 VarDecl *VD = (*T)->getActingDefinition(); 933 934 // If the tentative definition was completed, getActingDefinition() returns 935 // null. If we've already seen this variable before, insert()'s second 936 // return value is false. 937 if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second) 938 continue; 939 940 if (const IncompleteArrayType *ArrayT 941 = Context.getAsIncompleteArrayType(VD->getType())) { 942 // Set the length of the array to 1 (C99 6.9.2p5). 943 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 944 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 945 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), 946 One, ArrayType::Normal, 0); 947 VD->setType(T); 948 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 949 diag::err_tentative_def_incomplete_type)) 950 VD->setInvalidDecl(); 951 952 // No initialization is performed for a tentative definition. 953 CheckCompleteVariableDeclaration(VD); 954 955 // Notify the consumer that we've completed a tentative definition. 956 if (!VD->isInvalidDecl()) 957 Consumer.CompleteTentativeDefinition(VD); 958 959 } 960 961 // If there were errors, disable 'unused' warnings since they will mostly be 962 // noise. 963 if (!Diags.hasErrorOccurred()) { 964 // Output warning for unused file scoped decls. 965 for (UnusedFileScopedDeclsType::iterator 966 I = UnusedFileScopedDecls.begin(ExternalSource), 967 E = UnusedFileScopedDecls.end(); I != E; ++I) { 968 if (ShouldRemoveFromUnused(this, *I)) 969 continue; 970 971 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 972 const FunctionDecl *DiagD; 973 if (!FD->hasBody(DiagD)) 974 DiagD = FD; 975 if (DiagD->isDeleted()) 976 continue; // Deleted functions are supposed to be unused. 977 if (DiagD->isReferenced()) { 978 if (isa<CXXMethodDecl>(DiagD)) 979 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function) 980 << DiagD->getDeclName(); 981 else { 982 if (FD->getStorageClass() == SC_Static && 983 !FD->isInlineSpecified() && 984 !SourceMgr.isInMainFile( 985 SourceMgr.getExpansionLoc(FD->getLocation()))) 986 Diag(DiagD->getLocation(), 987 diag::warn_unneeded_static_internal_decl) 988 << DiagD->getDeclName(); 989 else 990 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 991 << /*function*/0 << DiagD->getDeclName(); 992 } 993 } else { 994 if (FD->getDescribedFunctionTemplate()) 995 Diag(DiagD->getLocation(), diag::warn_unused_template) 996 << /*function*/0 << DiagD->getDeclName(); 997 else 998 Diag(DiagD->getLocation(), 999 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function 1000 : diag::warn_unused_function) 1001 << DiagD->getDeclName(); 1002 } 1003 } else { 1004 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition(); 1005 if (!DiagD) 1006 DiagD = cast<VarDecl>(*I); 1007 if (DiagD->isReferenced()) { 1008 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 1009 << /*variable*/1 << DiagD->getDeclName(); 1010 } else if (DiagD->getType().isConstQualified()) { 1011 const SourceManager &SM = SourceMgr; 1012 if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) || 1013 !PP.getLangOpts().IsHeaderFile) 1014 Diag(DiagD->getLocation(), diag::warn_unused_const_variable) 1015 << DiagD->getDeclName(); 1016 } else { 1017 if (DiagD->getDescribedVarTemplate()) 1018 Diag(DiagD->getLocation(), diag::warn_unused_template) 1019 << /*variable*/1 << DiagD->getDeclName(); 1020 else 1021 Diag(DiagD->getLocation(), diag::warn_unused_variable) 1022 << DiagD->getDeclName(); 1023 } 1024 } 1025 } 1026 1027 emitAndClearUnusedLocalTypedefWarnings(); 1028 } 1029 1030 if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) { 1031 RecordCompleteMap RecordsComplete; 1032 RecordCompleteMap MNCComplete; 1033 for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(), 1034 E = UnusedPrivateFields.end(); I != E; ++I) { 1035 const NamedDecl *D = *I; 1036 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()); 1037 if (RD && !RD->isUnion() && 1038 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) { 1039 Diag(D->getLocation(), diag::warn_unused_private_field) 1040 << D->getDeclName(); 1041 } 1042 } 1043 } 1044 1045 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) { 1046 if (ExternalSource) 1047 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs); 1048 for (const auto &DeletedFieldInfo : DeleteExprs) { 1049 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) { 1050 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first, 1051 DeleteExprLoc.second); 1052 } 1053 } 1054 } 1055 1056 // Check we've noticed that we're no longer parsing the initializer for every 1057 // variable. If we miss cases, then at best we have a performance issue and 1058 // at worst a rejects-valid bug. 1059 assert(ParsingInitForAutoVars.empty() && 1060 "Didn't unmark var as having its initializer parsed"); 1061 1062 if (!PP.isIncrementalProcessingEnabled()) 1063 TUScope = nullptr; 1064 } 1065 1066 1067 //===----------------------------------------------------------------------===// 1068 // Helper functions. 1069 //===----------------------------------------------------------------------===// 1070 1071 DeclContext *Sema::getFunctionLevelDeclContext() { 1072 DeclContext *DC = CurContext; 1073 1074 while (true) { 1075 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) { 1076 DC = DC->getParent(); 1077 } else if (isa<CXXMethodDecl>(DC) && 1078 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 1079 cast<CXXRecordDecl>(DC->getParent())->isLambda()) { 1080 DC = DC->getParent()->getParent(); 1081 } 1082 else break; 1083 } 1084 1085 return DC; 1086 } 1087 1088 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 1089 /// to the function decl for the function being parsed. If we're currently 1090 /// in a 'block', this returns the containing context. 1091 FunctionDecl *Sema::getCurFunctionDecl() { 1092 DeclContext *DC = getFunctionLevelDeclContext(); 1093 return dyn_cast<FunctionDecl>(DC); 1094 } 1095 1096 ObjCMethodDecl *Sema::getCurMethodDecl() { 1097 DeclContext *DC = getFunctionLevelDeclContext(); 1098 while (isa<RecordDecl>(DC)) 1099 DC = DC->getParent(); 1100 return dyn_cast<ObjCMethodDecl>(DC); 1101 } 1102 1103 NamedDecl *Sema::getCurFunctionOrMethodDecl() { 1104 DeclContext *DC = getFunctionLevelDeclContext(); 1105 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 1106 return cast<NamedDecl>(DC); 1107 return nullptr; 1108 } 1109 1110 void Sema::EmitCurrentDiagnostic(unsigned DiagID) { 1111 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here 1112 // and yet we also use the current diag ID on the DiagnosticsEngine. This has 1113 // been made more painfully obvious by the refactor that introduced this 1114 // function, but it is possible that the incoming argument can be 1115 // eliminated. If it truly cannot be (for example, there is some reentrancy 1116 // issue I am not seeing yet), then there should at least be a clarifying 1117 // comment somewhere. 1118 if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) { 1119 switch (DiagnosticIDs::getDiagnosticSFINAEResponse( 1120 Diags.getCurrentDiagID())) { 1121 case DiagnosticIDs::SFINAE_Report: 1122 // We'll report the diagnostic below. 1123 break; 1124 1125 case DiagnosticIDs::SFINAE_SubstitutionFailure: 1126 // Count this failure so that we know that template argument deduction 1127 // has failed. 1128 ++NumSFINAEErrors; 1129 1130 // Make a copy of this suppressed diagnostic and store it with the 1131 // template-deduction information. 1132 if (*Info && !(*Info)->hasSFINAEDiagnostic()) { 1133 Diagnostic DiagInfo(&Diags); 1134 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(), 1135 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1136 } 1137 1138 Diags.setLastDiagnosticIgnored(); 1139 Diags.Clear(); 1140 return; 1141 1142 case DiagnosticIDs::SFINAE_AccessControl: { 1143 // Per C++ Core Issue 1170, access control is part of SFINAE. 1144 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily 1145 // make access control a part of SFINAE for the purposes of checking 1146 // type traits. 1147 if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11) 1148 break; 1149 1150 SourceLocation Loc = Diags.getCurrentDiagLoc(); 1151 1152 // Suppress this diagnostic. 1153 ++NumSFINAEErrors; 1154 1155 // Make a copy of this suppressed diagnostic and store it with the 1156 // template-deduction information. 1157 if (*Info && !(*Info)->hasSFINAEDiagnostic()) { 1158 Diagnostic DiagInfo(&Diags); 1159 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(), 1160 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1161 } 1162 1163 Diags.setLastDiagnosticIgnored(); 1164 Diags.Clear(); 1165 1166 // Now the diagnostic state is clear, produce a C++98 compatibility 1167 // warning. 1168 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control); 1169 1170 // The last diagnostic which Sema produced was ignored. Suppress any 1171 // notes attached to it. 1172 Diags.setLastDiagnosticIgnored(); 1173 return; 1174 } 1175 1176 case DiagnosticIDs::SFINAE_Suppress: 1177 // Make a copy of this suppressed diagnostic and store it with the 1178 // template-deduction information; 1179 if (*Info) { 1180 Diagnostic DiagInfo(&Diags); 1181 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(), 1182 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1183 } 1184 1185 // Suppress this diagnostic. 1186 Diags.setLastDiagnosticIgnored(); 1187 Diags.Clear(); 1188 return; 1189 } 1190 } 1191 1192 // Set up the context's printing policy based on our current state. 1193 Context.setPrintingPolicy(getPrintingPolicy()); 1194 1195 // Emit the diagnostic. 1196 if (!Diags.EmitCurrentDiagnostic()) 1197 return; 1198 1199 // If this is not a note, and we're in a template instantiation 1200 // that is different from the last template instantiation where 1201 // we emitted an error, print a template instantiation 1202 // backtrace. 1203 if (!DiagnosticIDs::isBuiltinNote(DiagID)) 1204 PrintContextStack(); 1205 } 1206 1207 Sema::SemaDiagnosticBuilder 1208 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) { 1209 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID())); 1210 PD.Emit(Builder); 1211 1212 return Builder; 1213 } 1214 1215 /// \brief Looks through the macro-expansion chain for the given 1216 /// location, looking for a macro expansion with the given name. 1217 /// If one is found, returns true and sets the location to that 1218 /// expansion loc. 1219 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) { 1220 SourceLocation loc = locref; 1221 if (!loc.isMacroID()) return false; 1222 1223 // There's no good way right now to look at the intermediate 1224 // expansions, so just jump to the expansion location. 1225 loc = getSourceManager().getExpansionLoc(loc); 1226 1227 // If that's written with the name, stop here. 1228 SmallVector<char, 16> buffer; 1229 if (getPreprocessor().getSpelling(loc, buffer) == name) { 1230 locref = loc; 1231 return true; 1232 } 1233 return false; 1234 } 1235 1236 /// \brief Determines the active Scope associated with the given declaration 1237 /// context. 1238 /// 1239 /// This routine maps a declaration context to the active Scope object that 1240 /// represents that declaration context in the parser. It is typically used 1241 /// from "scope-less" code (e.g., template instantiation, lazy creation of 1242 /// declarations) that injects a name for name-lookup purposes and, therefore, 1243 /// must update the Scope. 1244 /// 1245 /// \returns The scope corresponding to the given declaraion context, or NULL 1246 /// if no such scope is open. 1247 Scope *Sema::getScopeForContext(DeclContext *Ctx) { 1248 1249 if (!Ctx) 1250 return nullptr; 1251 1252 Ctx = Ctx->getPrimaryContext(); 1253 for (Scope *S = getCurScope(); S; S = S->getParent()) { 1254 // Ignore scopes that cannot have declarations. This is important for 1255 // out-of-line definitions of static class members. 1256 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) 1257 if (DeclContext *Entity = S->getEntity()) 1258 if (Ctx == Entity->getPrimaryContext()) 1259 return S; 1260 } 1261 1262 return nullptr; 1263 } 1264 1265 /// \brief Enter a new function scope 1266 void Sema::PushFunctionScope() { 1267 if (FunctionScopes.size() == 1) { 1268 // Use the "top" function scope rather than having to allocate 1269 // memory for a new scope. 1270 FunctionScopes.back()->Clear(); 1271 FunctionScopes.push_back(FunctionScopes.back()); 1272 if (LangOpts.OpenMP) 1273 pushOpenMPFunctionRegion(); 1274 return; 1275 } 1276 1277 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics())); 1278 if (LangOpts.OpenMP) 1279 pushOpenMPFunctionRegion(); 1280 } 1281 1282 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) { 1283 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(), 1284 BlockScope, Block)); 1285 } 1286 1287 LambdaScopeInfo *Sema::PushLambdaScope() { 1288 LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics()); 1289 FunctionScopes.push_back(LSI); 1290 return LSI; 1291 } 1292 1293 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) { 1294 if (LambdaScopeInfo *const LSI = getCurLambda()) { 1295 LSI->AutoTemplateParameterDepth = Depth; 1296 return; 1297 } 1298 llvm_unreachable( 1299 "Remove assertion if intentionally called in a non-lambda context."); 1300 } 1301 1302 void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP, 1303 const Decl *D, const BlockExpr *blkExpr) { 1304 FunctionScopeInfo *Scope = FunctionScopes.pop_back_val(); 1305 assert(!FunctionScopes.empty() && "mismatched push/pop!"); 1306 1307 if (LangOpts.OpenMP) 1308 popOpenMPFunctionRegion(Scope); 1309 1310 // Issue any analysis-based warnings. 1311 if (WP && D) 1312 AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr); 1313 else 1314 for (const auto &PUD : Scope->PossiblyUnreachableDiags) 1315 Diag(PUD.Loc, PUD.PD); 1316 1317 if (FunctionScopes.back() != Scope) 1318 delete Scope; 1319 } 1320 1321 void Sema::PushCompoundScope() { 1322 getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo()); 1323 } 1324 1325 void Sema::PopCompoundScope() { 1326 FunctionScopeInfo *CurFunction = getCurFunction(); 1327 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop"); 1328 1329 CurFunction->CompoundScopes.pop_back(); 1330 } 1331 1332 /// \brief Determine whether any errors occurred within this function/method/ 1333 /// block. 1334 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const { 1335 return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred(); 1336 } 1337 1338 BlockScopeInfo *Sema::getCurBlock() { 1339 if (FunctionScopes.empty()) 1340 return nullptr; 1341 1342 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back()); 1343 if (CurBSI && CurBSI->TheDecl && 1344 !CurBSI->TheDecl->Encloses(CurContext)) { 1345 // We have switched contexts due to template instantiation. 1346 assert(!CodeSynthesisContexts.empty()); 1347 return nullptr; 1348 } 1349 1350 return CurBSI; 1351 } 1352 1353 LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) { 1354 if (FunctionScopes.empty()) 1355 return nullptr; 1356 1357 auto I = FunctionScopes.rbegin(); 1358 if (IgnoreNonLambdaCapturingScope) { 1359 auto E = FunctionScopes.rend(); 1360 while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I)) 1361 ++I; 1362 if (I == E) 1363 return nullptr; 1364 } 1365 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I); 1366 if (CurLSI && CurLSI->Lambda && 1367 !CurLSI->Lambda->Encloses(CurContext)) { 1368 // We have switched contexts due to template instantiation. 1369 assert(!CodeSynthesisContexts.empty()); 1370 return nullptr; 1371 } 1372 1373 return CurLSI; 1374 } 1375 // We have a generic lambda if we parsed auto parameters, or we have 1376 // an associated template parameter list. 1377 LambdaScopeInfo *Sema::getCurGenericLambda() { 1378 if (LambdaScopeInfo *LSI = getCurLambda()) { 1379 return (LSI->AutoTemplateParams.size() || 1380 LSI->GLTemplateParameterList) ? LSI : nullptr; 1381 } 1382 return nullptr; 1383 } 1384 1385 1386 void Sema::ActOnComment(SourceRange Comment) { 1387 if (!LangOpts.RetainCommentsFromSystemHeaders && 1388 SourceMgr.isInSystemHeader(Comment.getBegin())) 1389 return; 1390 RawComment RC(SourceMgr, Comment, false, 1391 LangOpts.CommentOpts.ParseAllComments); 1392 if (RC.isAlmostTrailingComment()) { 1393 SourceRange MagicMarkerRange(Comment.getBegin(), 1394 Comment.getBegin().getLocWithOffset(3)); 1395 StringRef MagicMarkerText; 1396 switch (RC.getKind()) { 1397 case RawComment::RCK_OrdinaryBCPL: 1398 MagicMarkerText = "///<"; 1399 break; 1400 case RawComment::RCK_OrdinaryC: 1401 MagicMarkerText = "/**<"; 1402 break; 1403 default: 1404 llvm_unreachable("if this is an almost Doxygen comment, " 1405 "it should be ordinary"); 1406 } 1407 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) << 1408 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText); 1409 } 1410 Context.addComment(RC); 1411 } 1412 1413 // Pin this vtable to this file. 1414 ExternalSemaSource::~ExternalSemaSource() {} 1415 1416 void ExternalSemaSource::ReadMethodPool(Selector Sel) { } 1417 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { } 1418 1419 void ExternalSemaSource::ReadKnownNamespaces( 1420 SmallVectorImpl<NamespaceDecl *> &Namespaces) { 1421 } 1422 1423 void ExternalSemaSource::ReadUndefinedButUsed( 1424 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {} 1425 1426 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector< 1427 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {} 1428 1429 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const { 1430 SourceLocation Loc = this->Loc; 1431 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation(); 1432 if (Loc.isValid()) { 1433 Loc.print(OS, S.getSourceManager()); 1434 OS << ": "; 1435 } 1436 OS << Message; 1437 1438 if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) { 1439 OS << " '"; 1440 ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(), true); 1441 OS << "'"; 1442 } 1443 1444 OS << '\n'; 1445 } 1446 1447 /// \brief Figure out if an expression could be turned into a call. 1448 /// 1449 /// Use this when trying to recover from an error where the programmer may have 1450 /// written just the name of a function instead of actually calling it. 1451 /// 1452 /// \param E - The expression to examine. 1453 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call 1454 /// with no arguments, this parameter is set to the type returned by such a 1455 /// call; otherwise, it is set to an empty QualType. 1456 /// \param OverloadSet - If the expression is an overloaded function 1457 /// name, this parameter is populated with the decls of the various overloads. 1458 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, 1459 UnresolvedSetImpl &OverloadSet) { 1460 ZeroArgCallReturnTy = QualType(); 1461 OverloadSet.clear(); 1462 1463 const OverloadExpr *Overloads = nullptr; 1464 bool IsMemExpr = false; 1465 if (E.getType() == Context.OverloadTy) { 1466 OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E)); 1467 1468 // Ignore overloads that are pointer-to-member constants. 1469 if (FR.HasFormOfMemberPointer) 1470 return false; 1471 1472 Overloads = FR.Expression; 1473 } else if (E.getType() == Context.BoundMemberTy) { 1474 Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens()); 1475 IsMemExpr = true; 1476 } 1477 1478 bool Ambiguous = false; 1479 1480 if (Overloads) { 1481 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(), 1482 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) { 1483 OverloadSet.addDecl(*it); 1484 1485 // Check whether the function is a non-template, non-member which takes no 1486 // arguments. 1487 if (IsMemExpr) 1488 continue; 1489 if (const FunctionDecl *OverloadDecl 1490 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) { 1491 if (OverloadDecl->getMinRequiredArguments() == 0) { 1492 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) { 1493 ZeroArgCallReturnTy = QualType(); 1494 Ambiguous = true; 1495 } else 1496 ZeroArgCallReturnTy = OverloadDecl->getReturnType(); 1497 } 1498 } 1499 } 1500 1501 // If it's not a member, use better machinery to try to resolve the call 1502 if (!IsMemExpr) 1503 return !ZeroArgCallReturnTy.isNull(); 1504 } 1505 1506 // Attempt to call the member with no arguments - this will correctly handle 1507 // member templates with defaults/deduction of template arguments, overloads 1508 // with default arguments, etc. 1509 if (IsMemExpr && !E.isTypeDependent()) { 1510 bool Suppress = getDiagnostics().getSuppressAllDiagnostics(); 1511 getDiagnostics().setSuppressAllDiagnostics(true); 1512 ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(), 1513 None, SourceLocation()); 1514 getDiagnostics().setSuppressAllDiagnostics(Suppress); 1515 if (R.isUsable()) { 1516 ZeroArgCallReturnTy = R.get()->getType(); 1517 return true; 1518 } 1519 return false; 1520 } 1521 1522 if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) { 1523 if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) { 1524 if (Fun->getMinRequiredArguments() == 0) 1525 ZeroArgCallReturnTy = Fun->getReturnType(); 1526 return true; 1527 } 1528 } 1529 1530 // We don't have an expression that's convenient to get a FunctionDecl from, 1531 // but we can at least check if the type is "function of 0 arguments". 1532 QualType ExprTy = E.getType(); 1533 const FunctionType *FunTy = nullptr; 1534 QualType PointeeTy = ExprTy->getPointeeType(); 1535 if (!PointeeTy.isNull()) 1536 FunTy = PointeeTy->getAs<FunctionType>(); 1537 if (!FunTy) 1538 FunTy = ExprTy->getAs<FunctionType>(); 1539 1540 if (const FunctionProtoType *FPT = 1541 dyn_cast_or_null<FunctionProtoType>(FunTy)) { 1542 if (FPT->getNumParams() == 0) 1543 ZeroArgCallReturnTy = FunTy->getReturnType(); 1544 return true; 1545 } 1546 return false; 1547 } 1548 1549 /// \brief Give notes for a set of overloads. 1550 /// 1551 /// A companion to tryExprAsCall. In cases when the name that the programmer 1552 /// wrote was an overloaded function, we may be able to make some guesses about 1553 /// plausible overloads based on their return types; such guesses can be handed 1554 /// off to this method to be emitted as notes. 1555 /// 1556 /// \param Overloads - The overloads to note. 1557 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to 1558 /// -fshow-overloads=best, this is the location to attach to the note about too 1559 /// many candidates. Typically this will be the location of the original 1560 /// ill-formed expression. 1561 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, 1562 const SourceLocation FinalNoteLoc) { 1563 int ShownOverloads = 0; 1564 int SuppressedOverloads = 0; 1565 for (UnresolvedSetImpl::iterator It = Overloads.begin(), 1566 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 1567 // FIXME: Magic number for max shown overloads stolen from 1568 // OverloadCandidateSet::NoteCandidates. 1569 if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) { 1570 ++SuppressedOverloads; 1571 continue; 1572 } 1573 1574 NamedDecl *Fn = (*It)->getUnderlyingDecl(); 1575 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call); 1576 ++ShownOverloads; 1577 } 1578 1579 if (SuppressedOverloads) 1580 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates) 1581 << SuppressedOverloads; 1582 } 1583 1584 static void notePlausibleOverloads(Sema &S, SourceLocation Loc, 1585 const UnresolvedSetImpl &Overloads, 1586 bool (*IsPlausibleResult)(QualType)) { 1587 if (!IsPlausibleResult) 1588 return noteOverloads(S, Overloads, Loc); 1589 1590 UnresolvedSet<2> PlausibleOverloads; 1591 for (OverloadExpr::decls_iterator It = Overloads.begin(), 1592 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 1593 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It); 1594 QualType OverloadResultTy = OverloadDecl->getReturnType(); 1595 if (IsPlausibleResult(OverloadResultTy)) 1596 PlausibleOverloads.addDecl(It.getDecl()); 1597 } 1598 noteOverloads(S, PlausibleOverloads, Loc); 1599 } 1600 1601 /// Determine whether the given expression can be called by just 1602 /// putting parentheses after it. Notably, expressions with unary 1603 /// operators can't be because the unary operator will start parsing 1604 /// outside the call. 1605 static bool IsCallableWithAppend(Expr *E) { 1606 E = E->IgnoreImplicit(); 1607 return (!isa<CStyleCastExpr>(E) && 1608 !isa<UnaryOperator>(E) && 1609 !isa<BinaryOperator>(E) && 1610 !isa<CXXOperatorCallExpr>(E)); 1611 } 1612 1613 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 1614 bool ForceComplain, 1615 bool (*IsPlausibleResult)(QualType)) { 1616 SourceLocation Loc = E.get()->getExprLoc(); 1617 SourceRange Range = E.get()->getSourceRange(); 1618 1619 QualType ZeroArgCallTy; 1620 UnresolvedSet<4> Overloads; 1621 if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) && 1622 !ZeroArgCallTy.isNull() && 1623 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) { 1624 // At this point, we know E is potentially callable with 0 1625 // arguments and that it returns something of a reasonable type, 1626 // so we can emit a fixit and carry on pretending that E was 1627 // actually a CallExpr. 1628 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd()); 1629 Diag(Loc, PD) 1630 << /*zero-arg*/ 1 << Range 1631 << (IsCallableWithAppend(E.get()) 1632 ? FixItHint::CreateInsertion(ParenInsertionLoc, "()") 1633 : FixItHint()); 1634 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult); 1635 1636 // FIXME: Try this before emitting the fixit, and suppress diagnostics 1637 // while doing so. 1638 E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None, 1639 Range.getEnd().getLocWithOffset(1)); 1640 return true; 1641 } 1642 1643 if (!ForceComplain) return false; 1644 1645 Diag(Loc, PD) << /*not zero-arg*/ 0 << Range; 1646 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult); 1647 E = ExprError(); 1648 return true; 1649 } 1650 1651 IdentifierInfo *Sema::getSuperIdentifier() const { 1652 if (!Ident_super) 1653 Ident_super = &Context.Idents.get("super"); 1654 return Ident_super; 1655 } 1656 1657 IdentifierInfo *Sema::getFloat128Identifier() const { 1658 if (!Ident___float128) 1659 Ident___float128 = &Context.Idents.get("__float128"); 1660 return Ident___float128; 1661 } 1662 1663 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD, 1664 CapturedRegionKind K) { 1665 CapturingScopeInfo *CSI = new CapturedRegionScopeInfo( 1666 getDiagnostics(), S, CD, RD, CD->getContextParam(), K, 1667 (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0); 1668 CSI->ReturnType = Context.VoidTy; 1669 FunctionScopes.push_back(CSI); 1670 } 1671 1672 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() { 1673 if (FunctionScopes.empty()) 1674 return nullptr; 1675 1676 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back()); 1677 } 1678 1679 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> & 1680 Sema::getMismatchingDeleteExpressions() const { 1681 return DeleteExprs; 1682 } 1683 1684 void Sema::setOpenCLExtensionForType(QualType T, llvm::StringRef ExtStr) { 1685 if (ExtStr.empty()) 1686 return; 1687 llvm::SmallVector<StringRef, 1> Exts; 1688 ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false); 1689 auto CanT = T.getCanonicalType().getTypePtr(); 1690 for (auto &I : Exts) 1691 OpenCLTypeExtMap[CanT].insert(I.str()); 1692 } 1693 1694 void Sema::setOpenCLExtensionForDecl(Decl *FD, StringRef ExtStr) { 1695 llvm::SmallVector<StringRef, 1> Exts; 1696 ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false); 1697 if (Exts.empty()) 1698 return; 1699 for (auto &I : Exts) 1700 OpenCLDeclExtMap[FD].insert(I.str()); 1701 } 1702 1703 void Sema::setCurrentOpenCLExtensionForType(QualType T) { 1704 if (CurrOpenCLExtension.empty()) 1705 return; 1706 setOpenCLExtensionForType(T, CurrOpenCLExtension); 1707 } 1708 1709 void Sema::setCurrentOpenCLExtensionForDecl(Decl *D) { 1710 if (CurrOpenCLExtension.empty()) 1711 return; 1712 setOpenCLExtensionForDecl(D, CurrOpenCLExtension); 1713 } 1714 1715 bool Sema::isOpenCLDisabledDecl(Decl *FD) { 1716 auto Loc = OpenCLDeclExtMap.find(FD); 1717 if (Loc == OpenCLDeclExtMap.end()) 1718 return false; 1719 for (auto &I : Loc->second) { 1720 if (!getOpenCLOptions().isEnabled(I)) 1721 return true; 1722 } 1723 return false; 1724 } 1725 1726 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> 1727 bool Sema::checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, 1728 DiagInfoT DiagInfo, MapT &Map, 1729 unsigned Selector, 1730 SourceRange SrcRange) { 1731 auto Loc = Map.find(D); 1732 if (Loc == Map.end()) 1733 return false; 1734 bool Disabled = false; 1735 for (auto &I : Loc->second) { 1736 if (I != CurrOpenCLExtension && !getOpenCLOptions().isEnabled(I)) { 1737 Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo 1738 << I << SrcRange; 1739 Disabled = true; 1740 } 1741 } 1742 return Disabled; 1743 } 1744 1745 bool Sema::checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType QT) { 1746 // Check extensions for declared types. 1747 Decl *Decl = nullptr; 1748 if (auto TypedefT = dyn_cast<TypedefType>(QT.getTypePtr())) 1749 Decl = TypedefT->getDecl(); 1750 if (auto TagT = dyn_cast<TagType>(QT.getCanonicalType().getTypePtr())) 1751 Decl = TagT->getDecl(); 1752 auto Loc = DS.getTypeSpecTypeLoc(); 1753 if (checkOpenCLDisabledTypeOrDecl(Decl, Loc, QT, OpenCLDeclExtMap)) 1754 return true; 1755 1756 // Check extensions for builtin types. 1757 return checkOpenCLDisabledTypeOrDecl(QT.getCanonicalType().getTypePtr(), Loc, 1758 QT, OpenCLTypeExtMap); 1759 } 1760 1761 bool Sema::checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E) { 1762 IdentifierInfo *FnName = D.getIdentifier(); 1763 return checkOpenCLDisabledTypeOrDecl(&D, E.getLocStart(), FnName, 1764 OpenCLDeclExtMap, 1, D.getSourceRange()); 1765 } 1766