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