1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the actions class which performs semantic analysis and 10 // builds an AST out of a parse stream. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "UsedDeclVisitor.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTDiagnostic.h" 17 #include "clang/AST/Decl.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclFriend.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/PrettyDeclStackTrace.h" 24 #include "clang/AST/StmtCXX.h" 25 #include "clang/Basic/DarwinSDKInfo.h" 26 #include "clang/Basic/DiagnosticOptions.h" 27 #include "clang/Basic/PartialDiagnostic.h" 28 #include "clang/Basic/SourceManager.h" 29 #include "clang/Basic/Stack.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" 32 #include "clang/Lex/HeaderSearchOptions.h" 33 #include "clang/Lex/Preprocessor.h" 34 #include "clang/Sema/CXXFieldCollector.h" 35 #include "clang/Sema/DelayedDiagnostic.h" 36 #include "clang/Sema/ExternalSemaSource.h" 37 #include "clang/Sema/Initialization.h" 38 #include "clang/Sema/MultiplexExternalSemaSource.h" 39 #include "clang/Sema/ObjCMethodList.h" 40 #include "clang/Sema/Scope.h" 41 #include "clang/Sema/ScopeInfo.h" 42 #include "clang/Sema/SemaConsumer.h" 43 #include "clang/Sema/SemaInternal.h" 44 #include "clang/Sema/TemplateDeduction.h" 45 #include "clang/Sema/TemplateInstCallback.h" 46 #include "clang/Sema/TypoCorrection.h" 47 #include "llvm/ADT/DenseMap.h" 48 #include "llvm/ADT/SmallPtrSet.h" 49 #include "llvm/Support/TimeProfiler.h" 50 51 using namespace clang; 52 using namespace sema; 53 54 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) { 55 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts); 56 } 57 58 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); } 59 60 DarwinSDKInfo * 61 Sema::getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc, 62 StringRef Platform) { 63 if (CachedDarwinSDKInfo) 64 return CachedDarwinSDKInfo->get(); 65 auto SDKInfo = parseDarwinSDKInfo( 66 PP.getFileManager().getVirtualFileSystem(), 67 PP.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot); 68 if (SDKInfo && *SDKInfo) { 69 CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(std::move(**SDKInfo)); 70 return CachedDarwinSDKInfo->get(); 71 } 72 if (!SDKInfo) 73 llvm::consumeError(SDKInfo.takeError()); 74 Diag(Loc, diag::warn_missing_sdksettings_for_availability_checking) 75 << Platform; 76 CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>(); 77 return nullptr; 78 } 79 80 IdentifierInfo * 81 Sema::InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, 82 unsigned int Index) { 83 std::string InventedName; 84 llvm::raw_string_ostream OS(InventedName); 85 86 if (!ParamName) 87 OS << "auto:" << Index + 1; 88 else 89 OS << ParamName->getName() << ":auto"; 90 91 OS.flush(); 92 return &Context.Idents.get(OS.str()); 93 } 94 95 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context, 96 const Preprocessor &PP) { 97 PrintingPolicy Policy = Context.getPrintingPolicy(); 98 // In diagnostics, we print _Bool as bool if the latter is defined as the 99 // former. 100 Policy.Bool = Context.getLangOpts().Bool; 101 if (!Policy.Bool) { 102 if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) { 103 Policy.Bool = BoolMacro->isObjectLike() && 104 BoolMacro->getNumTokens() == 1 && 105 BoolMacro->getReplacementToken(0).is(tok::kw__Bool); 106 } 107 } 108 109 return Policy; 110 } 111 112 void Sema::ActOnTranslationUnitScope(Scope *S) { 113 TUScope = S; 114 PushDeclContext(S, Context.getTranslationUnitDecl()); 115 } 116 117 namespace clang { 118 namespace sema { 119 120 class SemaPPCallbacks : public PPCallbacks { 121 Sema *S = nullptr; 122 llvm::SmallVector<SourceLocation, 8> IncludeStack; 123 124 public: 125 void set(Sema &S) { this->S = &S; } 126 127 void reset() { S = nullptr; } 128 129 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason, 130 SrcMgr::CharacteristicKind FileType, 131 FileID PrevFID) override { 132 if (!S) 133 return; 134 switch (Reason) { 135 case EnterFile: { 136 SourceManager &SM = S->getSourceManager(); 137 SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc)); 138 if (IncludeLoc.isValid()) { 139 if (llvm::timeTraceProfilerEnabled()) { 140 const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc)); 141 llvm::timeTraceProfilerBegin( 142 "Source", FE != nullptr ? FE->getName() : StringRef("<unknown>")); 143 } 144 145 IncludeStack.push_back(IncludeLoc); 146 S->DiagnoseNonDefaultPragmaAlignPack( 147 Sema::PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude, 148 IncludeLoc); 149 } 150 break; 151 } 152 case ExitFile: 153 if (!IncludeStack.empty()) { 154 if (llvm::timeTraceProfilerEnabled()) 155 llvm::timeTraceProfilerEnd(); 156 157 S->DiagnoseNonDefaultPragmaAlignPack( 158 Sema::PragmaAlignPackDiagnoseKind::ChangedStateAtExit, 159 IncludeStack.pop_back_val()); 160 } 161 break; 162 default: 163 break; 164 } 165 } 166 }; 167 168 } // end namespace sema 169 } // end namespace clang 170 171 const unsigned Sema::MaxAlignmentExponent; 172 const unsigned Sema::MaximumAlignment; 173 174 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 175 TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter) 176 : ExternalSource(nullptr), isMultiplexExternalSource(false), 177 CurFPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp), 178 Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()), 179 SourceMgr(PP.getSourceManager()), CollectStats(false), 180 CodeCompleter(CodeCompleter), CurContext(nullptr), 181 OriginalLexicalContext(nullptr), MSStructPragmaOn(false), 182 MSPointerToMemberRepresentationMethod( 183 LangOpts.getMSPointerToMemberRepresentationMethod()), 184 VtorDispStack(LangOpts.getVtorDispMode()), 185 AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)), 186 DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr), 187 CodeSegStack(nullptr), FpPragmaStack(FPOptionsOverride()), 188 CurInitSeg(nullptr), VisContext(nullptr), 189 PragmaAttributeCurrentTargetDecl(nullptr), 190 IsBuildingRecoveryCallExpr(false), Cleanup{}, LateTemplateParser(nullptr), 191 LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp), 192 StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr), 193 StdCoroutineTraitsCache(nullptr), CXXTypeInfoDecl(nullptr), 194 MSVCGuidDecl(nullptr), NSNumberDecl(nullptr), NSValueDecl(nullptr), 195 NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr), 196 ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr), 197 ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr), 198 DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false), 199 TUKind(TUKind), NumSFINAEErrors(0), 200 FullyCheckedComparisonCategories( 201 static_cast<unsigned>(ComparisonCategoryType::Last) + 1), 202 SatisfactionCache(Context), AccessCheckingSFINAE(false), 203 InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0), 204 ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr), 205 DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this), 206 ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr), 207 CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) { 208 assert(pp.TUKind == TUKind); 209 TUScope = nullptr; 210 isConstantEvaluatedOverride = false; 211 212 LoadedExternalKnownNamespaces = false; 213 for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I) 214 NSNumberLiteralMethods[I] = nullptr; 215 216 if (getLangOpts().ObjC) 217 NSAPIObj.reset(new NSAPI(Context)); 218 219 if (getLangOpts().CPlusPlus) 220 FieldCollector.reset(new CXXFieldCollector()); 221 222 // Tell diagnostics how to render things from the AST library. 223 Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context); 224 225 ExprEvalContexts.emplace_back( 226 ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{}, 227 nullptr, ExpressionEvaluationContextRecord::EK_Other); 228 229 // Initialization of data sharing attributes stack for OpenMP 230 InitDataSharingAttributesStack(); 231 232 std::unique_ptr<sema::SemaPPCallbacks> Callbacks = 233 std::make_unique<sema::SemaPPCallbacks>(); 234 SemaPPCallbackHandler = Callbacks.get(); 235 PP.addPPCallbacks(std::move(Callbacks)); 236 SemaPPCallbackHandler->set(*this); 237 if (getLangOpts().getFPEvalMethod() == LangOptions::FEM_TargetDefault) 238 // Use setting from TargetInfo. 239 PP.setCurrentFPEvalMethod(ctxt.getTargetInfo().getFPEvalMethod()); 240 else 241 // Set initial value of __FLT_EVAL_METHOD__ from the command line. 242 PP.setCurrentFPEvalMethod(getLangOpts().getFPEvalMethod()); 243 } 244 245 // Anchor Sema's type info to this TU. 246 void Sema::anchor() {} 247 248 void Sema::addImplicitTypedef(StringRef Name, QualType T) { 249 DeclarationName DN = &Context.Idents.get(Name); 250 if (IdResolver.begin(DN) == IdResolver.end()) 251 PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope); 252 } 253 254 void Sema::Initialize() { 255 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 256 SC->InitializeSema(*this); 257 258 // Tell the external Sema source about this Sema object. 259 if (ExternalSemaSource *ExternalSema 260 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 261 ExternalSema->InitializeSema(*this); 262 263 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we 264 // will not be able to merge any duplicate __va_list_tag decls correctly. 265 VAListTagName = PP.getIdentifierInfo("__va_list_tag"); 266 267 if (!TUScope) 268 return; 269 270 // Initialize predefined 128-bit integer types, if needed. 271 if (Context.getTargetInfo().hasInt128Type() || 272 (Context.getAuxTargetInfo() && 273 Context.getAuxTargetInfo()->hasInt128Type())) { 274 // If either of the 128-bit integer types are unavailable to name lookup, 275 // define them now. 276 DeclarationName Int128 = &Context.Idents.get("__int128_t"); 277 if (IdResolver.begin(Int128) == IdResolver.end()) 278 PushOnScopeChains(Context.getInt128Decl(), TUScope); 279 280 DeclarationName UInt128 = &Context.Idents.get("__uint128_t"); 281 if (IdResolver.begin(UInt128) == IdResolver.end()) 282 PushOnScopeChains(Context.getUInt128Decl(), TUScope); 283 } 284 285 286 // Initialize predefined Objective-C types: 287 if (getLangOpts().ObjC) { 288 // If 'SEL' does not yet refer to any declarations, make it refer to the 289 // predefined 'SEL'. 290 DeclarationName SEL = &Context.Idents.get("SEL"); 291 if (IdResolver.begin(SEL) == IdResolver.end()) 292 PushOnScopeChains(Context.getObjCSelDecl(), TUScope); 293 294 // If 'id' does not yet refer to any declarations, make it refer to the 295 // predefined 'id'. 296 DeclarationName Id = &Context.Idents.get("id"); 297 if (IdResolver.begin(Id) == IdResolver.end()) 298 PushOnScopeChains(Context.getObjCIdDecl(), TUScope); 299 300 // Create the built-in typedef for 'Class'. 301 DeclarationName Class = &Context.Idents.get("Class"); 302 if (IdResolver.begin(Class) == IdResolver.end()) 303 PushOnScopeChains(Context.getObjCClassDecl(), TUScope); 304 305 // Create the built-in forward declaratino for 'Protocol'. 306 DeclarationName Protocol = &Context.Idents.get("Protocol"); 307 if (IdResolver.begin(Protocol) == IdResolver.end()) 308 PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope); 309 } 310 311 // Create the internal type for the *StringMakeConstantString builtins. 312 DeclarationName ConstantString = &Context.Idents.get("__NSConstantString"); 313 if (IdResolver.begin(ConstantString) == IdResolver.end()) 314 PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope); 315 316 // Initialize Microsoft "predefined C++ types". 317 if (getLangOpts().MSVCCompat) { 318 if (getLangOpts().CPlusPlus && 319 IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end()) 320 PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class), 321 TUScope); 322 323 addImplicitTypedef("size_t", Context.getSizeType()); 324 } 325 326 // Initialize predefined OpenCL types and supported extensions and (optional) 327 // core features. 328 if (getLangOpts().OpenCL) { 329 getOpenCLOptions().addSupport( 330 Context.getTargetInfo().getSupportedOpenCLOpts(), getLangOpts()); 331 addImplicitTypedef("sampler_t", Context.OCLSamplerTy); 332 addImplicitTypedef("event_t", Context.OCLEventTy); 333 if (getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) { 334 addImplicitTypedef("clk_event_t", Context.OCLClkEventTy); 335 addImplicitTypedef("queue_t", Context.OCLQueueTy); 336 if (getLangOpts().OpenCLPipes) 337 addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy); 338 addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy)); 339 addImplicitTypedef("atomic_uint", 340 Context.getAtomicType(Context.UnsignedIntTy)); 341 addImplicitTypedef("atomic_float", 342 Context.getAtomicType(Context.FloatTy)); 343 // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as 344 // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide. 345 addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy)); 346 347 348 // OpenCL v2.0 s6.13.11.6: 349 // - The atomic_long and atomic_ulong types are supported if the 350 // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics 351 // extensions are supported. 352 // - The atomic_double type is only supported if double precision 353 // is supported and the cl_khr_int64_base_atomics and 354 // cl_khr_int64_extended_atomics extensions are supported. 355 // - If the device address space is 64-bits, the data types 356 // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and 357 // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and 358 // cl_khr_int64_extended_atomics extensions are supported. 359 360 auto AddPointerSizeDependentTypes = [&]() { 361 auto AtomicSizeT = Context.getAtomicType(Context.getSizeType()); 362 auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType()); 363 auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType()); 364 auto AtomicPtrDiffT = 365 Context.getAtomicType(Context.getPointerDiffType()); 366 addImplicitTypedef("atomic_size_t", AtomicSizeT); 367 addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT); 368 addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT); 369 addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT); 370 }; 371 372 if (Context.getTypeSize(Context.getSizeType()) == 32) { 373 AddPointerSizeDependentTypes(); 374 } 375 376 std::vector<QualType> Atomic64BitTypes; 377 if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics", 378 getLangOpts()) && 379 getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics", 380 getLangOpts())) { 381 if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) { 382 auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy); 383 addImplicitTypedef("atomic_double", AtomicDoubleT); 384 Atomic64BitTypes.push_back(AtomicDoubleT); 385 } 386 auto AtomicLongT = Context.getAtomicType(Context.LongTy); 387 auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy); 388 addImplicitTypedef("atomic_long", AtomicLongT); 389 addImplicitTypedef("atomic_ulong", AtomicULongT); 390 391 392 if (Context.getTypeSize(Context.getSizeType()) == 64) { 393 AddPointerSizeDependentTypes(); 394 } 395 } 396 } 397 398 399 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 400 if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) { \ 401 addImplicitTypedef(#ExtType, Context.Id##Ty); \ 402 } 403 #include "clang/Basic/OpenCLExtensionTypes.def" 404 } 405 406 if (Context.getTargetInfo().hasAArch64SVETypes()) { 407 #define SVE_TYPE(Name, Id, SingletonId) \ 408 addImplicitTypedef(Name, Context.SingletonId); 409 #include "clang/Basic/AArch64SVEACLETypes.def" 410 } 411 412 if (Context.getTargetInfo().getTriple().isPPC64() && 413 Context.getTargetInfo().hasFeature("paired-vector-memops")) { 414 if (Context.getTargetInfo().hasFeature("mma")) { 415 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \ 416 addImplicitTypedef(#Name, Context.Id##Ty); 417 #include "clang/Basic/PPCTypes.def" 418 } 419 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \ 420 addImplicitTypedef(#Name, Context.Id##Ty); 421 #include "clang/Basic/PPCTypes.def" 422 } 423 424 if (Context.getTargetInfo().hasRISCVVTypes()) { 425 #define RVV_TYPE(Name, Id, SingletonId) \ 426 addImplicitTypedef(Name, Context.SingletonId); 427 #include "clang/Basic/RISCVVTypes.def" 428 } 429 430 if (Context.getTargetInfo().hasBuiltinMSVaList()) { 431 DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list"); 432 if (IdResolver.begin(MSVaList) == IdResolver.end()) 433 PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope); 434 } 435 436 DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list"); 437 if (IdResolver.begin(BuiltinVaList) == IdResolver.end()) 438 PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope); 439 } 440 441 Sema::~Sema() { 442 assert(InstantiatingSpecializations.empty() && 443 "failed to clean up an InstantiatingTemplate?"); 444 445 if (VisContext) FreeVisContext(); 446 447 // Kill all the active scopes. 448 for (sema::FunctionScopeInfo *FSI : FunctionScopes) 449 delete FSI; 450 451 // Tell the SemaConsumer to forget about us; we're going out of scope. 452 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer)) 453 SC->ForgetSema(); 454 455 // Detach from the external Sema source. 456 if (ExternalSemaSource *ExternalSema 457 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource())) 458 ExternalSema->ForgetSema(); 459 460 // If Sema's ExternalSource is the multiplexer - we own it. 461 if (isMultiplexExternalSource) 462 delete ExternalSource; 463 464 // Delete cached satisfactions. 465 std::vector<ConstraintSatisfaction *> Satisfactions; 466 Satisfactions.reserve(Satisfactions.size()); 467 for (auto &Node : SatisfactionCache) 468 Satisfactions.push_back(&Node); 469 for (auto *Node : Satisfactions) 470 delete Node; 471 472 threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache); 473 474 // Destroys data sharing attributes stack for OpenMP 475 DestroyDataSharingAttributesStack(); 476 477 // Detach from the PP callback handler which outlives Sema since it's owned 478 // by the preprocessor. 479 SemaPPCallbackHandler->reset(); 480 } 481 482 void Sema::warnStackExhausted(SourceLocation Loc) { 483 // Only warn about this once. 484 if (!WarnedStackExhausted) { 485 Diag(Loc, diag::warn_stack_exhausted); 486 WarnedStackExhausted = true; 487 } 488 } 489 490 void Sema::runWithSufficientStackSpace(SourceLocation Loc, 491 llvm::function_ref<void()> Fn) { 492 clang::runWithSufficientStackSpace([&] { warnStackExhausted(Loc); }, Fn); 493 } 494 495 /// makeUnavailableInSystemHeader - There is an error in the current 496 /// context. If we're still in a system header, and we can plausibly 497 /// make the relevant declaration unavailable instead of erroring, do 498 /// so and return true. 499 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc, 500 UnavailableAttr::ImplicitReason reason) { 501 // If we're not in a function, it's an error. 502 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext); 503 if (!fn) return false; 504 505 // If we're in template instantiation, it's an error. 506 if (inTemplateInstantiation()) 507 return false; 508 509 // If that function's not in a system header, it's an error. 510 if (!Context.getSourceManager().isInSystemHeader(loc)) 511 return false; 512 513 // If the function is already unavailable, it's not an error. 514 if (fn->hasAttr<UnavailableAttr>()) return true; 515 516 fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc)); 517 return true; 518 } 519 520 ASTMutationListener *Sema::getASTMutationListener() const { 521 return getASTConsumer().GetASTMutationListener(); 522 } 523 524 ///Registers an external source. If an external source already exists, 525 /// creates a multiplex external source and appends to it. 526 /// 527 ///\param[in] E - A non-null external sema source. 528 /// 529 void Sema::addExternalSource(ExternalSemaSource *E) { 530 assert(E && "Cannot use with NULL ptr"); 531 532 if (!ExternalSource) { 533 ExternalSource = E; 534 return; 535 } 536 537 if (isMultiplexExternalSource) 538 static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E); 539 else { 540 ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E); 541 isMultiplexExternalSource = true; 542 } 543 } 544 545 /// Print out statistics about the semantic analysis. 546 void Sema::PrintStats() const { 547 llvm::errs() << "\n*** Semantic Analysis Stats:\n"; 548 llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n"; 549 550 BumpAlloc.PrintStats(); 551 AnalysisWarnings.PrintStats(); 552 } 553 554 void Sema::diagnoseNullableToNonnullConversion(QualType DstType, 555 QualType SrcType, 556 SourceLocation Loc) { 557 Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context); 558 if (!ExprNullability || (*ExprNullability != NullabilityKind::Nullable && 559 *ExprNullability != NullabilityKind::NullableResult)) 560 return; 561 562 Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context); 563 if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull) 564 return; 565 566 Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType; 567 } 568 569 void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) { 570 if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant, 571 E->getBeginLoc())) 572 return; 573 // nullptr only exists from C++11 on, so don't warn on its absence earlier. 574 if (!getLangOpts().CPlusPlus11) 575 return; 576 577 if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer) 578 return; 579 if (E->IgnoreParenImpCasts()->getType()->isNullPtrType()) 580 return; 581 582 // Don't diagnose the conversion from a 0 literal to a null pointer argument 583 // in a synthesized call to operator<=>. 584 if (!CodeSynthesisContexts.empty() && 585 CodeSynthesisContexts.back().Kind == 586 CodeSynthesisContext::RewritingOperatorAsSpaceship) 587 return; 588 589 // If it is a macro from system header, and if the macro name is not "NULL", 590 // do not warn. 591 SourceLocation MaybeMacroLoc = E->getBeginLoc(); 592 if (Diags.getSuppressSystemWarnings() && 593 SourceMgr.isInSystemMacro(MaybeMacroLoc) && 594 !findMacroSpelling(MaybeMacroLoc, "NULL")) 595 return; 596 597 Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant) 598 << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr"); 599 } 600 601 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast. 602 /// If there is already an implicit cast, merge into the existing one. 603 /// The result is of the given category. 604 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty, 605 CastKind Kind, ExprValueKind VK, 606 const CXXCastPath *BasePath, 607 CheckedConversionKind CCK) { 608 #ifndef NDEBUG 609 if (VK == VK_PRValue && !E->isPRValue()) { 610 switch (Kind) { 611 default: 612 llvm_unreachable( 613 ("can't implicitly cast glvalue to prvalue with this cast " 614 "kind: " + 615 std::string(CastExpr::getCastKindName(Kind))) 616 .c_str()); 617 case CK_Dependent: 618 case CK_LValueToRValue: 619 case CK_ArrayToPointerDecay: 620 case CK_FunctionToPointerDecay: 621 case CK_ToVoid: 622 case CK_NonAtomicToAtomic: 623 break; 624 } 625 } 626 assert((VK == VK_PRValue || Kind == CK_Dependent || !E->isPRValue()) && 627 "can't cast prvalue to glvalue"); 628 #endif 629 630 diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc()); 631 diagnoseZeroToNullptrConversion(Kind, E); 632 633 QualType ExprTy = Context.getCanonicalType(E->getType()); 634 QualType TypeTy = Context.getCanonicalType(Ty); 635 636 if (ExprTy == TypeTy) 637 return E; 638 639 if (Kind == CK_ArrayToPointerDecay) { 640 // C++1z [conv.array]: The temporary materialization conversion is applied. 641 // We also use this to fuel C++ DR1213, which applies to C++11 onwards. 642 if (getLangOpts().CPlusPlus && E->isPRValue()) { 643 // The temporary is an lvalue in C++98 and an xvalue otherwise. 644 ExprResult Materialized = CreateMaterializeTemporaryExpr( 645 E->getType(), E, !getLangOpts().CPlusPlus11); 646 if (Materialized.isInvalid()) 647 return ExprError(); 648 E = Materialized.get(); 649 } 650 // C17 6.7.1p6 footnote 124: The implementation can treat any register 651 // declaration simply as an auto declaration. However, whether or not 652 // addressable storage is actually used, the address of any part of an 653 // object declared with storage-class specifier register cannot be 654 // computed, either explicitly(by use of the unary & operator as discussed 655 // in 6.5.3.2) or implicitly(by converting an array name to a pointer as 656 // discussed in 6.3.2.1).Thus, the only operator that can be applied to an 657 // array declared with storage-class specifier register is sizeof. 658 if (VK == VK_PRValue && !getLangOpts().CPlusPlus && !E->isPRValue()) { 659 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) { 660 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 661 if (VD->getStorageClass() == SC_Register) { 662 Diag(E->getExprLoc(), diag::err_typecheck_address_of) 663 << /*register variable*/ 3 << E->getSourceRange(); 664 return ExprError(); 665 } 666 } 667 } 668 } 669 } 670 671 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) { 672 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) { 673 ImpCast->setType(Ty); 674 ImpCast->setValueKind(VK); 675 return E; 676 } 677 } 678 679 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK, 680 CurFPFeatureOverrides()); 681 } 682 683 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 684 /// to the conversion from scalar type ScalarTy to the Boolean type. 685 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) { 686 switch (ScalarTy->getScalarTypeKind()) { 687 case Type::STK_Bool: return CK_NoOp; 688 case Type::STK_CPointer: return CK_PointerToBoolean; 689 case Type::STK_BlockPointer: return CK_PointerToBoolean; 690 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean; 691 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean; 692 case Type::STK_Integral: return CK_IntegralToBoolean; 693 case Type::STK_Floating: return CK_FloatingToBoolean; 694 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean; 695 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean; 696 case Type::STK_FixedPoint: return CK_FixedPointToBoolean; 697 } 698 llvm_unreachable("unknown scalar type kind"); 699 } 700 701 /// Used to prune the decls of Sema's UnusedFileScopedDecls vector. 702 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) { 703 if (D->getMostRecentDecl()->isUsed()) 704 return true; 705 706 if (D->isExternallyVisible()) 707 return true; 708 709 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 710 // If this is a function template and none of its specializations is used, 711 // we should warn. 712 if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate()) 713 for (const auto *Spec : Template->specializations()) 714 if (ShouldRemoveFromUnused(SemaRef, Spec)) 715 return true; 716 717 // UnusedFileScopedDecls stores the first declaration. 718 // The declaration may have become definition so check again. 719 const FunctionDecl *DeclToCheck; 720 if (FD->hasBody(DeclToCheck)) 721 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 722 723 // Later redecls may add new information resulting in not having to warn, 724 // so check again. 725 DeclToCheck = FD->getMostRecentDecl(); 726 if (DeclToCheck != FD) 727 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 728 } 729 730 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 731 // If a variable usable in constant expressions is referenced, 732 // don't warn if it isn't used: if the value of a variable is required 733 // for the computation of a constant expression, it doesn't make sense to 734 // warn even if the variable isn't odr-used. (isReferenced doesn't 735 // precisely reflect that, but it's a decent approximation.) 736 if (VD->isReferenced() && 737 VD->mightBeUsableInConstantExpressions(SemaRef->Context)) 738 return true; 739 740 if (VarTemplateDecl *Template = VD->getDescribedVarTemplate()) 741 // If this is a variable template and none of its specializations is used, 742 // we should warn. 743 for (const auto *Spec : Template->specializations()) 744 if (ShouldRemoveFromUnused(SemaRef, Spec)) 745 return true; 746 747 // UnusedFileScopedDecls stores the first declaration. 748 // The declaration may have become definition so check again. 749 const VarDecl *DeclToCheck = VD->getDefinition(); 750 if (DeclToCheck) 751 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 752 753 // Later redecls may add new information resulting in not having to warn, 754 // so check again. 755 DeclToCheck = VD->getMostRecentDecl(); 756 if (DeclToCheck != VD) 757 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck); 758 } 759 760 return false; 761 } 762 763 static bool isFunctionOrVarDeclExternC(NamedDecl *ND) { 764 if (auto *FD = dyn_cast<FunctionDecl>(ND)) 765 return FD->isExternC(); 766 return cast<VarDecl>(ND)->isExternC(); 767 } 768 769 /// Determine whether ND is an external-linkage function or variable whose 770 /// type has no linkage. 771 bool Sema::isExternalWithNoLinkageType(ValueDecl *VD) { 772 // Note: it's not quite enough to check whether VD has UniqueExternalLinkage, 773 // because we also want to catch the case where its type has VisibleNoLinkage, 774 // which does not affect the linkage of VD. 775 return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() && 776 !isExternalFormalLinkage(VD->getType()->getLinkage()) && 777 !isFunctionOrVarDeclExternC(VD); 778 } 779 780 /// Obtains a sorted list of functions and variables that are undefined but 781 /// ODR-used. 782 void Sema::getUndefinedButUsed( 783 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) { 784 for (const auto &UndefinedUse : UndefinedButUsed) { 785 NamedDecl *ND = UndefinedUse.first; 786 787 // Ignore attributes that have become invalid. 788 if (ND->isInvalidDecl()) continue; 789 790 // __attribute__((weakref)) is basically a definition. 791 if (ND->hasAttr<WeakRefAttr>()) continue; 792 793 if (isa<CXXDeductionGuideDecl>(ND)) 794 continue; 795 796 if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) { 797 // An exported function will always be emitted when defined, so even if 798 // the function is inline, it doesn't have to be emitted in this TU. An 799 // imported function implies that it has been exported somewhere else. 800 continue; 801 } 802 803 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 804 if (FD->isDefined()) 805 continue; 806 if (FD->isExternallyVisible() && 807 !isExternalWithNoLinkageType(FD) && 808 !FD->getMostRecentDecl()->isInlined() && 809 !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>()) 810 continue; 811 if (FD->getBuiltinID()) 812 continue; 813 } else { 814 auto *VD = cast<VarDecl>(ND); 815 if (VD->hasDefinition() != VarDecl::DeclarationOnly) 816 continue; 817 if (VD->isExternallyVisible() && 818 !isExternalWithNoLinkageType(VD) && 819 !VD->getMostRecentDecl()->isInline() && 820 !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>()) 821 continue; 822 823 // Skip VarDecls that lack formal definitions but which we know are in 824 // fact defined somewhere. 825 if (VD->isKnownToBeDefined()) 826 continue; 827 } 828 829 Undefined.push_back(std::make_pair(ND, UndefinedUse.second)); 830 } 831 } 832 833 /// checkUndefinedButUsed - Check for undefined objects with internal linkage 834 /// or that are inline. 835 static void checkUndefinedButUsed(Sema &S) { 836 if (S.UndefinedButUsed.empty()) return; 837 838 // Collect all the still-undefined entities with internal linkage. 839 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined; 840 S.getUndefinedButUsed(Undefined); 841 if (Undefined.empty()) return; 842 843 for (auto Undef : Undefined) { 844 ValueDecl *VD = cast<ValueDecl>(Undef.first); 845 SourceLocation UseLoc = Undef.second; 846 847 if (S.isExternalWithNoLinkageType(VD)) { 848 // C++ [basic.link]p8: 849 // A type without linkage shall not be used as the type of a variable 850 // or function with external linkage unless 851 // -- the entity has C language linkage 852 // -- the entity is not odr-used or is defined in the same TU 853 // 854 // As an extension, accept this in cases where the type is externally 855 // visible, since the function or variable actually can be defined in 856 // another translation unit in that case. 857 S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage()) 858 ? diag::ext_undefined_internal_type 859 : diag::err_undefined_internal_type) 860 << isa<VarDecl>(VD) << VD; 861 } else if (!VD->isExternallyVisible()) { 862 // FIXME: We can promote this to an error. The function or variable can't 863 // be defined anywhere else, so the program must necessarily violate the 864 // one definition rule. 865 bool IsImplicitBase = false; 866 if (const auto *BaseD = dyn_cast<FunctionDecl>(VD)) { 867 auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>(); 868 if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive( 869 llvm::omp::TraitProperty:: 870 implementation_extension_disable_implicit_base)) { 871 const auto *Func = cast<FunctionDecl>( 872 cast<DeclRefExpr>(DVAttr->getVariantFuncRef())->getDecl()); 873 IsImplicitBase = BaseD->isImplicit() && 874 Func->getIdentifier()->isMangledOpenMPVariantName(); 875 } 876 } 877 if (!S.getLangOpts().OpenMP || !IsImplicitBase) 878 S.Diag(VD->getLocation(), diag::warn_undefined_internal) 879 << isa<VarDecl>(VD) << VD; 880 } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) { 881 (void)FD; 882 assert(FD->getMostRecentDecl()->isInlined() && 883 "used object requires definition but isn't inline or internal?"); 884 // FIXME: This is ill-formed; we should reject. 885 S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD; 886 } else { 887 assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() && 888 "used var requires definition but isn't inline or internal?"); 889 S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD; 890 } 891 if (UseLoc.isValid()) 892 S.Diag(UseLoc, diag::note_used_here); 893 } 894 895 S.UndefinedButUsed.clear(); 896 } 897 898 void Sema::LoadExternalWeakUndeclaredIdentifiers() { 899 if (!ExternalSource) 900 return; 901 902 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs; 903 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs); 904 for (auto &WeakID : WeakIDs) 905 WeakUndeclaredIdentifiers.insert(WeakID); 906 } 907 908 909 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap; 910 911 /// Returns true, if all methods and nested classes of the given 912 /// CXXRecordDecl are defined in this translation unit. 913 /// 914 /// Should only be called from ActOnEndOfTranslationUnit so that all 915 /// definitions are actually read. 916 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD, 917 RecordCompleteMap &MNCComplete) { 918 RecordCompleteMap::iterator Cache = MNCComplete.find(RD); 919 if (Cache != MNCComplete.end()) 920 return Cache->second; 921 if (!RD->isCompleteDefinition()) 922 return false; 923 bool Complete = true; 924 for (DeclContext::decl_iterator I = RD->decls_begin(), 925 E = RD->decls_end(); 926 I != E && Complete; ++I) { 927 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I)) 928 Complete = M->isDefined() || M->isDefaulted() || 929 (M->isPure() && !isa<CXXDestructorDecl>(M)); 930 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I)) 931 // If the template function is marked as late template parsed at this 932 // point, it has not been instantiated and therefore we have not 933 // performed semantic analysis on it yet, so we cannot know if the type 934 // can be considered complete. 935 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() && 936 F->getTemplatedDecl()->isDefined(); 937 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) { 938 if (R->isInjectedClassName()) 939 continue; 940 if (R->hasDefinition()) 941 Complete = MethodsAndNestedClassesComplete(R->getDefinition(), 942 MNCComplete); 943 else 944 Complete = false; 945 } 946 } 947 MNCComplete[RD] = Complete; 948 return Complete; 949 } 950 951 /// Returns true, if the given CXXRecordDecl is fully defined in this 952 /// translation unit, i.e. all methods are defined or pure virtual and all 953 /// friends, friend functions and nested classes are fully defined in this 954 /// translation unit. 955 /// 956 /// Should only be called from ActOnEndOfTranslationUnit so that all 957 /// definitions are actually read. 958 static bool IsRecordFullyDefined(const CXXRecordDecl *RD, 959 RecordCompleteMap &RecordsComplete, 960 RecordCompleteMap &MNCComplete) { 961 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD); 962 if (Cache != RecordsComplete.end()) 963 return Cache->second; 964 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete); 965 for (CXXRecordDecl::friend_iterator I = RD->friend_begin(), 966 E = RD->friend_end(); 967 I != E && Complete; ++I) { 968 // Check if friend classes and methods are complete. 969 if (TypeSourceInfo *TSI = (*I)->getFriendType()) { 970 // Friend classes are available as the TypeSourceInfo of the FriendDecl. 971 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl()) 972 Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete); 973 else 974 Complete = false; 975 } else { 976 // Friend functions are available through the NamedDecl of FriendDecl. 977 if (const FunctionDecl *FD = 978 dyn_cast<FunctionDecl>((*I)->getFriendDecl())) 979 Complete = FD->isDefined(); 980 else 981 // This is a template friend, give up. 982 Complete = false; 983 } 984 } 985 RecordsComplete[RD] = Complete; 986 return Complete; 987 } 988 989 void Sema::emitAndClearUnusedLocalTypedefWarnings() { 990 if (ExternalSource) 991 ExternalSource->ReadUnusedLocalTypedefNameCandidates( 992 UnusedLocalTypedefNameCandidates); 993 for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) { 994 if (TD->isReferenced()) 995 continue; 996 Diag(TD->getLocation(), diag::warn_unused_local_typedef) 997 << isa<TypeAliasDecl>(TD) << TD->getDeclName(); 998 } 999 UnusedLocalTypedefNameCandidates.clear(); 1000 } 1001 1002 /// This is called before the very first declaration in the translation unit 1003 /// is parsed. Note that the ASTContext may have already injected some 1004 /// declarations. 1005 void Sema::ActOnStartOfTranslationUnit() { 1006 if (getLangOpts().ModulesTS && 1007 (getLangOpts().getCompilingModule() == LangOptions::CMK_ModuleInterface || 1008 getLangOpts().getCompilingModule() == LangOptions::CMK_None)) { 1009 // We start in an implied global module fragment. 1010 SourceLocation StartOfTU = 1011 SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); 1012 ActOnGlobalModuleFragmentDecl(StartOfTU); 1013 ModuleScopes.back().ImplicitGlobalModuleFragment = true; 1014 } 1015 } 1016 1017 void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) { 1018 // No explicit actions are required at the end of the global module fragment. 1019 if (Kind == TUFragmentKind::Global) 1020 return; 1021 1022 // Transfer late parsed template instantiations over to the pending template 1023 // instantiation list. During normal compilation, the late template parser 1024 // will be installed and instantiating these templates will succeed. 1025 // 1026 // If we are building a TU prefix for serialization, it is also safe to 1027 // transfer these over, even though they are not parsed. The end of the TU 1028 // should be outside of any eager template instantiation scope, so when this 1029 // AST is deserialized, these templates will not be parsed until the end of 1030 // the combined TU. 1031 PendingInstantiations.insert(PendingInstantiations.end(), 1032 LateParsedInstantiations.begin(), 1033 LateParsedInstantiations.end()); 1034 LateParsedInstantiations.clear(); 1035 1036 // If DefinedUsedVTables ends up marking any virtual member functions it 1037 // might lead to more pending template instantiations, which we then need 1038 // to instantiate. 1039 DefineUsedVTables(); 1040 1041 // C++: Perform implicit template instantiations. 1042 // 1043 // FIXME: When we perform these implicit instantiations, we do not 1044 // carefully keep track of the point of instantiation (C++ [temp.point]). 1045 // This means that name lookup that occurs within the template 1046 // instantiation will always happen at the end of the translation unit, 1047 // so it will find some names that are not required to be found. This is 1048 // valid, but we could do better by diagnosing if an instantiation uses a 1049 // name that was not visible at its first point of instantiation. 1050 if (ExternalSource) { 1051 // Load pending instantiations from the external source. 1052 SmallVector<PendingImplicitInstantiation, 4> Pending; 1053 ExternalSource->ReadPendingInstantiations(Pending); 1054 for (auto PII : Pending) 1055 if (auto Func = dyn_cast<FunctionDecl>(PII.first)) 1056 Func->setInstantiationIsPending(true); 1057 PendingInstantiations.insert(PendingInstantiations.begin(), 1058 Pending.begin(), Pending.end()); 1059 } 1060 1061 { 1062 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations"); 1063 PerformPendingInstantiations(); 1064 } 1065 1066 emitDeferredDiags(); 1067 1068 assert(LateParsedInstantiations.empty() && 1069 "end of TU template instantiation should not create more " 1070 "late-parsed templates"); 1071 1072 // Report diagnostics for uncorrected delayed typos. Ideally all of them 1073 // should have been corrected by that time, but it is very hard to cover all 1074 // cases in practice. 1075 for (const auto &Typo : DelayedTypos) { 1076 // We pass an empty TypoCorrection to indicate no correction was performed. 1077 Typo.second.DiagHandler(TypoCorrection()); 1078 } 1079 DelayedTypos.clear(); 1080 } 1081 1082 /// ActOnEndOfTranslationUnit - This is called at the very end of the 1083 /// translation unit when EOF is reached and all but the top-level scope is 1084 /// popped. 1085 void Sema::ActOnEndOfTranslationUnit() { 1086 assert(DelayedDiagnostics.getCurrentPool() == nullptr 1087 && "reached end of translation unit with a pool attached?"); 1088 1089 // If code completion is enabled, don't perform any end-of-translation-unit 1090 // work. 1091 if (PP.isCodeCompletionEnabled()) 1092 return; 1093 1094 // Complete translation units and modules define vtables and perform implicit 1095 // instantiations. PCH files do not. 1096 if (TUKind != TU_Prefix) { 1097 DiagnoseUseOfUnimplementedSelectors(); 1098 1099 ActOnEndOfTranslationUnitFragment( 1100 !ModuleScopes.empty() && ModuleScopes.back().Module->Kind == 1101 Module::PrivateModuleFragment 1102 ? TUFragmentKind::Private 1103 : TUFragmentKind::Normal); 1104 1105 if (LateTemplateParserCleanup) 1106 LateTemplateParserCleanup(OpaqueParser); 1107 1108 CheckDelayedMemberExceptionSpecs(); 1109 } else { 1110 // If we are building a TU prefix for serialization, it is safe to transfer 1111 // these over, even though they are not parsed. The end of the TU should be 1112 // outside of any eager template instantiation scope, so when this AST is 1113 // deserialized, these templates will not be parsed until the end of the 1114 // combined TU. 1115 PendingInstantiations.insert(PendingInstantiations.end(), 1116 LateParsedInstantiations.begin(), 1117 LateParsedInstantiations.end()); 1118 LateParsedInstantiations.clear(); 1119 1120 if (LangOpts.PCHInstantiateTemplates) { 1121 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations"); 1122 PerformPendingInstantiations(); 1123 } 1124 } 1125 1126 DiagnoseUnterminatedPragmaAlignPack(); 1127 DiagnoseUnterminatedPragmaAttribute(); 1128 1129 // All delayed member exception specs should be checked or we end up accepting 1130 // incompatible declarations. 1131 assert(DelayedOverridingExceptionSpecChecks.empty()); 1132 assert(DelayedEquivalentExceptionSpecChecks.empty()); 1133 1134 // All dllexport classes should have been processed already. 1135 assert(DelayedDllExportClasses.empty()); 1136 assert(DelayedDllExportMemberFunctions.empty()); 1137 1138 // Remove file scoped decls that turned out to be used. 1139 UnusedFileScopedDecls.erase( 1140 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true), 1141 UnusedFileScopedDecls.end(), 1142 [this](const DeclaratorDecl *DD) { 1143 return ShouldRemoveFromUnused(this, DD); 1144 }), 1145 UnusedFileScopedDecls.end()); 1146 1147 if (TUKind == TU_Prefix) { 1148 // Translation unit prefixes don't need any of the checking below. 1149 if (!PP.isIncrementalProcessingEnabled()) 1150 TUScope = nullptr; 1151 return; 1152 } 1153 1154 // Check for #pragma weak identifiers that were never declared 1155 LoadExternalWeakUndeclaredIdentifiers(); 1156 for (auto WeakID : WeakUndeclaredIdentifiers) { 1157 if (WeakID.second.getUsed()) 1158 continue; 1159 1160 Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(), 1161 LookupOrdinaryName); 1162 if (PrevDecl != nullptr && 1163 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) 1164 Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type) 1165 << "'weak'" << ExpectedVariableOrFunction; 1166 else 1167 Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared) 1168 << WeakID.first; 1169 } 1170 1171 if (LangOpts.CPlusPlus11 && 1172 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation())) 1173 CheckDelegatingCtorCycles(); 1174 1175 if (!Diags.hasErrorOccurred()) { 1176 if (ExternalSource) 1177 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed); 1178 checkUndefinedButUsed(*this); 1179 } 1180 1181 // A global-module-fragment is only permitted within a module unit. 1182 bool DiagnosedMissingModuleDeclaration = false; 1183 if (!ModuleScopes.empty() && 1184 ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment && 1185 !ModuleScopes.back().ImplicitGlobalModuleFragment) { 1186 Diag(ModuleScopes.back().BeginLoc, 1187 diag::err_module_declaration_missing_after_global_module_introducer); 1188 DiagnosedMissingModuleDeclaration = true; 1189 } 1190 1191 if (TUKind == TU_Module) { 1192 // If we are building a module interface unit, we need to have seen the 1193 // module declaration by now. 1194 if (getLangOpts().getCompilingModule() == 1195 LangOptions::CMK_ModuleInterface && 1196 (ModuleScopes.empty() || 1197 !ModuleScopes.back().Module->isModulePurview()) && 1198 !DiagnosedMissingModuleDeclaration) { 1199 // FIXME: Make a better guess as to where to put the module declaration. 1200 Diag(getSourceManager().getLocForStartOfFile( 1201 getSourceManager().getMainFileID()), 1202 diag::err_module_declaration_missing); 1203 } 1204 1205 // If we are building a module, resolve all of the exported declarations 1206 // now. 1207 if (Module *CurrentModule = PP.getCurrentModule()) { 1208 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap(); 1209 1210 SmallVector<Module *, 2> Stack; 1211 Stack.push_back(CurrentModule); 1212 while (!Stack.empty()) { 1213 Module *Mod = Stack.pop_back_val(); 1214 1215 // Resolve the exported declarations and conflicts. 1216 // FIXME: Actually complain, once we figure out how to teach the 1217 // diagnostic client to deal with complaints in the module map at this 1218 // point. 1219 ModMap.resolveExports(Mod, /*Complain=*/false); 1220 ModMap.resolveUses(Mod, /*Complain=*/false); 1221 ModMap.resolveConflicts(Mod, /*Complain=*/false); 1222 1223 // Queue the submodules, so their exports will also be resolved. 1224 Stack.append(Mod->submodule_begin(), Mod->submodule_end()); 1225 } 1226 } 1227 1228 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for 1229 // modules when they are built, not every time they are used. 1230 emitAndClearUnusedLocalTypedefWarnings(); 1231 } 1232 1233 // C99 6.9.2p2: 1234 // A declaration of an identifier for an object that has file 1235 // scope without an initializer, and without a storage-class 1236 // specifier or with the storage-class specifier static, 1237 // constitutes a tentative definition. If a translation unit 1238 // contains one or more tentative definitions for an identifier, 1239 // and the translation unit contains no external definition for 1240 // that identifier, then the behavior is exactly as if the 1241 // translation unit contains a file scope declaration of that 1242 // identifier, with the composite type as of the end of the 1243 // translation unit, with an initializer equal to 0. 1244 llvm::SmallSet<VarDecl *, 32> Seen; 1245 for (TentativeDefinitionsType::iterator 1246 T = TentativeDefinitions.begin(ExternalSource), 1247 TEnd = TentativeDefinitions.end(); 1248 T != TEnd; ++T) { 1249 VarDecl *VD = (*T)->getActingDefinition(); 1250 1251 // If the tentative definition was completed, getActingDefinition() returns 1252 // null. If we've already seen this variable before, insert()'s second 1253 // return value is false. 1254 if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second) 1255 continue; 1256 1257 if (const IncompleteArrayType *ArrayT 1258 = Context.getAsIncompleteArrayType(VD->getType())) { 1259 // Set the length of the array to 1 (C99 6.9.2p5). 1260 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array); 1261 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true); 1262 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), One, 1263 nullptr, ArrayType::Normal, 0); 1264 VD->setType(T); 1265 } else if (RequireCompleteType(VD->getLocation(), VD->getType(), 1266 diag::err_tentative_def_incomplete_type)) 1267 VD->setInvalidDecl(); 1268 1269 // No initialization is performed for a tentative definition. 1270 CheckCompleteVariableDeclaration(VD); 1271 1272 // Notify the consumer that we've completed a tentative definition. 1273 if (!VD->isInvalidDecl()) 1274 Consumer.CompleteTentativeDefinition(VD); 1275 } 1276 1277 for (auto D : ExternalDeclarations) { 1278 if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed()) 1279 continue; 1280 1281 Consumer.CompleteExternalDeclaration(D); 1282 } 1283 1284 // If there were errors, disable 'unused' warnings since they will mostly be 1285 // noise. Don't warn for a use from a module: either we should warn on all 1286 // file-scope declarations in modules or not at all, but whether the 1287 // declaration is used is immaterial. 1288 if (!Diags.hasErrorOccurred() && TUKind != TU_Module) { 1289 // Output warning for unused file scoped decls. 1290 for (UnusedFileScopedDeclsType::iterator 1291 I = UnusedFileScopedDecls.begin(ExternalSource), 1292 E = UnusedFileScopedDecls.end(); I != E; ++I) { 1293 if (ShouldRemoveFromUnused(this, *I)) 1294 continue; 1295 1296 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 1297 const FunctionDecl *DiagD; 1298 if (!FD->hasBody(DiagD)) 1299 DiagD = FD; 1300 if (DiagD->isDeleted()) 1301 continue; // Deleted functions are supposed to be unused. 1302 if (DiagD->isReferenced()) { 1303 if (isa<CXXMethodDecl>(DiagD)) 1304 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function) 1305 << DiagD; 1306 else { 1307 if (FD->getStorageClass() == SC_Static && 1308 !FD->isInlineSpecified() && 1309 !SourceMgr.isInMainFile( 1310 SourceMgr.getExpansionLoc(FD->getLocation()))) 1311 Diag(DiagD->getLocation(), 1312 diag::warn_unneeded_static_internal_decl) 1313 << DiagD; 1314 else 1315 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 1316 << /*function*/ 0 << DiagD; 1317 } 1318 } else { 1319 if (FD->getDescribedFunctionTemplate()) 1320 Diag(DiagD->getLocation(), diag::warn_unused_template) 1321 << /*function*/ 0 << DiagD; 1322 else 1323 Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD) 1324 ? diag::warn_unused_member_function 1325 : diag::warn_unused_function) 1326 << DiagD; 1327 } 1328 } else { 1329 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition(); 1330 if (!DiagD) 1331 DiagD = cast<VarDecl>(*I); 1332 if (DiagD->isReferenced()) { 1333 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl) 1334 << /*variable*/ 1 << DiagD; 1335 } else if (DiagD->getType().isConstQualified()) { 1336 const SourceManager &SM = SourceMgr; 1337 if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) || 1338 !PP.getLangOpts().IsHeaderFile) 1339 Diag(DiagD->getLocation(), diag::warn_unused_const_variable) 1340 << DiagD; 1341 } else { 1342 if (DiagD->getDescribedVarTemplate()) 1343 Diag(DiagD->getLocation(), diag::warn_unused_template) 1344 << /*variable*/ 1 << DiagD; 1345 else 1346 Diag(DiagD->getLocation(), diag::warn_unused_variable) << DiagD; 1347 } 1348 } 1349 } 1350 1351 emitAndClearUnusedLocalTypedefWarnings(); 1352 } 1353 1354 if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) { 1355 // FIXME: Load additional unused private field candidates from the external 1356 // source. 1357 RecordCompleteMap RecordsComplete; 1358 RecordCompleteMap MNCComplete; 1359 for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(), 1360 E = UnusedPrivateFields.end(); I != E; ++I) { 1361 const NamedDecl *D = *I; 1362 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()); 1363 if (RD && !RD->isUnion() && 1364 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) { 1365 Diag(D->getLocation(), diag::warn_unused_private_field) 1366 << D->getDeclName(); 1367 } 1368 } 1369 } 1370 1371 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) { 1372 if (ExternalSource) 1373 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs); 1374 for (const auto &DeletedFieldInfo : DeleteExprs) { 1375 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) { 1376 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first, 1377 DeleteExprLoc.second); 1378 } 1379 } 1380 } 1381 1382 // Check we've noticed that we're no longer parsing the initializer for every 1383 // variable. If we miss cases, then at best we have a performance issue and 1384 // at worst a rejects-valid bug. 1385 assert(ParsingInitForAutoVars.empty() && 1386 "Didn't unmark var as having its initializer parsed"); 1387 1388 if (!PP.isIncrementalProcessingEnabled()) 1389 TUScope = nullptr; 1390 } 1391 1392 1393 //===----------------------------------------------------------------------===// 1394 // Helper functions. 1395 //===----------------------------------------------------------------------===// 1396 1397 DeclContext *Sema::getFunctionLevelDeclContext() { 1398 DeclContext *DC = CurContext; 1399 1400 while (true) { 1401 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC) || 1402 isa<RequiresExprBodyDecl>(DC)) { 1403 DC = DC->getParent(); 1404 } else if (isa<CXXMethodDecl>(DC) && 1405 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call && 1406 cast<CXXRecordDecl>(DC->getParent())->isLambda()) { 1407 DC = DC->getParent()->getParent(); 1408 } 1409 else break; 1410 } 1411 1412 return DC; 1413 } 1414 1415 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 1416 /// to the function decl for the function being parsed. If we're currently 1417 /// in a 'block', this returns the containing context. 1418 FunctionDecl *Sema::getCurFunctionDecl() { 1419 DeclContext *DC = getFunctionLevelDeclContext(); 1420 return dyn_cast<FunctionDecl>(DC); 1421 } 1422 1423 ObjCMethodDecl *Sema::getCurMethodDecl() { 1424 DeclContext *DC = getFunctionLevelDeclContext(); 1425 while (isa<RecordDecl>(DC)) 1426 DC = DC->getParent(); 1427 return dyn_cast<ObjCMethodDecl>(DC); 1428 } 1429 1430 NamedDecl *Sema::getCurFunctionOrMethodDecl() { 1431 DeclContext *DC = getFunctionLevelDeclContext(); 1432 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC)) 1433 return cast<NamedDecl>(DC); 1434 return nullptr; 1435 } 1436 1437 LangAS Sema::getDefaultCXXMethodAddrSpace() const { 1438 if (getLangOpts().OpenCL) 1439 return LangAS::opencl_generic; 1440 return LangAS::Default; 1441 } 1442 1443 void Sema::EmitCurrentDiagnostic(unsigned DiagID) { 1444 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here 1445 // and yet we also use the current diag ID on the DiagnosticsEngine. This has 1446 // been made more painfully obvious by the refactor that introduced this 1447 // function, but it is possible that the incoming argument can be 1448 // eliminated. If it truly cannot be (for example, there is some reentrancy 1449 // issue I am not seeing yet), then there should at least be a clarifying 1450 // comment somewhere. 1451 if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) { 1452 switch (DiagnosticIDs::getDiagnosticSFINAEResponse( 1453 Diags.getCurrentDiagID())) { 1454 case DiagnosticIDs::SFINAE_Report: 1455 // We'll report the diagnostic below. 1456 break; 1457 1458 case DiagnosticIDs::SFINAE_SubstitutionFailure: 1459 // Count this failure so that we know that template argument deduction 1460 // has failed. 1461 ++NumSFINAEErrors; 1462 1463 // Make a copy of this suppressed diagnostic and store it with the 1464 // template-deduction information. 1465 if (*Info && !(*Info)->hasSFINAEDiagnostic()) { 1466 Diagnostic DiagInfo(&Diags); 1467 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(), 1468 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1469 } 1470 1471 Diags.setLastDiagnosticIgnored(true); 1472 Diags.Clear(); 1473 return; 1474 1475 case DiagnosticIDs::SFINAE_AccessControl: { 1476 // Per C++ Core Issue 1170, access control is part of SFINAE. 1477 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily 1478 // make access control a part of SFINAE for the purposes of checking 1479 // type traits. 1480 if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11) 1481 break; 1482 1483 SourceLocation Loc = Diags.getCurrentDiagLoc(); 1484 1485 // Suppress this diagnostic. 1486 ++NumSFINAEErrors; 1487 1488 // Make a copy of this suppressed diagnostic and store it with the 1489 // template-deduction information. 1490 if (*Info && !(*Info)->hasSFINAEDiagnostic()) { 1491 Diagnostic DiagInfo(&Diags); 1492 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(), 1493 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1494 } 1495 1496 Diags.setLastDiagnosticIgnored(true); 1497 Diags.Clear(); 1498 1499 // Now the diagnostic state is clear, produce a C++98 compatibility 1500 // warning. 1501 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control); 1502 1503 // The last diagnostic which Sema produced was ignored. Suppress any 1504 // notes attached to it. 1505 Diags.setLastDiagnosticIgnored(true); 1506 return; 1507 } 1508 1509 case DiagnosticIDs::SFINAE_Suppress: 1510 // Make a copy of this suppressed diagnostic and store it with the 1511 // template-deduction information; 1512 if (*Info) { 1513 Diagnostic DiagInfo(&Diags); 1514 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(), 1515 PartialDiagnostic(DiagInfo, Context.getDiagAllocator())); 1516 } 1517 1518 // Suppress this diagnostic. 1519 Diags.setLastDiagnosticIgnored(true); 1520 Diags.Clear(); 1521 return; 1522 } 1523 } 1524 1525 // Copy the diagnostic printing policy over the ASTContext printing policy. 1526 // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292 1527 Context.setPrintingPolicy(getPrintingPolicy()); 1528 1529 // Emit the diagnostic. 1530 if (!Diags.EmitCurrentDiagnostic()) 1531 return; 1532 1533 // If this is not a note, and we're in a template instantiation 1534 // that is different from the last template instantiation where 1535 // we emitted an error, print a template instantiation 1536 // backtrace. 1537 if (!DiagnosticIDs::isBuiltinNote(DiagID)) 1538 PrintContextStack(); 1539 } 1540 1541 Sema::SemaDiagnosticBuilder 1542 Sema::Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint) { 1543 return Diag(Loc, PD.getDiagID(), DeferHint) << PD; 1544 } 1545 1546 bool Sema::hasUncompilableErrorOccurred() const { 1547 if (getDiagnostics().hasUncompilableErrorOccurred()) 1548 return true; 1549 auto *FD = dyn_cast<FunctionDecl>(CurContext); 1550 if (!FD) 1551 return false; 1552 auto Loc = DeviceDeferredDiags.find(FD); 1553 if (Loc == DeviceDeferredDiags.end()) 1554 return false; 1555 for (auto PDAt : Loc->second) { 1556 if (DiagnosticIDs::isDefaultMappingAsError(PDAt.second.getDiagID())) 1557 return true; 1558 } 1559 return false; 1560 } 1561 1562 // Print notes showing how we can reach FD starting from an a priori 1563 // known-callable function. 1564 static void emitCallStackNotes(Sema &S, FunctionDecl *FD) { 1565 auto FnIt = S.DeviceKnownEmittedFns.find(FD); 1566 while (FnIt != S.DeviceKnownEmittedFns.end()) { 1567 // Respect error limit. 1568 if (S.Diags.hasFatalErrorOccurred()) 1569 return; 1570 DiagnosticBuilder Builder( 1571 S.Diags.Report(FnIt->second.Loc, diag::note_called_by)); 1572 Builder << FnIt->second.FD; 1573 FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD); 1574 } 1575 } 1576 1577 namespace { 1578 1579 /// Helper class that emits deferred diagnostic messages if an entity directly 1580 /// or indirectly using the function that causes the deferred diagnostic 1581 /// messages is known to be emitted. 1582 /// 1583 /// During parsing of AST, certain diagnostic messages are recorded as deferred 1584 /// diagnostics since it is unknown whether the functions containing such 1585 /// diagnostics will be emitted. A list of potentially emitted functions and 1586 /// variables that may potentially trigger emission of functions are also 1587 /// recorded. DeferredDiagnosticsEmitter recursively visits used functions 1588 /// by each function to emit deferred diagnostics. 1589 /// 1590 /// During the visit, certain OpenMP directives or initializer of variables 1591 /// with certain OpenMP attributes will cause subsequent visiting of any 1592 /// functions enter a state which is called OpenMP device context in this 1593 /// implementation. The state is exited when the directive or initializer is 1594 /// exited. This state can change the emission states of subsequent uses 1595 /// of functions. 1596 /// 1597 /// Conceptually the functions or variables to be visited form a use graph 1598 /// where the parent node uses the child node. At any point of the visit, 1599 /// the tree nodes traversed from the tree root to the current node form a use 1600 /// stack. The emission state of the current node depends on two factors: 1601 /// 1. the emission state of the root node 1602 /// 2. whether the current node is in OpenMP device context 1603 /// If the function is decided to be emitted, its contained deferred diagnostics 1604 /// are emitted, together with the information about the use stack. 1605 /// 1606 class DeferredDiagnosticsEmitter 1607 : public UsedDeclVisitor<DeferredDiagnosticsEmitter> { 1608 public: 1609 typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited; 1610 1611 // Whether the function is already in the current use-path. 1612 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath; 1613 1614 // The current use-path. 1615 llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath; 1616 1617 // Whether the visiting of the function has been done. Done[0] is for the 1618 // case not in OpenMP device context. Done[1] is for the case in OpenMP 1619 // device context. We need two sets because diagnostics emission may be 1620 // different depending on whether it is in OpenMP device context. 1621 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2]; 1622 1623 // Emission state of the root node of the current use graph. 1624 bool ShouldEmitRootNode; 1625 1626 // Current OpenMP device context level. It is initialized to 0 and each 1627 // entering of device context increases it by 1 and each exit decreases 1628 // it by 1. Non-zero value indicates it is currently in device context. 1629 unsigned InOMPDeviceContext; 1630 1631 DeferredDiagnosticsEmitter(Sema &S) 1632 : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {} 1633 1634 bool shouldVisitDiscardedStmt() const { return false; } 1635 1636 void VisitOMPTargetDirective(OMPTargetDirective *Node) { 1637 ++InOMPDeviceContext; 1638 Inherited::VisitOMPTargetDirective(Node); 1639 --InOMPDeviceContext; 1640 } 1641 1642 void visitUsedDecl(SourceLocation Loc, Decl *D) { 1643 if (isa<VarDecl>(D)) 1644 return; 1645 if (auto *FD = dyn_cast<FunctionDecl>(D)) 1646 checkFunc(Loc, FD); 1647 else 1648 Inherited::visitUsedDecl(Loc, D); 1649 } 1650 1651 void checkVar(VarDecl *VD) { 1652 assert(VD->isFileVarDecl() && 1653 "Should only check file-scope variables"); 1654 if (auto *Init = VD->getInit()) { 1655 auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD); 1656 bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost || 1657 *DevTy == OMPDeclareTargetDeclAttr::DT_Any); 1658 if (IsDev) 1659 ++InOMPDeviceContext; 1660 this->Visit(Init); 1661 if (IsDev) 1662 --InOMPDeviceContext; 1663 } 1664 } 1665 1666 void checkFunc(SourceLocation Loc, FunctionDecl *FD) { 1667 auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0]; 1668 FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back(); 1669 if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) || 1670 S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD)) 1671 return; 1672 // Finalize analysis of OpenMP-specific constructs. 1673 if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 && 1674 (ShouldEmitRootNode || InOMPDeviceContext)) 1675 S.finalizeOpenMPDelayedAnalysis(Caller, FD, Loc); 1676 if (Caller) 1677 S.DeviceKnownEmittedFns[FD] = {Caller, Loc}; 1678 // Always emit deferred diagnostics for the direct users. This does not 1679 // lead to explosion of diagnostics since each user is visited at most 1680 // twice. 1681 if (ShouldEmitRootNode || InOMPDeviceContext) 1682 emitDeferredDiags(FD, Caller); 1683 // Do not revisit a function if the function body has been completely 1684 // visited before. 1685 if (!Done.insert(FD).second) 1686 return; 1687 InUsePath.insert(FD); 1688 UsePath.push_back(FD); 1689 if (auto *S = FD->getBody()) { 1690 this->Visit(S); 1691 } 1692 UsePath.pop_back(); 1693 InUsePath.erase(FD); 1694 } 1695 1696 void checkRecordedDecl(Decl *D) { 1697 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1698 ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) == 1699 Sema::FunctionEmissionStatus::Emitted; 1700 checkFunc(SourceLocation(), FD); 1701 } else 1702 checkVar(cast<VarDecl>(D)); 1703 } 1704 1705 // Emit any deferred diagnostics for FD 1706 void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) { 1707 auto It = S.DeviceDeferredDiags.find(FD); 1708 if (It == S.DeviceDeferredDiags.end()) 1709 return; 1710 bool HasWarningOrError = false; 1711 bool FirstDiag = true; 1712 for (PartialDiagnosticAt &PDAt : It->second) { 1713 // Respect error limit. 1714 if (S.Diags.hasFatalErrorOccurred()) 1715 return; 1716 const SourceLocation &Loc = PDAt.first; 1717 const PartialDiagnostic &PD = PDAt.second; 1718 HasWarningOrError |= 1719 S.getDiagnostics().getDiagnosticLevel(PD.getDiagID(), Loc) >= 1720 DiagnosticsEngine::Warning; 1721 { 1722 DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID())); 1723 PD.Emit(Builder); 1724 } 1725 // Emit the note on the first diagnostic in case too many diagnostics 1726 // cause the note not emitted. 1727 if (FirstDiag && HasWarningOrError && ShowCallStack) { 1728 emitCallStackNotes(S, FD); 1729 FirstDiag = false; 1730 } 1731 } 1732 } 1733 }; 1734 } // namespace 1735 1736 void Sema::emitDeferredDiags() { 1737 if (ExternalSource) 1738 ExternalSource->ReadDeclsToCheckForDeferredDiags( 1739 DeclsToCheckForDeferredDiags); 1740 1741 if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) || 1742 DeclsToCheckForDeferredDiags.empty()) 1743 return; 1744 1745 DeferredDiagnosticsEmitter DDE(*this); 1746 for (auto D : DeclsToCheckForDeferredDiags) 1747 DDE.checkRecordedDecl(D); 1748 } 1749 1750 // In CUDA, there are some constructs which may appear in semantically-valid 1751 // code, but trigger errors if we ever generate code for the function in which 1752 // they appear. Essentially every construct you're not allowed to use on the 1753 // device falls into this category, because you are allowed to use these 1754 // constructs in a __host__ __device__ function, but only if that function is 1755 // never codegen'ed on the device. 1756 // 1757 // To handle semantic checking for these constructs, we keep track of the set of 1758 // functions we know will be emitted, either because we could tell a priori that 1759 // they would be emitted, or because they were transitively called by a 1760 // known-emitted function. 1761 // 1762 // We also keep a partial call graph of which not-known-emitted functions call 1763 // which other not-known-emitted functions. 1764 // 1765 // When we see something which is illegal if the current function is emitted 1766 // (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or 1767 // CheckCUDACall), we first check if the current function is known-emitted. If 1768 // so, we immediately output the diagnostic. 1769 // 1770 // Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags 1771 // until we discover that the function is known-emitted, at which point we take 1772 // it out of this map and emit the diagnostic. 1773 1774 Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc, 1775 unsigned DiagID, 1776 FunctionDecl *Fn, Sema &S) 1777 : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn), 1778 ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) { 1779 switch (K) { 1780 case K_Nop: 1781 break; 1782 case K_Immediate: 1783 case K_ImmediateWithCallStack: 1784 ImmediateDiag.emplace( 1785 ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID)); 1786 break; 1787 case K_Deferred: 1788 assert(Fn && "Must have a function to attach the deferred diag to."); 1789 auto &Diags = S.DeviceDeferredDiags[Fn]; 1790 PartialDiagId.emplace(Diags.size()); 1791 Diags.emplace_back(Loc, S.PDiag(DiagID)); 1792 break; 1793 } 1794 } 1795 1796 Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D) 1797 : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn), 1798 ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag), 1799 PartialDiagId(D.PartialDiagId) { 1800 // Clean the previous diagnostics. 1801 D.ShowCallStack = false; 1802 D.ImmediateDiag.reset(); 1803 D.PartialDiagId.reset(); 1804 } 1805 1806 Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() { 1807 if (ImmediateDiag) { 1808 // Emit our diagnostic and, if it was a warning or error, output a callstack 1809 // if Fn isn't a priori known-emitted. 1810 bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel( 1811 DiagID, Loc) >= DiagnosticsEngine::Warning; 1812 ImmediateDiag.reset(); // Emit the immediate diag. 1813 if (IsWarningOrError && ShowCallStack) 1814 emitCallStackNotes(S, Fn); 1815 } else { 1816 assert((!PartialDiagId || ShowCallStack) && 1817 "Must always show call stack for deferred diags."); 1818 } 1819 } 1820 1821 Sema::SemaDiagnosticBuilder 1822 Sema::targetDiag(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD) { 1823 FD = FD ? FD : getCurFunctionDecl(); 1824 if (LangOpts.OpenMP) 1825 return LangOpts.OpenMPIsDevice ? diagIfOpenMPDeviceCode(Loc, DiagID, FD) 1826 : diagIfOpenMPHostCode(Loc, DiagID, FD); 1827 if (getLangOpts().CUDA) 1828 return getLangOpts().CUDAIsDevice ? CUDADiagIfDeviceCode(Loc, DiagID) 1829 : CUDADiagIfHostCode(Loc, DiagID); 1830 1831 if (getLangOpts().SYCLIsDevice) 1832 return SYCLDiagIfDeviceCode(Loc, DiagID); 1833 1834 return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, DiagID, 1835 FD, *this); 1836 } 1837 1838 Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID, 1839 bool DeferHint) { 1840 bool IsError = Diags.getDiagnosticIDs()->isDefaultMappingAsError(DiagID); 1841 bool ShouldDefer = getLangOpts().CUDA && LangOpts.GPUDeferDiag && 1842 DiagnosticIDs::isDeferrable(DiagID) && 1843 (DeferHint || DeferDiags || !IsError); 1844 auto SetIsLastErrorImmediate = [&](bool Flag) { 1845 if (IsError) 1846 IsLastErrorImmediate = Flag; 1847 }; 1848 if (!ShouldDefer) { 1849 SetIsLastErrorImmediate(true); 1850 return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, 1851 DiagID, getCurFunctionDecl(), *this); 1852 } 1853 1854 SemaDiagnosticBuilder DB = getLangOpts().CUDAIsDevice 1855 ? CUDADiagIfDeviceCode(Loc, DiagID) 1856 : CUDADiagIfHostCode(Loc, DiagID); 1857 SetIsLastErrorImmediate(DB.isImmediate()); 1858 return DB; 1859 } 1860 1861 void Sema::checkDeviceDecl(ValueDecl *D, SourceLocation Loc) { 1862 if (isUnevaluatedContext()) 1863 return; 1864 1865 Decl *C = cast<Decl>(getCurLexicalContext()); 1866 1867 // Memcpy operations for structs containing a member with unsupported type 1868 // are ok, though. 1869 if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) { 1870 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) && 1871 MD->isTrivial()) 1872 return; 1873 1874 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD)) 1875 if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial()) 1876 return; 1877 } 1878 1879 // Try to associate errors with the lexical context, if that is a function, or 1880 // the value declaration otherwise. 1881 FunctionDecl *FD = 1882 isa<FunctionDecl>(C) ? cast<FunctionDecl>(C) : dyn_cast<FunctionDecl>(D); 1883 auto CheckType = [&](QualType Ty) { 1884 if (Ty->isDependentType()) 1885 return; 1886 1887 if (Ty->isExtIntType()) { 1888 if (!Context.getTargetInfo().hasExtIntType()) { 1889 targetDiag(Loc, diag::err_device_unsupported_type, FD) 1890 << D << false /*show bit size*/ << 0 /*bitsize*/ 1891 << Ty << Context.getTargetInfo().getTriple().str(); 1892 } 1893 return; 1894 } 1895 1896 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) || 1897 ((Ty->isFloat128Type() || 1898 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) && 1899 !Context.getTargetInfo().hasFloat128Type()) || 1900 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 && 1901 !Context.getTargetInfo().hasInt128Type())) { 1902 if (targetDiag(Loc, diag::err_device_unsupported_type, FD) 1903 << D << true /*show bit size*/ 1904 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty 1905 << Context.getTargetInfo().getTriple().str()) 1906 D->setInvalidDecl(); 1907 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D; 1908 } 1909 }; 1910 1911 QualType Ty = D->getType(); 1912 CheckType(Ty); 1913 1914 if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) { 1915 for (const auto &ParamTy : FPTy->param_types()) 1916 CheckType(ParamTy); 1917 CheckType(FPTy->getReturnType()); 1918 } 1919 if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty)) 1920 CheckType(FNPTy->getReturnType()); 1921 } 1922 1923 /// Looks through the macro-expansion chain for the given 1924 /// location, looking for a macro expansion with the given name. 1925 /// If one is found, returns true and sets the location to that 1926 /// expansion loc. 1927 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) { 1928 SourceLocation loc = locref; 1929 if (!loc.isMacroID()) return false; 1930 1931 // There's no good way right now to look at the intermediate 1932 // expansions, so just jump to the expansion location. 1933 loc = getSourceManager().getExpansionLoc(loc); 1934 1935 // If that's written with the name, stop here. 1936 SmallString<16> buffer; 1937 if (getPreprocessor().getSpelling(loc, buffer) == name) { 1938 locref = loc; 1939 return true; 1940 } 1941 return false; 1942 } 1943 1944 /// Determines the active Scope associated with the given declaration 1945 /// context. 1946 /// 1947 /// This routine maps a declaration context to the active Scope object that 1948 /// represents that declaration context in the parser. It is typically used 1949 /// from "scope-less" code (e.g., template instantiation, lazy creation of 1950 /// declarations) that injects a name for name-lookup purposes and, therefore, 1951 /// must update the Scope. 1952 /// 1953 /// \returns The scope corresponding to the given declaraion context, or NULL 1954 /// if no such scope is open. 1955 Scope *Sema::getScopeForContext(DeclContext *Ctx) { 1956 1957 if (!Ctx) 1958 return nullptr; 1959 1960 Ctx = Ctx->getPrimaryContext(); 1961 for (Scope *S = getCurScope(); S; S = S->getParent()) { 1962 // Ignore scopes that cannot have declarations. This is important for 1963 // out-of-line definitions of static class members. 1964 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) 1965 if (DeclContext *Entity = S->getEntity()) 1966 if (Ctx == Entity->getPrimaryContext()) 1967 return S; 1968 } 1969 1970 return nullptr; 1971 } 1972 1973 /// Enter a new function scope 1974 void Sema::PushFunctionScope() { 1975 if (FunctionScopes.empty() && CachedFunctionScope) { 1976 // Use CachedFunctionScope to avoid allocating memory when possible. 1977 CachedFunctionScope->Clear(); 1978 FunctionScopes.push_back(CachedFunctionScope.release()); 1979 } else { 1980 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics())); 1981 } 1982 if (LangOpts.OpenMP) 1983 pushOpenMPFunctionRegion(); 1984 } 1985 1986 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) { 1987 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(), 1988 BlockScope, Block)); 1989 } 1990 1991 LambdaScopeInfo *Sema::PushLambdaScope() { 1992 LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics()); 1993 FunctionScopes.push_back(LSI); 1994 return LSI; 1995 } 1996 1997 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) { 1998 if (LambdaScopeInfo *const LSI = getCurLambda()) { 1999 LSI->AutoTemplateParameterDepth = Depth; 2000 return; 2001 } 2002 llvm_unreachable( 2003 "Remove assertion if intentionally called in a non-lambda context."); 2004 } 2005 2006 // Check that the type of the VarDecl has an accessible copy constructor and 2007 // resolve its destructor's exception specification. 2008 // This also performs initialization of block variables when they are moved 2009 // to the heap. It uses the same rules as applicable for implicit moves 2010 // according to the C++ standard in effect ([class.copy.elision]p3). 2011 static void checkEscapingByref(VarDecl *VD, Sema &S) { 2012 QualType T = VD->getType(); 2013 EnterExpressionEvaluationContext scope( 2014 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); 2015 SourceLocation Loc = VD->getLocation(); 2016 Expr *VarRef = 2017 new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc); 2018 ExprResult Result; 2019 auto IE = InitializedEntity::InitializeBlock(Loc, T, false); 2020 if (S.getLangOpts().CPlusPlus2b) { 2021 auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr, 2022 VK_XValue, FPOptionsOverride()); 2023 Result = S.PerformCopyInitialization(IE, SourceLocation(), E); 2024 } else { 2025 Result = S.PerformMoveOrCopyInitialization( 2026 IE, Sema::NamedReturnInfo{VD, Sema::NamedReturnInfo::MoveEligible}, 2027 VarRef); 2028 } 2029 2030 if (!Result.isInvalid()) { 2031 Result = S.MaybeCreateExprWithCleanups(Result); 2032 Expr *Init = Result.getAs<Expr>(); 2033 S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init)); 2034 } 2035 2036 // The destructor's exception specification is needed when IRGen generates 2037 // block copy/destroy functions. Resolve it here. 2038 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) 2039 if (CXXDestructorDecl *DD = RD->getDestructor()) { 2040 auto *FPT = DD->getType()->getAs<FunctionProtoType>(); 2041 S.ResolveExceptionSpec(Loc, FPT); 2042 } 2043 } 2044 2045 static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) { 2046 // Set the EscapingByref flag of __block variables captured by 2047 // escaping blocks. 2048 for (const BlockDecl *BD : FSI.Blocks) { 2049 for (const BlockDecl::Capture &BC : BD->captures()) { 2050 VarDecl *VD = BC.getVariable(); 2051 if (VD->hasAttr<BlocksAttr>()) { 2052 // Nothing to do if this is a __block variable captured by a 2053 // non-escaping block. 2054 if (BD->doesNotEscape()) 2055 continue; 2056 VD->setEscapingByref(); 2057 } 2058 // Check whether the captured variable is or contains an object of 2059 // non-trivial C union type. 2060 QualType CapType = BC.getVariable()->getType(); 2061 if (CapType.hasNonTrivialToPrimitiveDestructCUnion() || 2062 CapType.hasNonTrivialToPrimitiveCopyCUnion()) 2063 S.checkNonTrivialCUnion(BC.getVariable()->getType(), 2064 BD->getCaretLocation(), 2065 Sema::NTCUC_BlockCapture, 2066 Sema::NTCUK_Destruct|Sema::NTCUK_Copy); 2067 } 2068 } 2069 2070 for (VarDecl *VD : FSI.ByrefBlockVars) { 2071 // __block variables might require us to capture a copy-initializer. 2072 if (!VD->isEscapingByref()) 2073 continue; 2074 // It's currently invalid to ever have a __block variable with an 2075 // array type; should we diagnose that here? 2076 // Regardless, we don't want to ignore array nesting when 2077 // constructing this copy. 2078 if (VD->getType()->isStructureOrClassType()) 2079 checkEscapingByref(VD, S); 2080 } 2081 } 2082 2083 /// Pop a function (or block or lambda or captured region) scope from the stack. 2084 /// 2085 /// \param WP The warning policy to use for CFG-based warnings, or null if such 2086 /// warnings should not be produced. 2087 /// \param D The declaration corresponding to this function scope, if producing 2088 /// CFG-based warnings. 2089 /// \param BlockType The type of the block expression, if D is a BlockDecl. 2090 Sema::PoppedFunctionScopePtr 2091 Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP, 2092 const Decl *D, QualType BlockType) { 2093 assert(!FunctionScopes.empty() && "mismatched push/pop!"); 2094 2095 markEscapingByrefs(*FunctionScopes.back(), *this); 2096 2097 PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(), 2098 PoppedFunctionScopeDeleter(this)); 2099 2100 if (LangOpts.OpenMP) 2101 popOpenMPFunctionRegion(Scope.get()); 2102 2103 // Issue any analysis-based warnings. 2104 if (WP && D) 2105 AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType); 2106 else 2107 for (const auto &PUD : Scope->PossiblyUnreachableDiags) 2108 Diag(PUD.Loc, PUD.PD); 2109 2110 return Scope; 2111 } 2112 2113 void Sema::PoppedFunctionScopeDeleter:: 2114 operator()(sema::FunctionScopeInfo *Scope) const { 2115 // Stash the function scope for later reuse if it's for a normal function. 2116 if (Scope->isPlainFunction() && !Self->CachedFunctionScope) 2117 Self->CachedFunctionScope.reset(Scope); 2118 else 2119 delete Scope; 2120 } 2121 2122 void Sema::PushCompoundScope(bool IsStmtExpr) { 2123 getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo(IsStmtExpr)); 2124 } 2125 2126 void Sema::PopCompoundScope() { 2127 FunctionScopeInfo *CurFunction = getCurFunction(); 2128 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop"); 2129 2130 CurFunction->CompoundScopes.pop_back(); 2131 } 2132 2133 /// Determine whether any errors occurred within this function/method/ 2134 /// block. 2135 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const { 2136 return getCurFunction()->hasUnrecoverableErrorOccurred(); 2137 } 2138 2139 void Sema::setFunctionHasBranchIntoScope() { 2140 if (!FunctionScopes.empty()) 2141 FunctionScopes.back()->setHasBranchIntoScope(); 2142 } 2143 2144 void Sema::setFunctionHasBranchProtectedScope() { 2145 if (!FunctionScopes.empty()) 2146 FunctionScopes.back()->setHasBranchProtectedScope(); 2147 } 2148 2149 void Sema::setFunctionHasIndirectGoto() { 2150 if (!FunctionScopes.empty()) 2151 FunctionScopes.back()->setHasIndirectGoto(); 2152 } 2153 2154 void Sema::setFunctionHasMustTail() { 2155 if (!FunctionScopes.empty()) 2156 FunctionScopes.back()->setHasMustTail(); 2157 } 2158 2159 BlockScopeInfo *Sema::getCurBlock() { 2160 if (FunctionScopes.empty()) 2161 return nullptr; 2162 2163 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back()); 2164 if (CurBSI && CurBSI->TheDecl && 2165 !CurBSI->TheDecl->Encloses(CurContext)) { 2166 // We have switched contexts due to template instantiation. 2167 assert(!CodeSynthesisContexts.empty()); 2168 return nullptr; 2169 } 2170 2171 return CurBSI; 2172 } 2173 2174 FunctionScopeInfo *Sema::getEnclosingFunction() const { 2175 if (FunctionScopes.empty()) 2176 return nullptr; 2177 2178 for (int e = FunctionScopes.size() - 1; e >= 0; --e) { 2179 if (isa<sema::BlockScopeInfo>(FunctionScopes[e])) 2180 continue; 2181 return FunctionScopes[e]; 2182 } 2183 return nullptr; 2184 } 2185 2186 LambdaScopeInfo *Sema::getEnclosingLambda() const { 2187 for (auto *Scope : llvm::reverse(FunctionScopes)) { 2188 if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) { 2189 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext)) { 2190 // We have switched contexts due to template instantiation. 2191 // FIXME: We should swap out the FunctionScopes during code synthesis 2192 // so that we don't need to check for this. 2193 assert(!CodeSynthesisContexts.empty()); 2194 return nullptr; 2195 } 2196 return LSI; 2197 } 2198 } 2199 return nullptr; 2200 } 2201 2202 LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) { 2203 if (FunctionScopes.empty()) 2204 return nullptr; 2205 2206 auto I = FunctionScopes.rbegin(); 2207 if (IgnoreNonLambdaCapturingScope) { 2208 auto E = FunctionScopes.rend(); 2209 while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I)) 2210 ++I; 2211 if (I == E) 2212 return nullptr; 2213 } 2214 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I); 2215 if (CurLSI && CurLSI->Lambda && 2216 !CurLSI->Lambda->Encloses(CurContext)) { 2217 // We have switched contexts due to template instantiation. 2218 assert(!CodeSynthesisContexts.empty()); 2219 return nullptr; 2220 } 2221 2222 return CurLSI; 2223 } 2224 2225 // We have a generic lambda if we parsed auto parameters, or we have 2226 // an associated template parameter list. 2227 LambdaScopeInfo *Sema::getCurGenericLambda() { 2228 if (LambdaScopeInfo *LSI = getCurLambda()) { 2229 return (LSI->TemplateParams.size() || 2230 LSI->GLTemplateParameterList) ? LSI : nullptr; 2231 } 2232 return nullptr; 2233 } 2234 2235 2236 void Sema::ActOnComment(SourceRange Comment) { 2237 if (!LangOpts.RetainCommentsFromSystemHeaders && 2238 SourceMgr.isInSystemHeader(Comment.getBegin())) 2239 return; 2240 RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false); 2241 if (RC.isAlmostTrailingComment()) { 2242 SourceRange MagicMarkerRange(Comment.getBegin(), 2243 Comment.getBegin().getLocWithOffset(3)); 2244 StringRef MagicMarkerText; 2245 switch (RC.getKind()) { 2246 case RawComment::RCK_OrdinaryBCPL: 2247 MagicMarkerText = "///<"; 2248 break; 2249 case RawComment::RCK_OrdinaryC: 2250 MagicMarkerText = "/**<"; 2251 break; 2252 default: 2253 llvm_unreachable("if this is an almost Doxygen comment, " 2254 "it should be ordinary"); 2255 } 2256 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) << 2257 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText); 2258 } 2259 Context.addComment(RC); 2260 } 2261 2262 // Pin this vtable to this file. 2263 ExternalSemaSource::~ExternalSemaSource() {} 2264 char ExternalSemaSource::ID; 2265 2266 void ExternalSemaSource::ReadMethodPool(Selector Sel) { } 2267 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { } 2268 2269 void ExternalSemaSource::ReadKnownNamespaces( 2270 SmallVectorImpl<NamespaceDecl *> &Namespaces) { 2271 } 2272 2273 void ExternalSemaSource::ReadUndefinedButUsed( 2274 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {} 2275 2276 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector< 2277 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {} 2278 2279 /// Figure out if an expression could be turned into a call. 2280 /// 2281 /// Use this when trying to recover from an error where the programmer may have 2282 /// written just the name of a function instead of actually calling it. 2283 /// 2284 /// \param E - The expression to examine. 2285 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call 2286 /// with no arguments, this parameter is set to the type returned by such a 2287 /// call; otherwise, it is set to an empty QualType. 2288 /// \param OverloadSet - If the expression is an overloaded function 2289 /// name, this parameter is populated with the decls of the various overloads. 2290 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, 2291 UnresolvedSetImpl &OverloadSet) { 2292 ZeroArgCallReturnTy = QualType(); 2293 OverloadSet.clear(); 2294 2295 const OverloadExpr *Overloads = nullptr; 2296 bool IsMemExpr = false; 2297 if (E.getType() == Context.OverloadTy) { 2298 OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E)); 2299 2300 // Ignore overloads that are pointer-to-member constants. 2301 if (FR.HasFormOfMemberPointer) 2302 return false; 2303 2304 Overloads = FR.Expression; 2305 } else if (E.getType() == Context.BoundMemberTy) { 2306 Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens()); 2307 IsMemExpr = true; 2308 } 2309 2310 bool Ambiguous = false; 2311 bool IsMV = false; 2312 2313 if (Overloads) { 2314 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(), 2315 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) { 2316 OverloadSet.addDecl(*it); 2317 2318 // Check whether the function is a non-template, non-member which takes no 2319 // arguments. 2320 if (IsMemExpr) 2321 continue; 2322 if (const FunctionDecl *OverloadDecl 2323 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) { 2324 if (OverloadDecl->getMinRequiredArguments() == 0) { 2325 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous && 2326 (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() || 2327 OverloadDecl->isCPUSpecificMultiVersion()))) { 2328 ZeroArgCallReturnTy = QualType(); 2329 Ambiguous = true; 2330 } else { 2331 ZeroArgCallReturnTy = OverloadDecl->getReturnType(); 2332 IsMV = OverloadDecl->isCPUDispatchMultiVersion() || 2333 OverloadDecl->isCPUSpecificMultiVersion(); 2334 } 2335 } 2336 } 2337 } 2338 2339 // If it's not a member, use better machinery to try to resolve the call 2340 if (!IsMemExpr) 2341 return !ZeroArgCallReturnTy.isNull(); 2342 } 2343 2344 // Attempt to call the member with no arguments - this will correctly handle 2345 // member templates with defaults/deduction of template arguments, overloads 2346 // with default arguments, etc. 2347 if (IsMemExpr && !E.isTypeDependent()) { 2348 Sema::TentativeAnalysisScope Trap(*this); 2349 ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(), 2350 None, SourceLocation()); 2351 if (R.isUsable()) { 2352 ZeroArgCallReturnTy = R.get()->getType(); 2353 return true; 2354 } 2355 return false; 2356 } 2357 2358 if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) { 2359 if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) { 2360 if (Fun->getMinRequiredArguments() == 0) 2361 ZeroArgCallReturnTy = Fun->getReturnType(); 2362 return true; 2363 } 2364 } 2365 2366 // We don't have an expression that's convenient to get a FunctionDecl from, 2367 // but we can at least check if the type is "function of 0 arguments". 2368 QualType ExprTy = E.getType(); 2369 const FunctionType *FunTy = nullptr; 2370 QualType PointeeTy = ExprTy->getPointeeType(); 2371 if (!PointeeTy.isNull()) 2372 FunTy = PointeeTy->getAs<FunctionType>(); 2373 if (!FunTy) 2374 FunTy = ExprTy->getAs<FunctionType>(); 2375 2376 if (const FunctionProtoType *FPT = 2377 dyn_cast_or_null<FunctionProtoType>(FunTy)) { 2378 if (FPT->getNumParams() == 0) 2379 ZeroArgCallReturnTy = FunTy->getReturnType(); 2380 return true; 2381 } 2382 return false; 2383 } 2384 2385 /// Give notes for a set of overloads. 2386 /// 2387 /// A companion to tryExprAsCall. In cases when the name that the programmer 2388 /// wrote was an overloaded function, we may be able to make some guesses about 2389 /// plausible overloads based on their return types; such guesses can be handed 2390 /// off to this method to be emitted as notes. 2391 /// 2392 /// \param Overloads - The overloads to note. 2393 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to 2394 /// -fshow-overloads=best, this is the location to attach to the note about too 2395 /// many candidates. Typically this will be the location of the original 2396 /// ill-formed expression. 2397 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, 2398 const SourceLocation FinalNoteLoc) { 2399 unsigned ShownOverloads = 0; 2400 unsigned SuppressedOverloads = 0; 2401 for (UnresolvedSetImpl::iterator It = Overloads.begin(), 2402 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 2403 if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) { 2404 ++SuppressedOverloads; 2405 continue; 2406 } 2407 2408 NamedDecl *Fn = (*It)->getUnderlyingDecl(); 2409 // Don't print overloads for non-default multiversioned functions. 2410 if (const auto *FD = Fn->getAsFunction()) { 2411 if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() && 2412 !FD->getAttr<TargetAttr>()->isDefaultVersion()) 2413 continue; 2414 } 2415 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call); 2416 ++ShownOverloads; 2417 } 2418 2419 S.Diags.overloadCandidatesShown(ShownOverloads); 2420 2421 if (SuppressedOverloads) 2422 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates) 2423 << SuppressedOverloads; 2424 } 2425 2426 static void notePlausibleOverloads(Sema &S, SourceLocation Loc, 2427 const UnresolvedSetImpl &Overloads, 2428 bool (*IsPlausibleResult)(QualType)) { 2429 if (!IsPlausibleResult) 2430 return noteOverloads(S, Overloads, Loc); 2431 2432 UnresolvedSet<2> PlausibleOverloads; 2433 for (OverloadExpr::decls_iterator It = Overloads.begin(), 2434 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) { 2435 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It); 2436 QualType OverloadResultTy = OverloadDecl->getReturnType(); 2437 if (IsPlausibleResult(OverloadResultTy)) 2438 PlausibleOverloads.addDecl(It.getDecl()); 2439 } 2440 noteOverloads(S, PlausibleOverloads, Loc); 2441 } 2442 2443 /// Determine whether the given expression can be called by just 2444 /// putting parentheses after it. Notably, expressions with unary 2445 /// operators can't be because the unary operator will start parsing 2446 /// outside the call. 2447 static bool IsCallableWithAppend(Expr *E) { 2448 E = E->IgnoreImplicit(); 2449 return (!isa<CStyleCastExpr>(E) && 2450 !isa<UnaryOperator>(E) && 2451 !isa<BinaryOperator>(E) && 2452 !isa<CXXOperatorCallExpr>(E)); 2453 } 2454 2455 static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) { 2456 if (const auto *UO = dyn_cast<UnaryOperator>(E)) 2457 E = UO->getSubExpr(); 2458 2459 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 2460 if (ULE->getNumDecls() == 0) 2461 return false; 2462 2463 const NamedDecl *ND = *ULE->decls_begin(); 2464 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 2465 return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion(); 2466 } 2467 return false; 2468 } 2469 2470 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 2471 bool ForceComplain, 2472 bool (*IsPlausibleResult)(QualType)) { 2473 SourceLocation Loc = E.get()->getExprLoc(); 2474 SourceRange Range = E.get()->getSourceRange(); 2475 2476 QualType ZeroArgCallTy; 2477 UnresolvedSet<4> Overloads; 2478 if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) && 2479 !ZeroArgCallTy.isNull() && 2480 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) { 2481 // At this point, we know E is potentially callable with 0 2482 // arguments and that it returns something of a reasonable type, 2483 // so we can emit a fixit and carry on pretending that E was 2484 // actually a CallExpr. 2485 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd()); 2486 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get()); 2487 Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range 2488 << (IsCallableWithAppend(E.get()) 2489 ? FixItHint::CreateInsertion(ParenInsertionLoc, "()") 2490 : FixItHint()); 2491 if (!IsMV) 2492 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult); 2493 2494 // FIXME: Try this before emitting the fixit, and suppress diagnostics 2495 // while doing so. 2496 E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), None, 2497 Range.getEnd().getLocWithOffset(1)); 2498 return true; 2499 } 2500 2501 if (!ForceComplain) return false; 2502 2503 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get()); 2504 Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range; 2505 if (!IsMV) 2506 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult); 2507 E = ExprError(); 2508 return true; 2509 } 2510 2511 IdentifierInfo *Sema::getSuperIdentifier() const { 2512 if (!Ident_super) 2513 Ident_super = &Context.Idents.get("super"); 2514 return Ident_super; 2515 } 2516 2517 IdentifierInfo *Sema::getFloat128Identifier() const { 2518 if (!Ident___float128) 2519 Ident___float128 = &Context.Idents.get("__float128"); 2520 return Ident___float128; 2521 } 2522 2523 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD, 2524 CapturedRegionKind K, 2525 unsigned OpenMPCaptureLevel) { 2526 auto *CSI = new CapturedRegionScopeInfo( 2527 getDiagnostics(), S, CD, RD, CD->getContextParam(), K, 2528 (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0, 2529 OpenMPCaptureLevel); 2530 CSI->ReturnType = Context.VoidTy; 2531 FunctionScopes.push_back(CSI); 2532 } 2533 2534 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() { 2535 if (FunctionScopes.empty()) 2536 return nullptr; 2537 2538 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back()); 2539 } 2540 2541 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> & 2542 Sema::getMismatchingDeleteExpressions() const { 2543 return DeleteExprs; 2544 } 2545 2546 Sema::FPFeaturesStateRAII::FPFeaturesStateRAII(Sema &S) 2547 : S(S), OldFPFeaturesState(S.CurFPFeatures), 2548 OldOverrides(S.FpPragmaStack.CurrentValue), 2549 OldEvalMethod(S.PP.getCurrentFPEvalMethod()) {} 2550 2551 Sema::FPFeaturesStateRAII::~FPFeaturesStateRAII() { 2552 S.CurFPFeatures = OldFPFeaturesState; 2553 S.FpPragmaStack.CurrentValue = OldOverrides; 2554 S.PP.setCurrentFPEvalMethod(OldEvalMethod); 2555 } 2556