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