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