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