clang 20.0.0git
Sema.cpp
Go to the documentation of this file.
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"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
24#include "clang/AST/StmtCXX.h"
30#include "clang/Basic/Stack.h"
43#include "clang/Sema/Scope.h"
46#include "clang/Sema/SemaARM.h"
47#include "clang/Sema/SemaAVR.h"
48#include "clang/Sema/SemaBPF.h"
49#include "clang/Sema/SemaCUDA.h"
52#include "clang/Sema/SemaHLSL.h"
56#include "clang/Sema/SemaM68k.h"
57#include "clang/Sema/SemaMIPS.h"
60#include "clang/Sema/SemaObjC.h"
64#include "clang/Sema/SemaPPC.h"
67#include "clang/Sema/SemaSYCL.h"
70#include "clang/Sema/SemaWasm.h"
71#include "clang/Sema/SemaX86.h"
75#include "llvm/ADT/DenseMap.h"
76#include "llvm/ADT/STLExtras.h"
77#include "llvm/ADT/SmallPtrSet.h"
78#include "llvm/Support/TimeProfiler.h"
79#include <optional>
80
81using namespace clang;
82using namespace sema;
83
86}
87
89
92 StringRef Platform) {
94 if (!SDKInfo && !WarnedDarwinSDKInfoMissing) {
95 Diag(Loc, diag::warn_missing_sdksettings_for_availability_checking)
96 << Platform;
97 WarnedDarwinSDKInfoMissing = true;
98 }
99 return SDKInfo;
100}
101
103 if (CachedDarwinSDKInfo)
104 return CachedDarwinSDKInfo->get();
105 auto SDKInfo = parseDarwinSDKInfo(
108 if (SDKInfo && *SDKInfo) {
109 CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(std::move(**SDKInfo));
110 return CachedDarwinSDKInfo->get();
111 }
112 if (!SDKInfo)
113 llvm::consumeError(SDKInfo.takeError());
114 CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>();
115 return nullptr;
116}
117
119 const IdentifierInfo *ParamName, unsigned int Index) {
120 std::string InventedName;
121 llvm::raw_string_ostream OS(InventedName);
122
123 if (!ParamName)
124 OS << "auto:" << Index + 1;
125 else
126 OS << ParamName->getName() << ":auto";
127
128 OS.flush();
129 return &Context.Idents.get(OS.str());
130}
131
133 const Preprocessor &PP) {
135 // In diagnostics, we print _Bool as bool if the latter is defined as the
136 // former.
137 Policy.Bool = Context.getLangOpts().Bool;
138 if (!Policy.Bool) {
139 if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
140 Policy.Bool = BoolMacro->isObjectLike() &&
141 BoolMacro->getNumTokens() == 1 &&
142 BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
143 }
144 }
145
146 // Shorten the data output if needed
147 Policy.EntireContentsOfLargeArray = false;
148
149 return Policy;
150}
151
153 TUScope = S;
155}
156
157namespace clang {
158namespace sema {
159
161 Sema *S = nullptr;
164
165public:
166 void set(Sema &S) { this->S = &S; }
167
168 void reset() { S = nullptr; }
169
172 FileID PrevFID) override {
173 if (!S)
174 return;
175 switch (Reason) {
176 case EnterFile: {
178 SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
179 if (IncludeLoc.isValid()) {
180 if (llvm::timeTraceProfilerEnabled()) {
181 OptionalFileEntryRef FE = SM.getFileEntryRefForID(SM.getFileID(Loc));
182 ProfilerStack.push_back(llvm::timeTraceAsyncProfilerBegin(
183 "Source", FE ? FE->getName() : StringRef("<unknown>")));
184 }
185
186 IncludeStack.push_back(IncludeLoc);
189 IncludeLoc);
190 }
191 break;
192 }
193 case ExitFile:
194 if (!IncludeStack.empty()) {
195 if (llvm::timeTraceProfilerEnabled())
196 llvm::timeTraceProfilerEnd(ProfilerStack.pop_back_val());
197
200 IncludeStack.pop_back_val());
201 }
202 break;
203 default:
204 break;
205 }
206 }
207};
208
209} // end namespace sema
210} // end namespace clang
211
212const unsigned Sema::MaxAlignmentExponent;
214
216 TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
217 : SemaBase(*this), CollectStats(false), TUKind(TUKind),
218 CurFPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
219 Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
220 SourceMgr(PP.getSourceManager()), APINotes(SourceMgr, LangOpts),
221 AnalysisWarnings(*this), ThreadSafetyDeclCache(nullptr),
222 LateTemplateParser(nullptr), LateTemplateParserCleanup(nullptr),
223 OpaqueParser(nullptr), CurContext(nullptr), ExternalSource(nullptr),
224 CurScope(nullptr), Ident_super(nullptr),
225 AMDGPUPtr(std::make_unique<SemaAMDGPU>(*this)),
226 ARMPtr(std::make_unique<SemaARM>(*this)),
227 AVRPtr(std::make_unique<SemaAVR>(*this)),
228 BPFPtr(std::make_unique<SemaBPF>(*this)),
229 CodeCompletionPtr(
230 std::make_unique<SemaCodeCompletion>(*this, CodeCompleter)),
231 CUDAPtr(std::make_unique<SemaCUDA>(*this)),
232 HLSLPtr(std::make_unique<SemaHLSL>(*this)),
233 HexagonPtr(std::make_unique<SemaHexagon>(*this)),
234 LoongArchPtr(std::make_unique<SemaLoongArch>(*this)),
235 M68kPtr(std::make_unique<SemaM68k>(*this)),
236 MIPSPtr(std::make_unique<SemaMIPS>(*this)),
237 MSP430Ptr(std::make_unique<SemaMSP430>(*this)),
238 NVPTXPtr(std::make_unique<SemaNVPTX>(*this)),
239 ObjCPtr(std::make_unique<SemaObjC>(*this)),
240 OpenACCPtr(std::make_unique<SemaOpenACC>(*this)),
241 OpenCLPtr(std::make_unique<SemaOpenCL>(*this)),
242 OpenMPPtr(std::make_unique<SemaOpenMP>(*this)),
243 PPCPtr(std::make_unique<SemaPPC>(*this)),
244 PseudoObjectPtr(std::make_unique<SemaPseudoObject>(*this)),
245 RISCVPtr(std::make_unique<SemaRISCV>(*this)),
246 SYCLPtr(std::make_unique<SemaSYCL>(*this)),
247 SwiftPtr(std::make_unique<SemaSwift>(*this)),
248 SystemZPtr(std::make_unique<SemaSystemZ>(*this)),
249 WasmPtr(std::make_unique<SemaWasm>(*this)),
250 X86Ptr(std::make_unique<SemaX86>(*this)),
251 MSPointerToMemberRepresentationMethod(
252 LangOpts.getMSPointerToMemberRepresentationMethod()),
253 MSStructPragmaOn(false), VtorDispStack(LangOpts.getVtorDispMode()),
254 AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)),
255 DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
256 CodeSegStack(nullptr), StrictGuardStackCheckStack(false),
257 FpPragmaStack(FPOptionsOverride()), CurInitSeg(nullptr),
258 VisContext(nullptr), PragmaAttributeCurrentTargetDecl(nullptr),
259 StdCoroutineTraitsCache(nullptr), IdResolver(pp),
260 OriginalLexicalContext(nullptr), StdInitializerList(nullptr),
261 FullyCheckedComparisonCategories(
262 static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
263 StdSourceLocationImplDecl(nullptr), CXXTypeInfoDecl(nullptr),
264 GlobalNewDeleteDeclared(false), DisableTypoCorrection(false),
265 TyposCorrected(0), IsBuildingRecoveryCallExpr(false), NumSFINAEErrors(0),
266 AccessCheckingSFINAE(false), CurrentInstantiationScope(nullptr),
267 InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
268 ArgumentPackSubstitutionIndex(-1), SatisfactionCache(Context) {
269 assert(pp.TUKind == TUKind);
270 TUScope = nullptr;
271
272 LoadedExternalKnownNamespaces = false;
273 for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
274 ObjC().NSNumberLiteralMethods[I] = nullptr;
275
276 if (getLangOpts().ObjC)
277 ObjC().NSAPIObj.reset(new NSAPI(Context));
278
281
282 // Tell diagnostics how to render things from the AST library.
284
285 // This evaluation context exists to ensure that there's always at least one
286 // valid evaluation context available. It is never removed from the
287 // evaluation stack.
288 ExprEvalContexts.emplace_back(
291
292 // Initialization of data sharing attributes stack for OpenMP
293 OpenMP().InitDataSharingAttributesStack();
294
295 std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
296 std::make_unique<sema::SemaPPCallbacks>();
297 SemaPPCallbackHandler = Callbacks.get();
298 PP.addPPCallbacks(std::move(Callbacks));
299 SemaPPCallbackHandler->set(*this);
300
301 CurFPFeatures.setFPEvalMethod(PP.getCurrentFPEvalMethod());
302}
303
304// Anchor Sema's type info to this TU.
306
307void Sema::addImplicitTypedef(StringRef Name, QualType T) {
308 DeclarationName DN = &Context.Idents.get(Name);
309 if (IdResolver.begin(DN) == IdResolver.end())
311}
312
314 // Create BuiltinVaListDecl *before* ExternalSemaSource::InitializeSema(this)
315 // because during initialization ASTReader can emit globals that require
316 // name mangling. And the name mangling uses BuiltinVaListDecl.
320
321 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
322 SC->InitializeSema(*this);
323
324 // Tell the external Sema source about this Sema object.
325 if (ExternalSemaSource *ExternalSema
326 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
327 ExternalSema->InitializeSema(*this);
328
329 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
330 // will not be able to merge any duplicate __va_list_tag decls correctly.
331 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
332
333 if (!TUScope)
334 return;
335
336 // Initialize predefined 128-bit integer types, if needed.
340 // If either of the 128-bit integer types are unavailable to name lookup,
341 // define them now.
342 DeclarationName Int128 = &Context.Idents.get("__int128_t");
343 if (IdResolver.begin(Int128) == IdResolver.end())
345
346 DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
347 if (IdResolver.begin(UInt128) == IdResolver.end())
349 }
350
351
352 // Initialize predefined Objective-C types:
353 if (getLangOpts().ObjC) {
354 // If 'SEL' does not yet refer to any declarations, make it refer to the
355 // predefined 'SEL'.
356 DeclarationName SEL = &Context.Idents.get("SEL");
357 if (IdResolver.begin(SEL) == IdResolver.end())
359
360 // If 'id' does not yet refer to any declarations, make it refer to the
361 // predefined 'id'.
363 if (IdResolver.begin(Id) == IdResolver.end())
365
366 // Create the built-in typedef for 'Class'.
370
371 // Create the built-in forward declaratino for 'Protocol'.
372 DeclarationName Protocol = &Context.Idents.get("Protocol");
373 if (IdResolver.begin(Protocol) == IdResolver.end())
375 }
376
377 // Create the internal type for the *StringMakeConstantString builtins.
378 DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
379 if (IdResolver.begin(ConstantString) == IdResolver.end())
381
382 // Initialize Microsoft "predefined C++ types".
383 if (getLangOpts().MSVCCompat) {
384 if (getLangOpts().CPlusPlus &&
385 IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
388 TUScope);
389
391 }
392
393 // Initialize predefined OpenCL types and supported extensions and (optional)
394 // core features.
395 if (getLangOpts().OpenCL) {
400 auto OCLCompatibleVersion = getLangOpts().getOpenCLCompatibleVersion();
401 if (OCLCompatibleVersion >= 200) {
402 if (getLangOpts().OpenCLCPlusPlus || getLangOpts().Blocks) {
405 }
406 if (getLangOpts().OpenCLPipes)
409 addImplicitTypedef("atomic_uint",
411 addImplicitTypedef("atomic_float",
413 // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
414 // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
416
417
418 // OpenCL v2.0 s6.13.11.6:
419 // - The atomic_long and atomic_ulong types are supported if the
420 // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
421 // extensions are supported.
422 // - The atomic_double type is only supported if double precision
423 // is supported and the cl_khr_int64_base_atomics and
424 // cl_khr_int64_extended_atomics extensions are supported.
425 // - If the device address space is 64-bits, the data types
426 // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
427 // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
428 // cl_khr_int64_extended_atomics extensions are supported.
429
430 auto AddPointerSizeDependentTypes = [&]() {
431 auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
432 auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
433 auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
434 auto AtomicPtrDiffT =
436 addImplicitTypedef("atomic_size_t", AtomicSizeT);
437 addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
438 addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
439 addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
440 };
441
442 if (Context.getTypeSize(Context.getSizeType()) == 32) {
443 AddPointerSizeDependentTypes();
444 }
445
446 if (getOpenCLOptions().isSupported("cl_khr_fp16", getLangOpts())) {
447 auto AtomicHalfT = Context.getAtomicType(Context.HalfTy);
448 addImplicitTypedef("atomic_half", AtomicHalfT);
449 }
450
451 std::vector<QualType> Atomic64BitTypes;
452 if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics",
453 getLangOpts()) &&
454 getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics",
455 getLangOpts())) {
456 if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) {
457 auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
458 addImplicitTypedef("atomic_double", AtomicDoubleT);
459 Atomic64BitTypes.push_back(AtomicDoubleT);
460 }
461 auto AtomicLongT = Context.getAtomicType(Context.LongTy);
462 auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
463 addImplicitTypedef("atomic_long", AtomicLongT);
464 addImplicitTypedef("atomic_ulong", AtomicULongT);
465
466
467 if (Context.getTypeSize(Context.getSizeType()) == 64) {
468 AddPointerSizeDependentTypes();
469 }
470 }
471 }
472
473#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
474 if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) { \
475 addImplicitTypedef(#ExtType, Context.Id##Ty); \
476 }
477#include "clang/Basic/OpenCLExtensionTypes.def"
478 }
479
483#define SVE_TYPE(Name, Id, SingletonId) \
484 addImplicitTypedef(Name, Context.SingletonId);
485#include "clang/Basic/AArch64SVEACLETypes.def"
486 }
487
488 if (Context.getTargetInfo().getTriple().isPPC64()) {
489#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
490 addImplicitTypedef(#Name, Context.Id##Ty);
491#include "clang/Basic/PPCTypes.def"
492#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
493 addImplicitTypedef(#Name, Context.Id##Ty);
494#include "clang/Basic/PPCTypes.def"
495 }
496
498#define RVV_TYPE(Name, Id, SingletonId) \
499 addImplicitTypedef(Name, Context.SingletonId);
500#include "clang/Basic/RISCVVTypes.def"
501 }
502
503 if (Context.getTargetInfo().getTriple().isWasm() &&
504 Context.getTargetInfo().hasFeature("reference-types")) {
505#define WASM_TYPE(Name, Id, SingletonId) \
506 addImplicitTypedef(Name, Context.SingletonId);
507#include "clang/Basic/WebAssemblyReferenceTypes.def"
508 }
509
510 if (Context.getTargetInfo().getTriple().isAMDGPU() ||
512 Context.getAuxTargetInfo()->getTriple().isAMDGPU())) {
513#define AMDGPU_TYPE(Name, Id, SingletonId) \
514 addImplicitTypedef(Name, Context.SingletonId);
515#include "clang/Basic/AMDGPUTypes.def"
516 }
517
519 DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
520 if (IdResolver.begin(MSVaList) == IdResolver.end())
522 }
523
524 DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
525 if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
527}
528
530 assert(InstantiatingSpecializations.empty() &&
531 "failed to clean up an InstantiatingTemplate?");
532
534
535 // Kill all the active scopes.
537 delete FSI;
538
539 // Tell the SemaConsumer to forget about us; we're going out of scope.
540 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
541 SC->ForgetSema();
542
543 // Detach from the external Sema source.
544 if (ExternalSemaSource *ExternalSema
545 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
546 ExternalSema->ForgetSema();
547
548 // Delete cached satisfactions.
549 std::vector<ConstraintSatisfaction *> Satisfactions;
550 Satisfactions.reserve(SatisfactionCache.size());
551 for (auto &Node : SatisfactionCache)
552 Satisfactions.push_back(&Node);
553 for (auto *Node : Satisfactions)
554 delete Node;
555
557
558 // Destroys data sharing attributes stack for OpenMP
559 OpenMP().DestroyDataSharingAttributesStack();
560
561 // Detach from the PP callback handler which outlives Sema since it's owned
562 // by the preprocessor.
563 SemaPPCallbackHandler->reset();
564}
565
567 // Only warn about this once.
569 Diag(Loc, diag::warn_stack_exhausted);
571 }
572}
573
575 llvm::function_ref<void()> Fn) {
577}
578
580 UnavailableAttr::ImplicitReason reason) {
581 // If we're not in a function, it's an error.
582 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
583 if (!fn) return false;
584
585 // If we're in template instantiation, it's an error.
587 return false;
588
589 // If that function's not in a system header, it's an error.
591 return false;
592
593 // If the function is already unavailable, it's not an error.
594 if (fn->hasAttr<UnavailableAttr>()) return true;
595
596 fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
597 return true;
598}
599
602}
603
605 assert(E && "Cannot use with NULL ptr");
606
607 if (!ExternalSource) {
609 return;
610 }
611
612 if (auto *Ex = dyn_cast<MultiplexExternalSemaSource>(ExternalSource))
613 Ex->AddSource(E);
614 else
616}
617
618void Sema::PrintStats() const {
619 llvm::errs() << "\n*** Semantic Analysis Stats:\n";
620 llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
621
622 BumpAlloc.PrintStats();
624}
625
627 QualType SrcType,
629 std::optional<NullabilityKind> ExprNullability = SrcType->getNullability();
630 if (!ExprNullability || (*ExprNullability != NullabilityKind::Nullable &&
631 *ExprNullability != NullabilityKind::NullableResult))
632 return;
633
634 std::optional<NullabilityKind> TypeNullability = DstType->getNullability();
635 if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
636 return;
637
638 Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
639}
640
641// Generate diagnostics when adding or removing effects in a type conversion.
644 const auto SrcFX = FunctionEffectsRef::get(SrcType);
645 const auto DstFX = FunctionEffectsRef::get(DstType);
646 if (SrcFX != DstFX) {
647 for (const auto &Diff : FunctionEffectDifferences(SrcFX, DstFX)) {
648 if (Diff.shouldDiagnoseConversion(SrcType, SrcFX, DstType, DstFX))
649 Diag(Loc, diag::warn_invalid_add_func_effects) << Diff.effectName();
650 }
651 }
652}
653
655 // nullptr only exists from C++11 on, so don't warn on its absence earlier.
657 return;
658
659 if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
660 return;
661
662 const Expr *EStripped = E->IgnoreParenImpCasts();
663 if (EStripped->getType()->isNullPtrType())
664 return;
665 if (isa<GNUNullExpr>(EStripped))
666 return;
667
668 if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
669 E->getBeginLoc()))
670 return;
671
672 // Don't diagnose the conversion from a 0 literal to a null pointer argument
673 // in a synthesized call to operator<=>.
674 if (!CodeSynthesisContexts.empty() &&
675 CodeSynthesisContexts.back().Kind ==
677 return;
678
679 // Ignore null pointers in defaulted comparison operators.
681 if (FD && FD->isDefaulted()) {
682 return;
683 }
684
685 // If it is a macro from system header, and if the macro name is not "NULL",
686 // do not warn.
687 // Note that uses of "NULL" will be ignored above on systems that define it
688 // as __null.
689 SourceLocation MaybeMacroLoc = E->getBeginLoc();
691 SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
692 !findMacroSpelling(MaybeMacroLoc, "NULL"))
693 return;
694
695 Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
697}
698
699/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
700/// If there is already an implicit cast, merge into the existing one.
701/// The result is of the given category.
703 CastKind Kind, ExprValueKind VK,
704 const CXXCastPath *BasePath,
706#ifndef NDEBUG
707 if (VK == VK_PRValue && !E->isPRValue()) {
708 switch (Kind) {
709 default:
710 llvm_unreachable(
711 ("can't implicitly cast glvalue to prvalue with this cast "
712 "kind: " +
713 std::string(CastExpr::getCastKindName(Kind)))
714 .c_str());
715 case CK_Dependent:
716 case CK_LValueToRValue:
717 case CK_ArrayToPointerDecay:
718 case CK_FunctionToPointerDecay:
719 case CK_ToVoid:
720 case CK_NonAtomicToAtomic:
721 case CK_HLSLArrayRValue:
722 break;
723 }
724 }
725 assert((VK == VK_PRValue || Kind == CK_Dependent || !E->isPRValue()) &&
726 "can't cast prvalue to glvalue");
727#endif
728
731 if (Context.hasAnyFunctionEffects() && !isCast(CCK) &&
732 Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
734
737
738 if (ExprTy == TypeTy)
739 return E;
740
741 if (Kind == CK_ArrayToPointerDecay) {
742 // C++1z [conv.array]: The temporary materialization conversion is applied.
743 // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
744 if (getLangOpts().CPlusPlus && E->isPRValue()) {
745 // The temporary is an lvalue in C++98 and an xvalue otherwise.
748 if (Materialized.isInvalid())
749 return ExprError();
750 E = Materialized.get();
751 }
752 // C17 6.7.1p6 footnote 124: The implementation can treat any register
753 // declaration simply as an auto declaration. However, whether or not
754 // addressable storage is actually used, the address of any part of an
755 // object declared with storage-class specifier register cannot be
756 // computed, either explicitly(by use of the unary & operator as discussed
757 // in 6.5.3.2) or implicitly(by converting an array name to a pointer as
758 // discussed in 6.3.2.1).Thus, the only operator that can be applied to an
759 // array declared with storage-class specifier register is sizeof.
760 if (VK == VK_PRValue && !getLangOpts().CPlusPlus && !E->isPRValue()) {
761 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
762 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
763 if (VD->getStorageClass() == SC_Register) {
764 Diag(E->getExprLoc(), diag::err_typecheck_address_of)
765 << /*register variable*/ 3 << E->getSourceRange();
766 return ExprError();
767 }
768 }
769 }
770 }
771 }
772
773 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
774 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
775 ImpCast->setType(Ty);
776 ImpCast->setValueKind(VK);
777 return E;
778 }
779 }
780
781 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
783}
784
786 switch (ScalarTy->getScalarTypeKind()) {
787 case Type::STK_Bool: return CK_NoOp;
788 case Type::STK_CPointer: return CK_PointerToBoolean;
789 case Type::STK_BlockPointer: return CK_PointerToBoolean;
790 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
791 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
792 case Type::STK_Integral: return CK_IntegralToBoolean;
793 case Type::STK_Floating: return CK_FloatingToBoolean;
794 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
795 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
796 case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
797 }
798 llvm_unreachable("unknown scalar type kind");
799}
800
801/// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
802static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
803 if (D->getMostRecentDecl()->isUsed())
804 return true;
805
806 if (D->isExternallyVisible())
807 return true;
808
809 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
810 // If this is a function template and none of its specializations is used,
811 // we should warn.
812 if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
813 for (const auto *Spec : Template->specializations())
814 if (ShouldRemoveFromUnused(SemaRef, Spec))
815 return true;
816
817 // UnusedFileScopedDecls stores the first declaration.
818 // The declaration may have become definition so check again.
819 const FunctionDecl *DeclToCheck;
820 if (FD->hasBody(DeclToCheck))
821 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
822
823 // Later redecls may add new information resulting in not having to warn,
824 // so check again.
825 DeclToCheck = FD->getMostRecentDecl();
826 if (DeclToCheck != FD)
827 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
828 }
829
830 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
831 // If a variable usable in constant expressions is referenced,
832 // don't warn if it isn't used: if the value of a variable is required
833 // for the computation of a constant expression, it doesn't make sense to
834 // warn even if the variable isn't odr-used. (isReferenced doesn't
835 // precisely reflect that, but it's a decent approximation.)
836 if (VD->isReferenced() &&
837 VD->mightBeUsableInConstantExpressions(SemaRef->Context))
838 return true;
839
840 if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
841 // If this is a variable template and none of its specializations is used,
842 // we should warn.
843 for (const auto *Spec : Template->specializations())
844 if (ShouldRemoveFromUnused(SemaRef, Spec))
845 return true;
846
847 // UnusedFileScopedDecls stores the first declaration.
848 // The declaration may have become definition so check again.
849 const VarDecl *DeclToCheck = VD->getDefinition();
850 if (DeclToCheck)
851 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
852
853 // Later redecls may add new information resulting in not having to warn,
854 // so check again.
855 DeclToCheck = VD->getMostRecentDecl();
856 if (DeclToCheck != VD)
857 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
858 }
859
860 return false;
861}
862
863static bool isFunctionOrVarDeclExternC(const NamedDecl *ND) {
864 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
865 return FD->isExternC();
866 return cast<VarDecl>(ND)->isExternC();
867}
868
869/// Determine whether ND is an external-linkage function or variable whose
870/// type has no linkage.
872 // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
873 // because we also want to catch the case where its type has VisibleNoLinkage,
874 // which does not affect the linkage of VD.
875 return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
878}
879
880/// Obtains a sorted list of functions and variables that are undefined but
881/// ODR-used.
883 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
884 for (const auto &UndefinedUse : UndefinedButUsed) {
885 NamedDecl *ND = UndefinedUse.first;
886
887 // Ignore attributes that have become invalid.
888 if (ND->isInvalidDecl()) continue;
889
890 // __attribute__((weakref)) is basically a definition.
891 if (ND->hasAttr<WeakRefAttr>()) continue;
892
893 if (isa<CXXDeductionGuideDecl>(ND))
894 continue;
895
896 if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
897 // An exported function will always be emitted when defined, so even if
898 // the function is inline, it doesn't have to be emitted in this TU. An
899 // imported function implies that it has been exported somewhere else.
900 continue;
901 }
902
903 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
904 if (FD->isDefined())
905 continue;
906 if (FD->isExternallyVisible() &&
908 !FD->getMostRecentDecl()->isInlined() &&
909 !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
910 continue;
911 if (FD->getBuiltinID())
912 continue;
913 } else {
914 const auto *VD = cast<VarDecl>(ND);
915 if (VD->hasDefinition() != VarDecl::DeclarationOnly)
916 continue;
917 if (VD->isExternallyVisible() &&
919 !VD->getMostRecentDecl()->isInline() &&
920 !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
921 continue;
922
923 // Skip VarDecls that lack formal definitions but which we know are in
924 // fact defined somewhere.
925 if (VD->isKnownToBeDefined())
926 continue;
927 }
928
929 Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
930 }
931}
932
933/// checkUndefinedButUsed - Check for undefined objects with internal linkage
934/// or that are inline.
936 if (S.UndefinedButUsed.empty()) return;
937
938 // Collect all the still-undefined entities with internal linkage.
940 S.getUndefinedButUsed(Undefined);
941 S.UndefinedButUsed.clear();
942 if (Undefined.empty()) return;
943
944 for (const auto &Undef : Undefined) {
945 ValueDecl *VD = cast<ValueDecl>(Undef.first);
946 SourceLocation UseLoc = Undef.second;
947
948 if (S.isExternalWithNoLinkageType(VD)) {
949 // C++ [basic.link]p8:
950 // A type without linkage shall not be used as the type of a variable
951 // or function with external linkage unless
952 // -- the entity has C language linkage
953 // -- the entity is not odr-used or is defined in the same TU
954 //
955 // As an extension, accept this in cases where the type is externally
956 // visible, since the function or variable actually can be defined in
957 // another translation unit in that case.
959 ? diag::ext_undefined_internal_type
960 : diag::err_undefined_internal_type)
961 << isa<VarDecl>(VD) << VD;
962 } else if (!VD->isExternallyVisible()) {
963 // FIXME: We can promote this to an error. The function or variable can't
964 // be defined anywhere else, so the program must necessarily violate the
965 // one definition rule.
966 bool IsImplicitBase = false;
967 if (const auto *BaseD = dyn_cast<FunctionDecl>(VD)) {
968 auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>();
969 if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(
970 llvm::omp::TraitProperty::
971 implementation_extension_disable_implicit_base)) {
972 const auto *Func = cast<FunctionDecl>(
973 cast<DeclRefExpr>(DVAttr->getVariantFuncRef())->getDecl());
974 IsImplicitBase = BaseD->isImplicit() &&
975 Func->getIdentifier()->isMangledOpenMPVariantName();
976 }
977 }
978 if (!S.getLangOpts().OpenMP || !IsImplicitBase)
979 S.Diag(VD->getLocation(), diag::warn_undefined_internal)
980 << isa<VarDecl>(VD) << VD;
981 } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
982 (void)FD;
983 assert(FD->getMostRecentDecl()->isInlined() &&
984 "used object requires definition but isn't inline or internal?");
985 // FIXME: This is ill-formed; we should reject.
986 S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
987 } else {
988 assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
989 "used var requires definition but isn't inline or internal?");
990 S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
991 }
992 if (UseLoc.isValid())
993 S.Diag(UseLoc, diag::note_used_here);
994 }
995}
996
998 if (!ExternalSource)
999 return;
1000
1002 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
1003 for (auto &WeakID : WeakIDs)
1004 (void)WeakUndeclaredIdentifiers[WeakID.first].insert(WeakID.second);
1005}
1006
1007
1008typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
1009
1010/// Returns true, if all methods and nested classes of the given
1011/// CXXRecordDecl are defined in this translation unit.
1012///
1013/// Should only be called from ActOnEndOfTranslationUnit so that all
1014/// definitions are actually read.
1016 RecordCompleteMap &MNCComplete) {
1017 RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
1018 if (Cache != MNCComplete.end())
1019 return Cache->second;
1020 if (!RD->isCompleteDefinition())
1021 return false;
1022 bool Complete = true;
1024 E = RD->decls_end();
1025 I != E && Complete; ++I) {
1026 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
1027 Complete = M->isDefined() || M->isDefaulted() ||
1028 (M->isPureVirtual() && !isa<CXXDestructorDecl>(M));
1029 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
1030 // If the template function is marked as late template parsed at this
1031 // point, it has not been instantiated and therefore we have not
1032 // performed semantic analysis on it yet, so we cannot know if the type
1033 // can be considered complete.
1034 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
1035 F->getTemplatedDecl()->isDefined();
1036 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
1037 if (R->isInjectedClassName())
1038 continue;
1039 if (R->hasDefinition())
1040 Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
1041 MNCComplete);
1042 else
1043 Complete = false;
1044 }
1045 }
1046 MNCComplete[RD] = Complete;
1047 return Complete;
1048}
1049
1050/// Returns true, if the given CXXRecordDecl is fully defined in this
1051/// translation unit, i.e. all methods are defined or pure virtual and all
1052/// friends, friend functions and nested classes are fully defined in this
1053/// translation unit.
1054///
1055/// Should only be called from ActOnEndOfTranslationUnit so that all
1056/// definitions are actually read.
1058 RecordCompleteMap &RecordsComplete,
1059 RecordCompleteMap &MNCComplete) {
1060 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
1061 if (Cache != RecordsComplete.end())
1062 return Cache->second;
1063 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
1065 E = RD->friend_end();
1066 I != E && Complete; ++I) {
1067 // Check if friend classes and methods are complete.
1068 if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
1069 // Friend classes are available as the TypeSourceInfo of the FriendDecl.
1070 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
1071 Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
1072 else
1073 Complete = false;
1074 } else {
1075 // Friend functions are available through the NamedDecl of FriendDecl.
1076 if (const FunctionDecl *FD =
1077 dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
1078 Complete = FD->isDefined();
1079 else
1080 // This is a template friend, give up.
1081 Complete = false;
1082 }
1083 }
1084 RecordsComplete[RD] = Complete;
1085 return Complete;
1086}
1087
1089 if (ExternalSource)
1090 ExternalSource->ReadUnusedLocalTypedefNameCandidates(
1093 if (TD->isReferenced())
1094 continue;
1095 Diag(TD->getLocation(), diag::warn_unused_local_typedef)
1096 << isa<TypeAliasDecl>(TD) << TD->getDeclName();
1097 }
1099}
1100
1102 if (getLangOpts().CPlusPlusModules &&
1103 getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit)
1104 HandleStartOfHeaderUnit();
1105}
1106
1108 // No explicit actions are required at the end of the global module fragment.
1109 if (Kind == TUFragmentKind::Global)
1110 return;
1111
1112 // Transfer late parsed template instantiations over to the pending template
1113 // instantiation list. During normal compilation, the late template parser
1114 // will be installed and instantiating these templates will succeed.
1115 //
1116 // If we are building a TU prefix for serialization, it is also safe to
1117 // transfer these over, even though they are not parsed. The end of the TU
1118 // should be outside of any eager template instantiation scope, so when this
1119 // AST is deserialized, these templates will not be parsed until the end of
1120 // the combined TU.
1125
1126 // If DefinedUsedVTables ends up marking any virtual member functions it
1127 // might lead to more pending template instantiations, which we then need
1128 // to instantiate.
1130
1131 // C++: Perform implicit template instantiations.
1132 //
1133 // FIXME: When we perform these implicit instantiations, we do not
1134 // carefully keep track of the point of instantiation (C++ [temp.point]).
1135 // This means that name lookup that occurs within the template
1136 // instantiation will always happen at the end of the translation unit,
1137 // so it will find some names that are not required to be found. This is
1138 // valid, but we could do better by diagnosing if an instantiation uses a
1139 // name that was not visible at its first point of instantiation.
1140 if (ExternalSource) {
1141 // Load pending instantiations from the external source.
1143 ExternalSource->ReadPendingInstantiations(Pending);
1144 for (auto PII : Pending)
1145 if (auto Func = dyn_cast<FunctionDecl>(PII.first))
1146 Func->setInstantiationIsPending(true);
1148 Pending.begin(), Pending.end());
1149 }
1150
1151 {
1152 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1154 }
1155
1157
1158 assert(LateParsedInstantiations.empty() &&
1159 "end of TU template instantiation should not create more "
1160 "late-parsed templates");
1161
1162 // Report diagnostics for uncorrected delayed typos. Ideally all of them
1163 // should have been corrected by that time, but it is very hard to cover all
1164 // cases in practice.
1165 for (const auto &Typo : DelayedTypos) {
1166 // We pass an empty TypoCorrection to indicate no correction was performed.
1167 Typo.second.DiagHandler(TypoCorrection());
1168 }
1169 DelayedTypos.clear();
1170}
1171
1173 assert(DelayedDiagnostics.getCurrentPool() == nullptr
1174 && "reached end of translation unit with a pool attached?");
1175
1176 // If code completion is enabled, don't perform any end-of-translation-unit
1177 // work.
1179 return;
1180
1181 // Complete translation units and modules define vtables and perform implicit
1182 // instantiations. PCH files do not.
1183 if (TUKind != TU_Prefix) {
1185
1187 !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1191
1194
1196 } else {
1197 // If we are building a TU prefix for serialization, it is safe to transfer
1198 // these over, even though they are not parsed. The end of the TU should be
1199 // outside of any eager template instantiation scope, so when this AST is
1200 // deserialized, these templates will not be parsed until the end of the
1201 // combined TU.
1206
1207 if (LangOpts.PCHInstantiateTemplates) {
1208 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1210 }
1211 }
1212
1216
1217 // All delayed member exception specs should be checked or we end up accepting
1218 // incompatible declarations.
1221
1222 // All dllexport classes should have been processed already.
1223 assert(DelayedDllExportClasses.empty());
1224 assert(DelayedDllExportMemberFunctions.empty());
1225
1226 // Remove file scoped decls that turned out to be used.
1228 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
1230 [this](const DeclaratorDecl *DD) {
1231 return ShouldRemoveFromUnused(this, DD);
1232 }),
1234
1235 if (TUKind == TU_Prefix) {
1236 // Translation unit prefixes don't need any of the checking below.
1238 TUScope = nullptr;
1239 return;
1240 }
1241
1242 // Check for #pragma weak identifiers that were never declared
1244 for (const auto &WeakIDs : WeakUndeclaredIdentifiers) {
1245 if (WeakIDs.second.empty())
1246 continue;
1247
1248 Decl *PrevDecl = LookupSingleName(TUScope, WeakIDs.first, SourceLocation(),
1250 if (PrevDecl != nullptr &&
1251 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
1252 for (const auto &WI : WeakIDs.second)
1253 Diag(WI.getLocation(), diag::warn_attribute_wrong_decl_type)
1254 << "'weak'" << /*isRegularKeyword=*/0 << ExpectedVariableOrFunction;
1255 else
1256 for (const auto &WI : WeakIDs.second)
1257 Diag(WI.getLocation(), diag::warn_weak_identifier_undeclared)
1258 << WeakIDs.first;
1259 }
1260
1261 if (LangOpts.CPlusPlus11 &&
1262 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
1264
1265 if (!Diags.hasErrorOccurred()) {
1266 if (ExternalSource)
1267 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
1268 checkUndefinedButUsed(*this);
1269 }
1270
1271 // A global-module-fragment is only permitted within a module unit.
1272 if (!ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1274 Diag(ModuleScopes.back().BeginLoc,
1275 diag::err_module_declaration_missing_after_global_module_introducer);
1276 } else if (getLangOpts().getCompilingModule() ==
1278 // We can't use ModuleScopes here since ModuleScopes is always
1279 // empty if we're compiling the BMI.
1280 !getASTContext().getCurrentNamedModule()) {
1281 // If we are building a module interface unit, we should have seen the
1282 // module declaration.
1283 //
1284 // FIXME: Make a better guess as to where to put the module declaration.
1285 Diag(getSourceManager().getLocForStartOfFile(
1286 getSourceManager().getMainFileID()),
1287 diag::err_module_declaration_missing);
1288 }
1289
1290 // Now we can decide whether the modules we're building need an initializer.
1291 if (Module *CurrentModule = getCurrentModule();
1292 CurrentModule && CurrentModule->isInterfaceOrPartition()) {
1293 auto DoesModNeedInit = [this](Module *M) {
1294 if (!getASTContext().getModuleInitializers(M).empty())
1295 return true;
1296 for (auto [Exported, _] : M->Exports)
1297 if (Exported->isNamedModuleInterfaceHasInit())
1298 return true;
1299 for (Module *I : M->Imports)
1301 return true;
1302
1303 return false;
1304 };
1305
1306 CurrentModule->NamedModuleHasInit =
1307 DoesModNeedInit(CurrentModule) ||
1308 llvm::any_of(CurrentModule->submodules(),
1309 [&](auto *SubM) { return DoesModNeedInit(SubM); });
1310 }
1311
1312 if (TUKind == TU_ClangModule) {
1313 // If we are building a module, resolve all of the exported declarations
1314 // now.
1315 if (Module *CurrentModule = PP.getCurrentModule()) {
1317
1319 Stack.push_back(CurrentModule);
1320 while (!Stack.empty()) {
1321 Module *Mod = Stack.pop_back_val();
1322
1323 // Resolve the exported declarations and conflicts.
1324 // FIXME: Actually complain, once we figure out how to teach the
1325 // diagnostic client to deal with complaints in the module map at this
1326 // point.
1327 ModMap.resolveExports(Mod, /*Complain=*/false);
1328 ModMap.resolveUses(Mod, /*Complain=*/false);
1329 ModMap.resolveConflicts(Mod, /*Complain=*/false);
1330
1331 // Queue the submodules, so their exports will also be resolved.
1332 auto SubmodulesRange = Mod->submodules();
1333 Stack.append(SubmodulesRange.begin(), SubmodulesRange.end());
1334 }
1335 }
1336
1337 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
1338 // modules when they are built, not every time they are used.
1340 }
1341
1342 // C++ standard modules. Diagnose cases where a function is declared inline
1343 // in the module purview but has no definition before the end of the TU or
1344 // the start of a Private Module Fragment (if one is present).
1345 if (!PendingInlineFuncDecls.empty()) {
1346 for (auto *D : PendingInlineFuncDecls) {
1347 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1348 bool DefInPMF = false;
1349 if (auto *FDD = FD->getDefinition()) {
1350 DefInPMF = FDD->getOwningModule()->isPrivateModule();
1351 if (!DefInPMF)
1352 continue;
1353 }
1354 Diag(FD->getLocation(), diag::err_export_inline_not_defined)
1355 << DefInPMF;
1356 // If we have a PMF it should be at the end of the ModuleScopes.
1357 if (DefInPMF &&
1358 ModuleScopes.back().Module->Kind == Module::PrivateModuleFragment) {
1359 Diag(ModuleScopes.back().BeginLoc,
1360 diag::note_private_module_fragment);
1361 }
1362 }
1363 }
1364 PendingInlineFuncDecls.clear();
1365 }
1366
1367 // C99 6.9.2p2:
1368 // A declaration of an identifier for an object that has file
1369 // scope without an initializer, and without a storage-class
1370 // specifier or with the storage-class specifier static,
1371 // constitutes a tentative definition. If a translation unit
1372 // contains one or more tentative definitions for an identifier,
1373 // and the translation unit contains no external definition for
1374 // that identifier, then the behavior is exactly as if the
1375 // translation unit contains a file scope declaration of that
1376 // identifier, with the composite type as of the end of the
1377 // translation unit, with an initializer equal to 0.
1378 llvm::SmallSet<VarDecl *, 32> Seen;
1379 for (TentativeDefinitionsType::iterator
1381 TEnd = TentativeDefinitions.end();
1382 T != TEnd; ++T) {
1383 VarDecl *VD = (*T)->getActingDefinition();
1384
1385 // If the tentative definition was completed, getActingDefinition() returns
1386 // null. If we've already seen this variable before, insert()'s second
1387 // return value is false.
1388 if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
1389 continue;
1390
1391 if (const IncompleteArrayType *ArrayT
1393 // Set the length of the array to 1 (C99 6.9.2p5).
1394 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
1395 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
1397 ArrayT->getElementType(), One, nullptr, ArraySizeModifier::Normal, 0);
1398 VD->setType(T);
1399 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
1400 diag::err_tentative_def_incomplete_type))
1401 VD->setInvalidDecl();
1402
1403 // No initialization is performed for a tentative definition.
1405
1406 // Notify the consumer that we've completed a tentative definition.
1407 if (!VD->isInvalidDecl())
1409 }
1410
1411 for (auto *D : ExternalDeclarations) {
1412 if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed())
1413 continue;
1414
1416 }
1417
1418 if (LangOpts.HLSL)
1420 getASTContext().getTranslationUnitDecl());
1421
1422 // If there were errors, disable 'unused' warnings since they will mostly be
1423 // noise. Don't warn for a use from a module: either we should warn on all
1424 // file-scope declarations in modules or not at all, but whether the
1425 // declaration is used is immaterial.
1427 // Output warning for unused file scoped decls.
1428 for (UnusedFileScopedDeclsType::iterator
1431 I != E; ++I) {
1432 if (ShouldRemoveFromUnused(this, *I))
1433 continue;
1434
1435 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1436 const FunctionDecl *DiagD;
1437 if (!FD->hasBody(DiagD))
1438 DiagD = FD;
1439 if (DiagD->isDeleted())
1440 continue; // Deleted functions are supposed to be unused.
1441 SourceRange DiagRange = DiagD->getLocation();
1442 if (const ASTTemplateArgumentListInfo *ASTTAL =
1444 DiagRange.setEnd(ASTTAL->RAngleLoc);
1445 if (DiagD->isReferenced()) {
1446 if (isa<CXXMethodDecl>(DiagD))
1447 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
1448 << DiagD << DiagRange;
1449 else {
1450 if (FD->getStorageClass() == SC_Static &&
1451 !FD->isInlineSpecified() &&
1453 SourceMgr.getExpansionLoc(FD->getLocation())))
1454 Diag(DiagD->getLocation(),
1455 diag::warn_unneeded_static_internal_decl)
1456 << DiagD << DiagRange;
1457 else
1458 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1459 << /*function=*/0 << DiagD << DiagRange;
1460 }
1461 } else if (!FD->isTargetMultiVersion() ||
1462 FD->isTargetMultiVersionDefault()) {
1463 if (FD->getDescribedFunctionTemplate())
1464 Diag(DiagD->getLocation(), diag::warn_unused_template)
1465 << /*function=*/0 << DiagD << DiagRange;
1466 else
1467 Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD)
1468 ? diag::warn_unused_member_function
1469 : diag::warn_unused_function)
1470 << DiagD << DiagRange;
1471 }
1472 } else {
1473 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
1474 if (!DiagD)
1475 DiagD = cast<VarDecl>(*I);
1476 SourceRange DiagRange = DiagD->getLocation();
1477 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(DiagD)) {
1478 if (const ASTTemplateArgumentListInfo *ASTTAL =
1479 VTSD->getTemplateArgsAsWritten())
1480 DiagRange.setEnd(ASTTAL->RAngleLoc);
1481 }
1482 if (DiagD->isReferenced()) {
1483 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1484 << /*variable=*/1 << DiagD << DiagRange;
1485 } else if (DiagD->getDescribedVarTemplate()) {
1486 Diag(DiagD->getLocation(), diag::warn_unused_template)
1487 << /*variable=*/1 << DiagD << DiagRange;
1488 } else if (DiagD->getType().isConstQualified()) {
1489 const SourceManager &SM = SourceMgr;
1490 if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
1492 Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
1493 << DiagD << DiagRange;
1494 } else {
1495 Diag(DiagD->getLocation(), diag::warn_unused_variable)
1496 << DiagD << DiagRange;
1497 }
1498 }
1499 }
1500
1502 }
1503
1504 if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
1505 // FIXME: Load additional unused private field candidates from the external
1506 // source.
1507 RecordCompleteMap RecordsComplete;
1508 RecordCompleteMap MNCComplete;
1509 for (const NamedDecl *D : UnusedPrivateFields) {
1510 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1511 if (RD && !RD->isUnion() &&
1512 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
1513 Diag(D->getLocation(), diag::warn_unused_private_field)
1514 << D->getDeclName();
1515 }
1516 }
1517 }
1518
1519 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
1520 if (ExternalSource)
1521 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
1522 for (const auto &DeletedFieldInfo : DeleteExprs) {
1523 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
1524 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
1525 DeleteExprLoc.second);
1526 }
1527 }
1528 }
1529
1531
1532 // Check we've noticed that we're no longer parsing the initializer for every
1533 // variable. If we miss cases, then at best we have a performance issue and
1534 // at worst a rejects-valid bug.
1535 assert(ParsingInitForAutoVars.empty() &&
1536 "Didn't unmark var as having its initializer parsed");
1537
1539 TUScope = nullptr;
1540}
1541
1542
1543//===----------------------------------------------------------------------===//
1544// Helper functions.
1545//===----------------------------------------------------------------------===//
1546
1548 DeclContext *DC = CurContext;
1549
1550 while (true) {
1551 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC) ||
1552 isa<RequiresExprBodyDecl>(DC)) {
1553 DC = DC->getParent();
1554 } else if (!AllowLambda && isa<CXXMethodDecl>(DC) &&
1555 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
1556 cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
1557 DC = DC->getParent()->getParent();
1558 } else break;
1559 }
1560
1561 return DC;
1562}
1563
1564/// getCurFunctionDecl - If inside of a function body, this returns a pointer
1565/// to the function decl for the function being parsed. If we're currently
1566/// in a 'block', this returns the containing context.
1567FunctionDecl *Sema::getCurFunctionDecl(bool AllowLambda) const {
1568 DeclContext *DC = getFunctionLevelDeclContext(AllowLambda);
1569 return dyn_cast<FunctionDecl>(DC);
1570}
1571
1574 while (isa<RecordDecl>(DC))
1575 DC = DC->getParent();
1576 return dyn_cast<ObjCMethodDecl>(DC);
1577}
1578
1581 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
1582 return cast<NamedDecl>(DC);
1583 return nullptr;
1584}
1585
1587 if (getLangOpts().OpenCL)
1589 return LangAS::Default;
1590}
1591
1592void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
1593 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1594 // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1595 // been made more painfully obvious by the refactor that introduced this
1596 // function, but it is possible that the incoming argument can be
1597 // eliminated. If it truly cannot be (for example, there is some reentrancy
1598 // issue I am not seeing yet), then there should at least be a clarifying
1599 // comment somewhere.
1600 if (std::optional<TemplateDeductionInfo *> Info = isSFINAEContext()) {
1604 // We'll report the diagnostic below.
1605 break;
1606
1608 // Count this failure so that we know that template argument deduction
1609 // has failed.
1611
1612 // Make a copy of this suppressed diagnostic and store it with the
1613 // template-deduction information.
1614 if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1615 Diagnostic DiagInfo(&Diags);
1616 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1618 }
1619
1621 Diags.Clear();
1622 return;
1623
1625 // Per C++ Core Issue 1170, access control is part of SFINAE.
1626 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1627 // make access control a part of SFINAE for the purposes of checking
1628 // type traits.
1630 break;
1631
1633
1634 // Suppress this diagnostic.
1636
1637 // Make a copy of this suppressed diagnostic and store it with the
1638 // template-deduction information.
1639 if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1640 Diagnostic DiagInfo(&Diags);
1641 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1643 }
1644
1646 Diags.Clear();
1647
1648 // Now the diagnostic state is clear, produce a C++98 compatibility
1649 // warning.
1650 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1651
1652 // The last diagnostic which Sema produced was ignored. Suppress any
1653 // notes attached to it.
1655 return;
1656 }
1657
1659 // Make a copy of this suppressed diagnostic and store it with the
1660 // template-deduction information;
1661 if (*Info) {
1662 Diagnostic DiagInfo(&Diags);
1663 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1665 }
1666
1667 // Suppress this diagnostic.
1669 Diags.Clear();
1670 return;
1671 }
1672 }
1673
1674 // Copy the diagnostic printing policy over the ASTContext printing policy.
1675 // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292
1677
1678 // Emit the diagnostic.
1680 return;
1681
1682 // If this is not a note, and we're in a template instantiation
1683 // that is different from the last template instantiation where
1684 // we emitted an error, print a template instantiation
1685 // backtrace.
1686 if (!DiagnosticIDs::isBuiltinNote(DiagID))
1688}
1689
1692 return true;
1693 auto *FD = dyn_cast<FunctionDecl>(CurContext);
1694 if (!FD)
1695 return false;
1696 auto Loc = DeviceDeferredDiags.find(FD);
1697 if (Loc == DeviceDeferredDiags.end())
1698 return false;
1699 for (auto PDAt : Loc->second) {
1700 if (DiagnosticIDs::isDefaultMappingAsError(PDAt.second.getDiagID()))
1701 return true;
1702 }
1703 return false;
1704}
1705
1706// Print notes showing how we can reach FD starting from an a priori
1707// known-callable function.
1708static void emitCallStackNotes(Sema &S, const FunctionDecl *FD) {
1709 auto FnIt = S.CUDA().DeviceKnownEmittedFns.find(FD);
1710 while (FnIt != S.CUDA().DeviceKnownEmittedFns.end()) {
1711 // Respect error limit.
1713 return;
1714 DiagnosticBuilder Builder(
1715 S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
1716 Builder << FnIt->second.FD;
1717 FnIt = S.CUDA().DeviceKnownEmittedFns.find(FnIt->second.FD);
1718 }
1719}
1720
1721namespace {
1722
1723/// Helper class that emits deferred diagnostic messages if an entity directly
1724/// or indirectly using the function that causes the deferred diagnostic
1725/// messages is known to be emitted.
1726///
1727/// During parsing of AST, certain diagnostic messages are recorded as deferred
1728/// diagnostics since it is unknown whether the functions containing such
1729/// diagnostics will be emitted. A list of potentially emitted functions and
1730/// variables that may potentially trigger emission of functions are also
1731/// recorded. DeferredDiagnosticsEmitter recursively visits used functions
1732/// by each function to emit deferred diagnostics.
1733///
1734/// During the visit, certain OpenMP directives or initializer of variables
1735/// with certain OpenMP attributes will cause subsequent visiting of any
1736/// functions enter a state which is called OpenMP device context in this
1737/// implementation. The state is exited when the directive or initializer is
1738/// exited. This state can change the emission states of subsequent uses
1739/// of functions.
1740///
1741/// Conceptually the functions or variables to be visited form a use graph
1742/// where the parent node uses the child node. At any point of the visit,
1743/// the tree nodes traversed from the tree root to the current node form a use
1744/// stack. The emission state of the current node depends on two factors:
1745/// 1. the emission state of the root node
1746/// 2. whether the current node is in OpenMP device context
1747/// If the function is decided to be emitted, its contained deferred diagnostics
1748/// are emitted, together with the information about the use stack.
1749///
1750class DeferredDiagnosticsEmitter
1751 : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
1752public:
1754
1755 // Whether the function is already in the current use-path.
1757
1758 // The current use-path.
1760
1761 // Whether the visiting of the function has been done. Done[0] is for the
1762 // case not in OpenMP device context. Done[1] is for the case in OpenMP
1763 // device context. We need two sets because diagnostics emission may be
1764 // different depending on whether it is in OpenMP device context.
1766
1767 // Emission state of the root node of the current use graph.
1768 bool ShouldEmitRootNode;
1769
1770 // Current OpenMP device context level. It is initialized to 0 and each
1771 // entering of device context increases it by 1 and each exit decreases
1772 // it by 1. Non-zero value indicates it is currently in device context.
1773 unsigned InOMPDeviceContext;
1774
1775 DeferredDiagnosticsEmitter(Sema &S)
1776 : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
1777
1778 bool shouldVisitDiscardedStmt() const { return false; }
1779
1780 void VisitOMPTargetDirective(OMPTargetDirective *Node) {
1781 ++InOMPDeviceContext;
1782 Inherited::VisitOMPTargetDirective(Node);
1783 --InOMPDeviceContext;
1784 }
1785
1786 void visitUsedDecl(SourceLocation Loc, Decl *D) {
1787 if (isa<VarDecl>(D))
1788 return;
1789 if (auto *FD = dyn_cast<FunctionDecl>(D))
1790 checkFunc(Loc, FD);
1791 else
1792 Inherited::visitUsedDecl(Loc, D);
1793 }
1794
1795 void checkVar(VarDecl *VD) {
1796 assert(VD->isFileVarDecl() &&
1797 "Should only check file-scope variables");
1798 if (auto *Init = VD->getInit()) {
1799 auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
1800 bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
1801 *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
1802 if (IsDev)
1803 ++InOMPDeviceContext;
1804 this->Visit(Init);
1805 if (IsDev)
1806 --InOMPDeviceContext;
1807 }
1808 }
1809
1810 void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
1811 auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0];
1812 FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back();
1813 if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) ||
1814 S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD))
1815 return;
1816 // Finalize analysis of OpenMP-specific constructs.
1817 if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 &&
1818 (ShouldEmitRootNode || InOMPDeviceContext))
1819 S.OpenMP().finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);
1820 if (Caller)
1821 S.CUDA().DeviceKnownEmittedFns[FD] = {Caller, Loc};
1822 // Always emit deferred diagnostics for the direct users. This does not
1823 // lead to explosion of diagnostics since each user is visited at most
1824 // twice.
1825 if (ShouldEmitRootNode || InOMPDeviceContext)
1826 emitDeferredDiags(FD, Caller);
1827 // Do not revisit a function if the function body has been completely
1828 // visited before.
1829 if (!Done.insert(FD).second)
1830 return;
1831 InUsePath.insert(FD);
1832 UsePath.push_back(FD);
1833 if (auto *S = FD->getBody()) {
1834 this->Visit(S);
1835 }
1836 UsePath.pop_back();
1837 InUsePath.erase(FD);
1838 }
1839
1840 void checkRecordedDecl(Decl *D) {
1841 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1842 ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==
1843 Sema::FunctionEmissionStatus::Emitted;
1844 checkFunc(SourceLocation(), FD);
1845 } else
1846 checkVar(cast<VarDecl>(D));
1847 }
1848
1849 // Emit any deferred diagnostics for FD
1850 void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) {
1851 auto It = S.DeviceDeferredDiags.find(FD);
1852 if (It == S.DeviceDeferredDiags.end())
1853 return;
1854 bool HasWarningOrError = false;
1855 bool FirstDiag = true;
1856 for (PartialDiagnosticAt &PDAt : It->second) {
1857 // Respect error limit.
1859 return;
1860 const SourceLocation &Loc = PDAt.first;
1861 const PartialDiagnostic &PD = PDAt.second;
1862 HasWarningOrError |=
1865 {
1866 DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
1867 PD.Emit(Builder);
1868 }
1869 // Emit the note on the first diagnostic in case too many diagnostics
1870 // cause the note not emitted.
1871 if (FirstDiag && HasWarningOrError && ShowCallStack) {
1872 emitCallStackNotes(S, FD);
1873 FirstDiag = false;
1874 }
1875 }
1876 }
1877};
1878} // namespace
1879
1881 if (ExternalSource)
1882 ExternalSource->ReadDeclsToCheckForDeferredDiags(
1883 DeclsToCheckForDeferredDiags);
1884
1885 if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) ||
1886 DeclsToCheckForDeferredDiags.empty())
1887 return;
1888
1889 DeferredDiagnosticsEmitter DDE(*this);
1890 for (auto *D : DeclsToCheckForDeferredDiags)
1891 DDE.checkRecordedDecl(D);
1892}
1893
1894// In CUDA, there are some constructs which may appear in semantically-valid
1895// code, but trigger errors if we ever generate code for the function in which
1896// they appear. Essentially every construct you're not allowed to use on the
1897// device falls into this category, because you are allowed to use these
1898// constructs in a __host__ __device__ function, but only if that function is
1899// never codegen'ed on the device.
1900//
1901// To handle semantic checking for these constructs, we keep track of the set of
1902// functions we know will be emitted, either because we could tell a priori that
1903// they would be emitted, or because they were transitively called by a
1904// known-emitted function.
1905//
1906// We also keep a partial call graph of which not-known-emitted functions call
1907// which other not-known-emitted functions.
1908//
1909// When we see something which is illegal if the current function is emitted
1910// (usually by way of DiagIfDeviceCode, DiagIfHostCode, or
1911// CheckCall), we first check if the current function is known-emitted. If
1912// so, we immediately output the diagnostic.
1913//
1914// Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags
1915// until we discover that the function is known-emitted, at which point we take
1916// it out of this map and emit the diagnostic.
1917
1918Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc,
1919 unsigned DiagID,
1920 const FunctionDecl *Fn,
1921 Sema &S)
1922 : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
1923 ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
1924 switch (K) {
1925 case K_Nop:
1926 break;
1927 case K_Immediate:
1928 case K_ImmediateWithCallStack:
1929 ImmediateDiag.emplace(
1930 ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID));
1931 break;
1932 case K_Deferred:
1933 assert(Fn && "Must have a function to attach the deferred diag to.");
1934 auto &Diags = S.DeviceDeferredDiags[Fn];
1935 PartialDiagId.emplace(Diags.size());
1936 Diags.emplace_back(Loc, S.PDiag(DiagID));
1937 break;
1938 }
1939}
1940
1941Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D)
1942 : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
1943 ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
1944 PartialDiagId(D.PartialDiagId) {
1945 // Clean the previous diagnostics.
1946 D.ShowCallStack = false;
1947 D.ImmediateDiag.reset();
1948 D.PartialDiagId.reset();
1949}
1950
1951Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
1952 if (ImmediateDiag) {
1953 // Emit our diagnostic and, if it was a warning or error, output a callstack
1954 // if Fn isn't a priori known-emitted.
1955 bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
1956 DiagID, Loc) >= DiagnosticsEngine::Warning;
1957 ImmediateDiag.reset(); // Emit the immediate diag.
1958 if (IsWarningOrError && ShowCallStack)
1959 emitCallStackNotes(S, Fn);
1960 } else {
1961 assert((!PartialDiagId || ShowCallStack) &&
1962 "Must always show call stack for deferred diags.");
1963 }
1964}
1965
1967Sema::targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD) {
1968 FD = FD ? FD : getCurFunctionDecl();
1969 if (LangOpts.OpenMP)
1970 return LangOpts.OpenMPIsTargetDevice
1971 ? OpenMP().diagIfOpenMPDeviceCode(Loc, DiagID, FD)
1972 : OpenMP().diagIfOpenMPHostCode(Loc, DiagID, FD);
1973 if (getLangOpts().CUDA)
1974 return getLangOpts().CUDAIsDevice ? CUDA().DiagIfDeviceCode(Loc, DiagID)
1975 : CUDA().DiagIfHostCode(Loc, DiagID);
1976
1977 if (getLangOpts().SYCLIsDevice)
1978 return SYCL().DiagIfDeviceCode(Loc, DiagID);
1979
1981 FD, *this);
1982}
1983
1985 if (isUnevaluatedContext() || Ty.isNull())
1986 return;
1987
1988 // The original idea behind checkTypeSupport function is that unused
1989 // declarations can be replaced with an array of bytes of the same size during
1990 // codegen, such replacement doesn't seem to be possible for types without
1991 // constant byte size like zero length arrays. So, do a deep check for SYCL.
1992 if (D && LangOpts.SYCLIsDevice) {
1993 llvm::DenseSet<QualType> Visited;
1994 SYCL().deepTypeCheckForDevice(Loc, Visited, D);
1995 }
1996
1997 Decl *C = cast<Decl>(getCurLexicalContext());
1998
1999 // Memcpy operations for structs containing a member with unsupported type
2000 // are ok, though.
2001 if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {
2002 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
2003 MD->isTrivial())
2004 return;
2005
2006 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))
2007 if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial())
2008 return;
2009 }
2010
2011 // Try to associate errors with the lexical context, if that is a function, or
2012 // the value declaration otherwise.
2013 const FunctionDecl *FD = isa<FunctionDecl>(C)
2014 ? cast<FunctionDecl>(C)
2015 : dyn_cast_or_null<FunctionDecl>(D);
2016
2017 auto CheckDeviceType = [&](QualType Ty) {
2018 if (Ty->isDependentType())
2019 return;
2020
2021 if (Ty->isBitIntType()) {
2022 if (!Context.getTargetInfo().hasBitIntType()) {
2023 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2024 if (D)
2025 PD << D;
2026 else
2027 PD << "expression";
2028 targetDiag(Loc, PD, FD)
2029 << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/
2030 << Ty << Context.getTargetInfo().getTriple().str();
2031 }
2032 return;
2033 }
2034
2035 // Check if we are dealing with two 'long double' but with different
2036 // semantics.
2037 bool LongDoubleMismatched = false;
2038 if (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128) {
2039 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(Ty);
2040 if ((&Sem != &llvm::APFloat::PPCDoubleDouble() &&
2041 !Context.getTargetInfo().hasFloat128Type()) ||
2042 (&Sem == &llvm::APFloat::PPCDoubleDouble() &&
2043 !Context.getTargetInfo().hasIbm128Type()))
2044 LongDoubleMismatched = true;
2045 }
2046
2047 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
2048 (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
2049 (Ty->isIbm128Type() && !Context.getTargetInfo().hasIbm128Type()) ||
2050 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
2051 !Context.getTargetInfo().hasInt128Type()) ||
2052 (Ty->isBFloat16Type() && !Context.getTargetInfo().hasBFloat16Type() &&
2053 !LangOpts.CUDAIsDevice) ||
2054 LongDoubleMismatched) {
2055 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2056 if (D)
2057 PD << D;
2058 else
2059 PD << "expression";
2060
2061 if (targetDiag(Loc, PD, FD)
2062 << true /*show bit size*/
2063 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
2064 << false /*return*/ << Context.getTargetInfo().getTriple().str()) {
2065 if (D)
2066 D->setInvalidDecl();
2067 }
2068 if (D)
2069 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2070 }
2071 };
2072
2073 auto CheckType = [&](QualType Ty, bool IsRetTy = false) {
2074 if (LangOpts.SYCLIsDevice ||
2075 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice) ||
2076 LangOpts.CUDAIsDevice)
2077 CheckDeviceType(Ty);
2078
2080 const TargetInfo &TI = Context.getTargetInfo();
2081 if (!TI.hasLongDoubleType() && UnqualTy == Context.LongDoubleTy) {
2082 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2083 if (D)
2084 PD << D;
2085 else
2086 PD << "expression";
2087
2088 if (Diag(Loc, PD, FD)
2089 << false /*show bit size*/ << 0 << Ty << false /*return*/
2090 << TI.getTriple().str()) {
2091 if (D)
2092 D->setInvalidDecl();
2093 }
2094 if (D)
2095 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2096 }
2097
2098 bool IsDouble = UnqualTy == Context.DoubleTy;
2099 bool IsFloat = UnqualTy == Context.FloatTy;
2100 if (IsRetTy && !TI.hasFPReturn() && (IsDouble || IsFloat)) {
2101 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2102 if (D)
2103 PD << D;
2104 else
2105 PD << "expression";
2106
2107 if (Diag(Loc, PD, FD)
2108 << false /*show bit size*/ << 0 << Ty << true /*return*/
2109 << TI.getTriple().str()) {
2110 if (D)
2111 D->setInvalidDecl();
2112 }
2113 if (D)
2114 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2115 }
2116
2117 if (TI.hasRISCVVTypes() && Ty->isRVVSizelessBuiltinType() && FD) {
2118 llvm::StringMap<bool> CallerFeatureMap;
2119 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
2120 RISCV().checkRVVTypeSupport(Ty, Loc, D, CallerFeatureMap);
2121 }
2122
2123 // Don't allow SVE types in functions without a SVE target.
2124 if (Ty->isSVESizelessBuiltinType() && FD) {
2125 llvm::StringMap<bool> CallerFeatureMap;
2126 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
2127 if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {
2128 if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap))
2129 Diag(Loc, diag::err_sve_vector_in_non_sve_target) << Ty;
2130 else if (!IsArmStreamingFunction(FD,
2131 /*IncludeLocallyStreaming=*/true)) {
2132 Diag(Loc, diag::err_sve_vector_in_non_streaming_function) << Ty;
2133 }
2134 }
2135 }
2136 };
2137
2138 CheckType(Ty);
2139 if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
2140 for (const auto &ParamTy : FPTy->param_types())
2141 CheckType(ParamTy);
2142 CheckType(FPTy->getReturnType(), /*IsRetTy=*/true);
2143 }
2144 if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty))
2145 CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true);
2146}
2147
2148bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
2149 SourceLocation loc = locref;
2150 if (!loc.isMacroID()) return false;
2151
2152 // There's no good way right now to look at the intermediate
2153 // expansions, so just jump to the expansion location.
2154 loc = getSourceManager().getExpansionLoc(loc);
2155
2156 // If that's written with the name, stop here.
2157 SmallString<16> buffer;
2158 if (getPreprocessor().getSpelling(loc, buffer) == name) {
2159 locref = loc;
2160 return true;
2161 }
2162 return false;
2163}
2164
2166
2167 if (!Ctx)
2168 return nullptr;
2169
2170 Ctx = Ctx->getPrimaryContext();
2171 for (Scope *S = getCurScope(); S; S = S->getParent()) {
2172 // Ignore scopes that cannot have declarations. This is important for
2173 // out-of-line definitions of static class members.
2174 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
2175 if (DeclContext *Entity = S->getEntity())
2176 if (Ctx == Entity->getPrimaryContext())
2177 return S;
2178 }
2179
2180 return nullptr;
2181}
2182
2183/// Enter a new function scope
2185 if (FunctionScopes.empty() && CachedFunctionScope) {
2186 // Use CachedFunctionScope to avoid allocating memory when possible.
2187 CachedFunctionScope->Clear();
2188 FunctionScopes.push_back(CachedFunctionScope.release());
2189 } else {
2190 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
2191 }
2192 if (LangOpts.OpenMP)
2193 OpenMP().pushOpenMPFunctionRegion();
2194}
2195
2197 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
2198 BlockScope, Block));
2199 CapturingFunctionScopes++;
2200}
2201
2204 FunctionScopes.push_back(LSI);
2205 CapturingFunctionScopes++;
2206 return LSI;
2207}
2208
2210 if (LambdaScopeInfo *const LSI = getCurLambda()) {
2211 LSI->AutoTemplateParameterDepth = Depth;
2212 return;
2213 }
2214 llvm_unreachable(
2215 "Remove assertion if intentionally called in a non-lambda context.");
2216}
2217
2218// Check that the type of the VarDecl has an accessible copy constructor and
2219// resolve its destructor's exception specification.
2220// This also performs initialization of block variables when they are moved
2221// to the heap. It uses the same rules as applicable for implicit moves
2222// according to the C++ standard in effect ([class.copy.elision]p3).
2223static void checkEscapingByref(VarDecl *VD, Sema &S) {
2224 QualType T = VD->getType();
2228 Expr *VarRef =
2229 new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
2232 if (S.getLangOpts().CPlusPlus23) {
2233 auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr,
2236 } else {
2239 VarRef);
2240 }
2241
2242 if (!Result.isInvalid()) {
2244 Expr *Init = Result.getAs<Expr>();
2246 }
2247
2248 // The destructor's exception specification is needed when IRGen generates
2249 // block copy/destroy functions. Resolve it here.
2250 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2251 if (CXXDestructorDecl *DD = RD->getDestructor()) {
2252 auto *FPT = DD->getType()->castAs<FunctionProtoType>();
2253 S.ResolveExceptionSpec(Loc, FPT);
2254 }
2255}
2256
2257static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
2258 // Set the EscapingByref flag of __block variables captured by
2259 // escaping blocks.
2260 for (const BlockDecl *BD : FSI.Blocks) {
2261 for (const BlockDecl::Capture &BC : BD->captures()) {
2262 VarDecl *VD = BC.getVariable();
2263 if (VD->hasAttr<BlocksAttr>()) {
2264 // Nothing to do if this is a __block variable captured by a
2265 // non-escaping block.
2266 if (BD->doesNotEscape())
2267 continue;
2268 VD->setEscapingByref();
2269 }
2270 // Check whether the captured variable is or contains an object of
2271 // non-trivial C union type.
2272 QualType CapType = BC.getVariable()->getType();
2275 S.checkNonTrivialCUnion(BC.getVariable()->getType(),
2276 BD->getCaretLocation(),
2279 }
2280 }
2281
2282 for (VarDecl *VD : FSI.ByrefBlockVars) {
2283 // __block variables might require us to capture a copy-initializer.
2284 if (!VD->isEscapingByref())
2285 continue;
2286 // It's currently invalid to ever have a __block variable with an
2287 // array type; should we diagnose that here?
2288 // Regardless, we don't want to ignore array nesting when
2289 // constructing this copy.
2290 if (VD->getType()->isStructureOrClassType())
2291 checkEscapingByref(VD, S);
2292 }
2293}
2294
2297 const Decl *D, QualType BlockType) {
2298 assert(!FunctionScopes.empty() && "mismatched push/pop!");
2299
2300 markEscapingByrefs(*FunctionScopes.back(), *this);
2301
2302 PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),
2304
2305 if (LangOpts.OpenMP)
2306 OpenMP().popOpenMPFunctionRegion(Scope.get());
2307
2308 // Issue any analysis-based warnings.
2309 if (WP && D)
2310 AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
2311 else
2312 for (const auto &PUD : Scope->PossiblyUnreachableDiags)
2313 Diag(PUD.Loc, PUD.PD);
2314
2315 return Scope;
2316}
2317
2320 if (!Scope->isPlainFunction())
2321 Self->CapturingFunctionScopes--;
2322 // Stash the function scope for later reuse if it's for a normal function.
2323 if (Scope->isPlainFunction() && !Self->CachedFunctionScope)
2324 Self->CachedFunctionScope.reset(Scope);
2325 else
2326 delete Scope;
2327}
2328
2329void Sema::PushCompoundScope(bool IsStmtExpr) {
2330 getCurFunction()->CompoundScopes.push_back(
2331 CompoundScopeInfo(IsStmtExpr, getCurFPFeatures()));
2332}
2333
2335 FunctionScopeInfo *CurFunction = getCurFunction();
2336 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
2337
2338 CurFunction->CompoundScopes.pop_back();
2339}
2340
2342 return getCurFunction()->hasUnrecoverableErrorOccurred();
2343}
2344
2346 if (!FunctionScopes.empty())
2347 FunctionScopes.back()->setHasBranchIntoScope();
2348}
2349
2351 if (!FunctionScopes.empty())
2352 FunctionScopes.back()->setHasBranchProtectedScope();
2353}
2354
2356 if (!FunctionScopes.empty())
2357 FunctionScopes.back()->setHasIndirectGoto();
2358}
2359
2361 if (!FunctionScopes.empty())
2362 FunctionScopes.back()->setHasMustTail();
2363}
2364
2366 if (FunctionScopes.empty())
2367 return nullptr;
2368
2369 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
2370 if (CurBSI && CurBSI->TheDecl &&
2371 !CurBSI->TheDecl->Encloses(CurContext)) {
2372 // We have switched contexts due to template instantiation.
2373 assert(!CodeSynthesisContexts.empty());
2374 return nullptr;
2375 }
2376
2377 return CurBSI;
2378}
2379
2381 if (FunctionScopes.empty())
2382 return nullptr;
2383
2384 for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
2385 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
2386 continue;
2387 return FunctionScopes[e];
2388 }
2389 return nullptr;
2390}
2391
2393 for (auto *Scope : llvm::reverse(FunctionScopes)) {
2394 if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) {
2395 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&
2396 LSI->AfterParameterList) {
2397 // We have switched contexts due to template instantiation.
2398 // FIXME: We should swap out the FunctionScopes during code synthesis
2399 // so that we don't need to check for this.
2400 assert(!CodeSynthesisContexts.empty());
2401 return nullptr;
2402 }
2403 return LSI;
2404 }
2405 }
2406 return nullptr;
2407}
2408
2409LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
2410 if (FunctionScopes.empty())
2411 return nullptr;
2412
2413 auto I = FunctionScopes.rbegin();
2414 if (IgnoreNonLambdaCapturingScope) {
2415 auto E = FunctionScopes.rend();
2416 while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
2417 ++I;
2418 if (I == E)
2419 return nullptr;
2420 }
2421 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
2422 if (CurLSI && CurLSI->Lambda && CurLSI->CallOperator &&
2423 !CurLSI->Lambda->Encloses(CurContext) && CurLSI->AfterParameterList) {
2424 // We have switched contexts due to template instantiation.
2425 assert(!CodeSynthesisContexts.empty());
2426 return nullptr;
2427 }
2428
2429 return CurLSI;
2430}
2431
2432// We have a generic lambda if we parsed auto parameters, or we have
2433// an associated template parameter list.
2435 if (LambdaScopeInfo *LSI = getCurLambda()) {
2436 return (LSI->TemplateParams.size() ||
2437 LSI->GLTemplateParameterList) ? LSI : nullptr;
2438 }
2439 return nullptr;
2440}
2441
2442
2444 if (!LangOpts.RetainCommentsFromSystemHeaders &&
2445 SourceMgr.isInSystemHeader(Comment.getBegin()))
2446 return;
2447 RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
2448 if (RC.isAlmostTrailingComment() || RC.hasUnsupportedSplice(SourceMgr)) {
2449 SourceRange MagicMarkerRange(Comment.getBegin(),
2450 Comment.getBegin().getLocWithOffset(3));
2451 StringRef MagicMarkerText;
2452 switch (RC.getKind()) {
2454 MagicMarkerText = "///<";
2455 break;
2457 MagicMarkerText = "/**<";
2458 break;
2460 // FIXME: are there other scenarios that could produce an invalid
2461 // raw comment here?
2462 Diag(Comment.getBegin(), diag::warn_splice_in_doxygen_comment);
2463 return;
2464 default:
2465 llvm_unreachable("if this is an almost Doxygen comment, "
2466 "it should be ordinary");
2467 }
2468 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
2469 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
2470 }
2471 Context.addComment(RC);
2472}
2473
2474// Pin this vtable to this file.
2476char ExternalSemaSource::ID;
2477
2480
2483}
2484
2486 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
2487
2489 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
2490
2491bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
2492 UnresolvedSetImpl &OverloadSet) {
2493 ZeroArgCallReturnTy = QualType();
2494 OverloadSet.clear();
2495
2496 const OverloadExpr *Overloads = nullptr;
2497 bool IsMemExpr = false;
2498 if (E.getType() == Context.OverloadTy) {
2500
2501 // Ignore overloads that are pointer-to-member constants.
2503 return false;
2504
2505 Overloads = FR.Expression;
2506 } else if (E.getType() == Context.BoundMemberTy) {
2507 Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
2508 IsMemExpr = true;
2509 }
2510
2511 bool Ambiguous = false;
2512 bool IsMV = false;
2513
2514 if (Overloads) {
2515 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
2516 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
2517 OverloadSet.addDecl(*it);
2518
2519 // Check whether the function is a non-template, non-member which takes no
2520 // arguments.
2521 if (IsMemExpr)
2522 continue;
2523 if (const FunctionDecl *OverloadDecl
2524 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
2525 if (OverloadDecl->getMinRequiredArguments() == 0) {
2526 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&
2527 (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
2528 OverloadDecl->isCPUSpecificMultiVersion()))) {
2529 ZeroArgCallReturnTy = QualType();
2530 Ambiguous = true;
2531 } else {
2532 ZeroArgCallReturnTy = OverloadDecl->getReturnType();
2533 IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
2534 OverloadDecl->isCPUSpecificMultiVersion();
2535 }
2536 }
2537 }
2538 }
2539
2540 // If it's not a member, use better machinery to try to resolve the call
2541 if (!IsMemExpr)
2542 return !ZeroArgCallReturnTy.isNull();
2543 }
2544
2545 // Attempt to call the member with no arguments - this will correctly handle
2546 // member templates with defaults/deduction of template arguments, overloads
2547 // with default arguments, etc.
2548 if (IsMemExpr && !E.isTypeDependent()) {
2549 Sema::TentativeAnalysisScope Trap(*this);
2550 ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
2551 std::nullopt, SourceLocation());
2552 if (R.isUsable()) {
2553 ZeroArgCallReturnTy = R.get()->getType();
2554 return true;
2555 }
2556 return false;
2557 }
2558
2559 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
2560 if (const auto *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
2561 if (Fun->getMinRequiredArguments() == 0)
2562 ZeroArgCallReturnTy = Fun->getReturnType();
2563 return true;
2564 }
2565 }
2566
2567 // We don't have an expression that's convenient to get a FunctionDecl from,
2568 // but we can at least check if the type is "function of 0 arguments".
2569 QualType ExprTy = E.getType();
2570 const FunctionType *FunTy = nullptr;
2571 QualType PointeeTy = ExprTy->getPointeeType();
2572 if (!PointeeTy.isNull())
2573 FunTy = PointeeTy->getAs<FunctionType>();
2574 if (!FunTy)
2575 FunTy = ExprTy->getAs<FunctionType>();
2576
2577 if (const auto *FPT = dyn_cast_if_present<FunctionProtoType>(FunTy)) {
2578 if (FPT->getNumParams() == 0)
2579 ZeroArgCallReturnTy = FunTy->getReturnType();
2580 return true;
2581 }
2582 return false;
2583}
2584
2585/// Give notes for a set of overloads.
2586///
2587/// A companion to tryExprAsCall. In cases when the name that the programmer
2588/// wrote was an overloaded function, we may be able to make some guesses about
2589/// plausible overloads based on their return types; such guesses can be handed
2590/// off to this method to be emitted as notes.
2591///
2592/// \param Overloads - The overloads to note.
2593/// \param FinalNoteLoc - If we've suppressed printing some overloads due to
2594/// -fshow-overloads=best, this is the location to attach to the note about too
2595/// many candidates. Typically this will be the location of the original
2596/// ill-formed expression.
2597static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
2598 const SourceLocation FinalNoteLoc) {
2599 unsigned ShownOverloads = 0;
2600 unsigned SuppressedOverloads = 0;
2601 for (UnresolvedSetImpl::iterator It = Overloads.begin(),
2602 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2603 if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) {
2604 ++SuppressedOverloads;
2605 continue;
2606 }
2607
2608 const NamedDecl *Fn = (*It)->getUnderlyingDecl();
2609 // Don't print overloads for non-default multiversioned functions.
2610 if (const auto *FD = Fn->getAsFunction()) {
2611 if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&
2612 !FD->getAttr<TargetAttr>()->isDefaultVersion())
2613 continue;
2614 if (FD->isMultiVersion() && FD->hasAttr<TargetVersionAttr>() &&
2615 !FD->getAttr<TargetVersionAttr>()->isDefaultVersion())
2616 continue;
2617 }
2618 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
2619 ++ShownOverloads;
2620 }
2621
2622 S.Diags.overloadCandidatesShown(ShownOverloads);
2623
2624 if (SuppressedOverloads)
2625 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
2626 << SuppressedOverloads;
2627}
2628
2630 const UnresolvedSetImpl &Overloads,
2631 bool (*IsPlausibleResult)(QualType)) {
2632 if (!IsPlausibleResult)
2633 return noteOverloads(S, Overloads, Loc);
2634
2635 UnresolvedSet<2> PlausibleOverloads;
2636 for (OverloadExpr::decls_iterator It = Overloads.begin(),
2637 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2638 const auto *OverloadDecl = cast<FunctionDecl>(*It);
2639 QualType OverloadResultTy = OverloadDecl->getReturnType();
2640 if (IsPlausibleResult(OverloadResultTy))
2641 PlausibleOverloads.addDecl(It.getDecl());
2642 }
2643 noteOverloads(S, PlausibleOverloads, Loc);
2644}
2645
2646/// Determine whether the given expression can be called by just
2647/// putting parentheses after it. Notably, expressions with unary
2648/// operators can't be because the unary operator will start parsing
2649/// outside the call.
2650static bool IsCallableWithAppend(const Expr *E) {
2651 E = E->IgnoreImplicit();
2652 return (!isa<CStyleCastExpr>(E) &&
2653 !isa<UnaryOperator>(E) &&
2654 !isa<BinaryOperator>(E) &&
2655 !isa<CXXOperatorCallExpr>(E));
2656}
2657
2659 if (const auto *UO = dyn_cast<UnaryOperator>(E))
2660 E = UO->getSubExpr();
2661
2662 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2663 if (ULE->getNumDecls() == 0)
2664 return false;
2665
2666 const NamedDecl *ND = *ULE->decls_begin();
2667 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2669 }
2670 return false;
2671}
2672
2674 bool ForceComplain,
2675 bool (*IsPlausibleResult)(QualType)) {
2676 SourceLocation Loc = E.get()->getExprLoc();
2677 SourceRange Range = E.get()->getSourceRange();
2678 UnresolvedSet<4> Overloads;
2679
2680 // If this is a SFINAE context, don't try anything that might trigger ADL
2681 // prematurely.
2682 if (!isSFINAEContext()) {
2683 QualType ZeroArgCallTy;
2684 if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
2685 !ZeroArgCallTy.isNull() &&
2686 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
2687 // At this point, we know E is potentially callable with 0
2688 // arguments and that it returns something of a reasonable type,
2689 // so we can emit a fixit and carry on pretending that E was
2690 // actually a CallExpr.
2691 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
2692 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2693 Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
2694 << (IsCallableWithAppend(E.get())
2695 ? FixItHint::CreateInsertion(ParenInsertionLoc,
2696 "()")
2697 : FixItHint());
2698 if (!IsMV)
2699 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2700
2701 // FIXME: Try this before emitting the fixit, and suppress diagnostics
2702 // while doing so.
2703 E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), std::nullopt,
2705 return true;
2706 }
2707 }
2708 if (!ForceComplain) return false;
2709
2710 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2711 Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
2712 if (!IsMV)
2713 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2714 E = ExprError();
2715 return true;
2716}
2717
2719 if (!Ident_super)
2720 Ident_super = &Context.Idents.get("super");
2721 return Ident_super;
2722}
2723
2726 unsigned OpenMPCaptureLevel) {
2727 auto *CSI = new CapturedRegionScopeInfo(
2728 getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
2729 (getLangOpts().OpenMP && K == CR_OpenMP)
2730 ? OpenMP().getOpenMPNestingLevel()
2731 : 0,
2732 OpenMPCaptureLevel);
2733 CSI->ReturnType = Context.VoidTy;
2734 FunctionScopes.push_back(CSI);
2735 CapturingFunctionScopes++;
2736}
2737
2739 if (FunctionScopes.empty())
2740 return nullptr;
2741
2742 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
2743}
2744
2745const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
2747 return DeleteExprs;
2748}
2749
2751 : S(S), OldFPFeaturesState(S.CurFPFeatures),
2752 OldOverrides(S.FpPragmaStack.CurrentValue),
2753 OldEvalMethod(S.PP.getCurrentFPEvalMethod()),
2754 OldFPPragmaLocation(S.PP.getLastFPEvalPragmaLocation()) {}
2755
2757 S.CurFPFeatures = OldFPFeaturesState;
2758 S.FpPragmaStack.CurrentValue = OldOverrides;
2759 S.PP.setCurrentFPEvalMethod(OldFPPragmaLocation, OldEvalMethod);
2760}
2761
2763 assert(D.getCXXScopeSpec().isSet() &&
2764 "can only be called for qualified names");
2765
2766 auto LR = LookupResult(*this, D.getIdentifier(), D.getBeginLoc(),
2768 DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(),
2769 !D.getDeclSpec().isFriendSpecified());
2770 if (!DC)
2771 return false;
2772
2773 LookupQualifiedName(LR, DC);
2774 bool Result = llvm::all_of(LR, [](Decl *Dcl) {
2775 if (NamedDecl *ND = dyn_cast<NamedDecl>(Dcl)) {
2776 ND = ND->getUnderlyingDecl();
2777 return isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
2778 isa<UsingDecl>(ND);
2779 }
2780 return false;
2781 });
2782 return Result;
2783}
2784
2786 const FunctionEffectsRef &Old, const FunctionEffectsRef &New) {
2787
2789 FunctionEffectsRef::iterator OldEnd = Old.end();
2791 FunctionEffectsRef::iterator NewEnd = New.end();
2792
2793 while (true) {
2794 int cmp = 0;
2795 if (POld == OldEnd) {
2796 if (PNew == NewEnd)
2797 break;
2798 cmp = 1;
2799 } else if (PNew == NewEnd)
2800 cmp = -1;
2801 else {
2802 FunctionEffectWithCondition Old = *POld;
2803 FunctionEffectWithCondition New = *PNew;
2804 if (Old.Effect.kind() < New.Effect.kind())
2805 cmp = -1;
2806 else if (New.Effect.kind() < Old.Effect.kind())
2807 cmp = 1;
2808 else {
2809 cmp = 0;
2810 if (Old.Cond.getCondition() != New.Cond.getCondition()) {
2811 // FIXME: Cases where the expressions are equivalent but
2812 // don't have the same identity.
2813 push_back(FunctionEffectDiff{
2815 Old, New});
2816 }
2817 }
2818 }
2819
2820 if (cmp < 0) {
2821 // removal
2822 FunctionEffectWithCondition Old = *POld;
2823 push_back(FunctionEffectDiff{
2825 ++POld;
2826 } else if (cmp > 0) {
2827 // addition
2828 FunctionEffectWithCondition New = *PNew;
2829 push_back(FunctionEffectDiff{
2831 ++PNew;
2832 } else {
2833 ++POld;
2834 ++PNew;
2835 }
2836 }
2837}
2838
2840 QualType SrcType, const FunctionEffectsRef &SrcFX, QualType DstType,
2841 const FunctionEffectsRef &DstFX) const {
2842
2843 switch (EffectKind) {
2845 // nonallocating can't be added (spoofed) during a conversion, unless we
2846 // have nonblocking.
2847 if (DiffKind == Kind::Added) {
2848 for (const auto &CFE : SrcFX) {
2849 if (CFE.Effect.kind() == FunctionEffect::Kind::NonBlocking)
2850 return false;
2851 }
2852 }
2853 [[fallthrough]];
2855 // nonblocking can't be added (spoofed) during a conversion.
2856 switch (DiffKind) {
2857 case Kind::Added:
2858 return true;
2859 case Kind::Removed:
2860 return false;
2861 case Kind::ConditionMismatch:
2862 // FIXME: Condition mismatches are too coarse right now -- expressions
2863 // which are equivalent but don't have the same identity are detected as
2864 // mismatches. We're going to diagnose those anyhow until expression
2865 // matching is better.
2866 return true;
2867 }
2870 return false;
2872 break;
2873 }
2874 llvm_unreachable("unknown effect kind");
2875}
2876
2878 const FunctionDecl &OldFunction, const FunctionEffectsRef &OldFX,
2879 const FunctionDecl &NewFunction, const FunctionEffectsRef &NewFX) const {
2880 switch (EffectKind) {
2883 // nonblocking/nonallocating can't be removed in a redeclaration.
2884 switch (DiffKind) {
2885 case Kind::Added:
2886 return false; // No diagnostic.
2887 case Kind::Removed:
2888 return true; // Issue diagnostic.
2889 case Kind::ConditionMismatch:
2890 // All these forms of mismatches are diagnosed.
2891 return true;
2892 }
2895 return false;
2897 break;
2898 }
2899 llvm_unreachable("unknown effect kind");
2900}
2901
2904 const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,
2905 const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const {
2906 switch (EffectKind) {
2909 switch (DiffKind) {
2910
2911 // If added on an override, that's fine and not diagnosed.
2912 case Kind::Added:
2913 return OverrideResult::NoAction;
2914
2915 // If missing from an override (removed), propagate from base to derived.
2916 case Kind::Removed:
2917 return OverrideResult::Merge;
2918
2919 // If there's a mismatch involving the effect's polarity or condition,
2920 // issue a warning.
2921 case Kind::ConditionMismatch:
2922 return OverrideResult::Warn;
2923 }
2924
2927 return OverrideResult::NoAction;
2928
2930 break;
2931 }
2932 llvm_unreachable("unknown effect kind");
2933}
Defines the clang::ASTContext interface.
DynTypedNode Node
#define SM(sm)
Definition: Cuda.cpp:83
const Decl * D
Expr * E
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
llvm::DenseSet< const void * > Visited
Definition: HTMLLogger.cpp:146
llvm::MachO::FileType FileType
Definition: MachO.h:46
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
This file declares semantic analysis functions specific to AMDGPU.
uint32_t Id
Definition: SemaARM.cpp:1144
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to AVR.
This file declares semantic analysis functions specific to BPF.
This file declares semantic analysis for CUDA constructs.
This file declares facilities that support code completion.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to M68k.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to MSP430.
This file declares semantic analysis functions specific to NVPTX.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenACC constructs and clauses.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis for expressions involving.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to Swift.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
static void checkEscapingByref(VarDecl *VD, Sema &S)
Definition: Sema.cpp:2223
static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E)
Definition: Sema.cpp:2658
llvm::DenseMap< const CXXRecordDecl *, bool > RecordCompleteMap
Definition: Sema.cpp:1008
static bool IsCallableWithAppend(const Expr *E)
Determine whether the given expression can be called by just putting parentheses after it.
Definition: Sema.cpp:2650
static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD, RecordCompleteMap &MNCComplete)
Returns true, if all methods and nested classes of the given CXXRecordDecl are defined in this transl...
Definition: Sema.cpp:1015
static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads, const SourceLocation FinalNoteLoc)
Give notes for a set of overloads.
Definition: Sema.cpp:2597
static bool isFunctionOrVarDeclExternC(const NamedDecl *ND)
Definition: Sema.cpp:863
static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S)
Definition: Sema.cpp:2257
static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D)
Used to prune the decls of Sema's UnusedFileScopedDecls vector.
Definition: Sema.cpp:802
static void emitCallStackNotes(Sema &S, const FunctionDecl *FD)
Definition: Sema.cpp:1708
static void notePlausibleOverloads(Sema &S, SourceLocation Loc, const UnresolvedSetImpl &Overloads, bool(*IsPlausibleResult)(QualType))
Definition: Sema.cpp:2629
static void checkUndefinedButUsed(Sema &S)
checkUndefinedButUsed - Check for undefined objects with internal linkage or that are inline.
Definition: Sema.cpp:935
static bool IsRecordFullyDefined(const CXXRecordDecl *RD, RecordCompleteMap &RecordsComplete, RecordCompleteMap &MNCComplete)
Returns true, if the given CXXRecordDecl is fully defined in this translation unit,...
Definition: Sema.cpp:1057
Defines the SourceManager interface.
Defines utilities for dealing with stack allocation and stack space.
Allows QualTypes to be sorted and hence used in maps and sets.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition: ASTConsumer.h:34
virtual void CompleteTentativeDefinition(VarDecl *D)
CompleteTentativeDefinition - Callback invoked at the end of a translation unit to notify the consume...
Definition: ASTConsumer.h:104
virtual ASTMutationListener * GetASTMutationListener()
If the consumer is interested in entities getting modified after their initial creation,...
Definition: ASTConsumer.h:129
virtual void CompleteExternalDeclaration(DeclaratorDecl *D)
CompleteExternalDeclaration - Callback invoked at the end of a translation unit to notify the consume...
Definition: ASTConsumer.h:109
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
SourceManager & getSourceManager()
Definition: ASTContext.h:721
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1101
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
CanQualType LongTy
Definition: ASTContext.h:1128
TypedefDecl * getObjCClassDecl() const
Retrieve the typedef declaration corresponding to the predefined Objective-C 'Class' type.
TypedefDecl * getCFConstantStringDecl() const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
TypedefDecl * getObjCSelDecl() const
Retrieve the typedef corresponding to the predefined 'SEL' type in Objective-C.
TypedefDecl * buildImplicitTypedef(QualType T, StringRef Name) const
Create a new implicit TU-level typedef declaration.
TypedefDecl * getBuiltinMSVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_ms_va_list type.
TypedefDecl * getObjCIdDecl() const
Retrieve the typedef corresponding to the predefined id type in Objective-C.
CanQualType FloatTy
Definition: ASTContext.h:1131
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2628
CanQualType DoubleTy
Definition: ASTContext.h:1131
ArrayRef< Decl * > getModuleInitializers(Module *M)
Get the initializations to perform when importing a module, if any.
CanQualType LongDoubleTy
Definition: ASTContext.h:1131
void addComment(const RawComment &RC)
Definition: ASTContext.cpp:328
RecordDecl * buildImplicitRecord(StringRef Name, RecordDecl::TagKind TK=RecordDecl::TagKind::Struct) const
Create a new implicit TU-level CXXRecordDecl or RecordDecl declaration.
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2831
IdentifierTable & Idents
Definition: ASTContext.h:660
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:797
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
PartialDiagnostic::DiagStorageAllocator & getDiagAllocator()
Definition: ASTContext.h:775
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
const TargetInfo * getAuxTargetInfo() const
Definition: ASTContext.h:780
CanQualType UnsignedLongTy
Definition: ASTContext.h:1129
bool hasAnyFunctionEffects() const
Definition: ASTContext.h:2924
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType BoundMemberTy
Definition: ASTContext.h:1147
TypedefDecl * getInt128Decl() const
Retrieve the declaration for the 128-bit signed integer type.
CanQualType IntTy
Definition: ASTContext.h:1128
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
Definition: ASTContext.h:1462
CanQualType OverloadTy
Definition: ASTContext.h:1147
CanQualType OCLClkEventTy
Definition: ASTContext.h:1156
TypedefDecl * getUInt128Decl() const
Retrieve the declaration for the 128-bit unsigned integer type.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:713
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2394
ObjCInterfaceDecl * getObjCProtocolDecl() const
Retrieve the Objective-C class declaration corresponding to the predefined Protocol class.
CanQualType OCLSamplerTy
Definition: ASTContext.h:1156
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
Definition: ASTContext.h:1119
CanQualType UnsignedIntTy
Definition: ASTContext.h:1129
CanQualType OCLReserveIDTy
Definition: ASTContext.h:1157
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
CanQualType OCLQueueTy
Definition: ASTContext.h:1157
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
void setBlockVarCopyInit(const VarDecl *VD, Expr *CopyExpr, bool CanThrow)
Set the copy initialization expression of a block var decl.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1227
QualType getIntPtrType() const
Return a type compatible with "intptr_t" (C99 7.18.1.4), as defined by the target.
IdentifierInfo * getBoolName() const
Retrieve the identifier 'bool'.
Definition: ASTContext.h:1978
CanQualType HalfTy
Definition: ASTContext.h:1143
CanQualType OCLEventTy
Definition: ASTContext.h:1156
void setPrintingPolicy(const clang::PrintingPolicy &Policy)
Definition: ASTContext.h:717
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
A class which contains all the information about a particular captured value.
Definition: Decl.h:4477
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4471
ArrayRef< Capture > captures() const
Definition: Decl.h:4598
SourceLocation getCaretLocation() const
Definition: Decl.h:4544
bool doesNotEscape() const
Definition: Decl.h:4622
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2803
CXXFieldCollector - Used to keep track of CXXFieldDecls during parsing of C++ classes.
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
An iterator over the friend declarations of a class.
Definition: DeclFriend.h:201
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
friend_iterator friend_begin() const
Definition: DeclFriend.h:253
friend_iterator friend_end() const
Definition: DeclFriend.h:257
Represents the body of a CapturedStmt, and serves as its DeclContext.
Definition: Decl.h:4670
ImplicitParamDecl * getContextParam() const
Retrieve the parameter containing captured variables.
Definition: Decl.h:4732
const char * getCastKindName() const
Definition: Expr.h:3546
Abstract interface for a consumer of code-completion information.
The information about the darwin SDK that was used during this compilation.
Definition: DarwinSDKInfo.h:29
decl_iterator - Iterates through the declarations stored within this context.
Definition: DeclBase.h:2307
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
decl_iterator decls_end() const
Definition: DeclBase.h:2352
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1423
decl_iterator decls_begin() const
Definition: DeclBase.cpp:1622
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1051
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1066
T * getAttr() const
Definition: DeclBase.h:580
void addAttr(Attr *A)
Definition: DeclBase.cpp:1013
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:577
bool isInvalidDecl() const
Definition: DeclBase.h:595
SourceLocation getLocation() const
Definition: DeclBase.h:446
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:552
DeclContext * getDeclContext()
Definition: DeclBase.h:455
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:438
bool hasAttr() const
Definition: DeclBase.h:584
The name of a declaration.
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:731
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1271
static SFINAEResponse getDiagnosticSFINAEResponse(unsigned DiagID)
Determines whether the given built-in diagnostic ID is for an error that is suppressed if it occurs d...
static bool isDefaultMappingAsError(unsigned DiagID)
Return true if the specified diagnostic is mapped to errors by default.
static bool isBuiltinNote(unsigned DiagID)
Determine whether the given built-in diagnostic ID is a Note.
@ SFINAE_SubstitutionFailure
The diagnostic should not be reported, but it should cause template argument deduction to fail.
@ SFINAE_Suppress
The diagnostic should be suppressed entirely.
@ SFINAE_AccessControl
The diagnostic is an access-control diagnostic, which will be substitution failures in some contexts ...
@ SFINAE_Report
The diagnostic should be reported.
A little helper class (which is basically a smart pointer that forwards info from DiagnosticsEngine) ...
Definition: Diagnostic.h:1571
const SourceLocation & getLocation() const
Definition: Diagnostic.h:1582
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie)
Definition: Diagnostic.h:889
bool hasErrorOccurred() const
Definition: Diagnostic.h:843
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition: Diagnostic.h:746
void setLastDiagnosticIgnored(bool Ignored)
Pretend that the last diagnostic issued was ignored, so any subsequent notes will be suppressed,...
Definition: Diagnostic.h:761
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition: Diagnostic.h:731
SourceLocation getCurrentDiagLoc() const
Definition: Diagnostic.h:1064
void Clear()
Clear out the current diagnostic.
Definition: Diagnostic.h:982
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:850
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const
Based on the way the client configured the DiagnosticsEngine object, classify the specified diagnosti...
Definition: Diagnostic.h:931
bool EmitCurrentDiagnostic(bool Force=false)
Emit the current diagnostic and clear the diagnostic state.
Definition: Diagnostic.cpp:527
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:690
unsigned getCurrentDiagID() const
Definition: Diagnostic.h:1062
Expr * getCondition() const
Definition: Type.h:4810
RAII object that enters a new expression evaluation context.
This represents one expression.
Definition: Expr.h:110
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3070
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3058
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3066
bool isPRValue() const
Definition: Expr.h:278
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
An abstract interface that should be implemented by external AST sources that also provide informatio...
virtual void updateOutOfDateSelector(Selector Sel)
Load the contents of the global method pool for a given selector if necessary.
Definition: Sema.cpp:2479
virtual void ReadMethodPool(Selector Sel)
Load the contents of the global method pool for a given selector.
Definition: Sema.cpp:2478
virtual void ReadUndefinedButUsed(llvm::MapVector< NamedDecl *, SourceLocation > &Undefined)
Load the set of used but not defined functions or variables with internal linkage,...
Definition: Sema.cpp:2485
~ExternalSemaSource() override
Definition: Sema.cpp:2475
virtual void ReadKnownNamespaces(SmallVectorImpl< NamespaceDecl * > &Namespaces)
Load the set of namespaces that are known to the external source, which will be used during typo corr...
Definition: Sema.cpp:2481
virtual void ReadMismatchingDeleteExpressions(llvm::MapVector< FieldDecl *, llvm::SmallVector< std::pair< SourceLocation, bool >, 4 > > &)
Definition: Sema.cpp:2488
Represents difference between two FPOptions values.
Definition: LangOptions.h:947
Represents a member of a struct/union/class.
Definition: Decl.h:3030
StringRef getName() const
The name of this FileEntry.
Definition: FileEntry.h:61
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
llvm::vfs::FileSystem & getVirtualFileSystem() const
Definition: FileManager.h:251
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
Represents a function declaration or definition.
Definition: Decl.h:1932
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2562
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3224
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3562
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2465
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3558
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2310
const ASTTemplateArgumentListInfo * getTemplateSpecializationArgsAsWritten() const
Retrieve the template argument list as written in the sources, if any.
Definition: Decl.cpp:4174
Support iteration in parallel through a pair of FunctionEffect and EffectConditionExpr containers.
Definition: Type.h:4835
Kind kind() const
The kind of the effect.
Definition: Type.h:4743
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition: Type.h:4882
iterator begin() const
Definition: Type.h:4920
iterator end() const
Definition: Type.h:4921
static FunctionEffectsRef get(QualType QT)
Extract the effects from a Type if it is a function, block, or member function pointer,...
Definition: Type.h:8645
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5002
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4308
QualType getReturnType() const
Definition: Type.h:4630
std::string Sysroot
If non-empty, the directory to use as a "virtual system root" for include paths.
ModuleMap & getModuleMap()
Retrieve the module map.
Definition: HeaderSearch.h:833
HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized.
Definition: HeaderSearch.h:382
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
iterator begin(DeclarationName Name)
Returns an iterator over decls with the name 'Name'.
iterator end()
Returns the end iterator.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3675
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
Represents a C array with an unspecified size.
Definition: Type.h:3751
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type)
@ CMK_HeaderUnit
Compiling a module header unit.
Definition: LangOptions.h:105
@ CMK_ModuleInterface
Compiling a C++ modules interface unit.
Definition: LangOptions.h:108
bool IsHeaderFile
Indicates whether the front-end is explicitly told that the input is a header file (i....
Definition: LangOptions.h:568
CommentOptions CommentOpts
Options for parsing comments.
Definition: LangOptions.h:540
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
void erase(iterator From, iterator To)
iterator begin(Source *source, bool LocalOnly=false)
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition: Lexer.cpp:850
Represents the results of name lookup.
Definition: Lookup.h:46
Encapsulates the data about a macro definition (e.g.
Definition: MacroInfo.h:39
Abstract interface for a module loader.
Definition: ModuleLoader.h:82
bool resolveExports(Module *Mod, bool Complain)
Resolve all of the unresolved exports in the given module.
Definition: ModuleMap.cpp:1399
bool resolveConflicts(Module *Mod, bool Complain)
Resolve all of the unresolved conflicts in the given module.
Definition: ModuleMap.cpp:1426
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Definition: ModuleMap.cpp:1412
Describes a module or submodule.
Definition: Module.h:105
bool isNamedModuleInterfaceHasInit() const
Definition: Module.h:628
bool isInterfaceOrPartition() const
Definition: Module.h:615
llvm::SmallSetVector< Module *, 2 > Imports
The set of modules imported by this module, and on which this module depends.
Definition: Module.h:402
llvm::iterator_range< submodule_iterator > submodules()
Definition: Module.h:783
@ PrivateModuleFragment
This is the private module fragment within some C++ module.
Definition: Module.h:141
@ ExplicitGlobalModuleFragment
This is the explicit Global Module Fragment of a modular TU.
Definition: Module.h:138
An abstract interface that should be implemented by external AST sources that also provide informatio...
static const unsigned NumNSNumberLiteralMethods
Definition: NSAPI.h:191
This represents a decl that may have a name.
Definition: Decl.h:249
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:404
bool isExternallyVisible() const
Definition: Decl.h:408
This represents '#pragma omp target' directive.
Definition: StmtOpenMP.h:3152
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
void addSupport(const llvm::StringMap< bool > &FeaturesMap, const LangOptions &Opts)
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:2982
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3043
decls_iterator decls_begin() const
Definition: ExprCXX.h:3075
decls_iterator decls_end() const
Definition: ExprCXX.h:3078
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition: PPCallbacks.h:36
void Emit(const DiagnosticBuilder &DB) const
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
Definition: Preprocessor.h:137
bool isIncrementalProcessingEnabled() const
Returns true if incremental processing is enabled.
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
LangOptions::FPEvalMethodKind getCurrentFPEvalMethod() const
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Preprocessor.h:295
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with this preprocessor.
void addPPCallbacks(std::unique_ptr< PPCallbacks > C)
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
Module * getCurrentModule()
Retrieves the module that we're currently building, if any.
void setCurrentFPEvalMethod(SourceLocation PragmaLoc, LangOptions::FPEvalMethodKind Val)
FileManager & getFileManager() const
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
HeaderSearch & getHeaderSearchInfo() const
const LangOptions & getLangOpts() const
A (possibly-)qualified type.
Definition: Type.h:941
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition: Type.h:7897
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition: Type.h:7891
QualType getCanonicalType() const
Definition: Type.h:7802
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7844
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7823
bool hasUnsupportedSplice(const SourceManager &SourceMgr) const
@ RCK_OrdinaryC
Any normal C comment.
@ RCK_Invalid
Invalid comment.
@ RCK_OrdinaryBCPL
Any normal BCPL comments.
bool isAlmostTrailingComment() const LLVM_READONLY
Returns true if it is a probable typo:
CommentKind getKind() const LLVM_READONLY
Represents a struct/union/class.
Definition: Decl.h:4145
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:227
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:81
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
Smart pointer class that efficiently represents Objective-C method names.
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
@ K_Immediate
Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
Definition: SemaBase.h:116
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
const LangOptions & getLangOpts() const
Definition: SemaBase.cpp:11
DiagnosticsEngine & getDiagnostics() const
Definition: SemaBase.cpp:10
llvm::DenseMap< CanonicalDeclPtr< const FunctionDecl >, FunctionDeclAndLoc > DeviceKnownEmittedFns
An inverse call graph, mapping known-emitted functions to one of their known-emitted callers (plus th...
Definition: SemaCUDA.h:82
An abstract interface that should be implemented by clients that read ASTs and then require further s...
Definition: SemaConsumer.h:25
void DiagnoseAvailabilityViolations(TranslationUnitDecl *TU)
Definition: SemaHLSL.cpp:887
ObjCMethodDecl * NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]
The Objective-C NSNumber methods used to create NSNumber literals.
Definition: SemaObjC.h:616
void DiagnoseUseOfUnimplementedSelectors()
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: SemaObjC.h:601
void DiagnoseUnterminatedOpenMPDeclareTarget()
Report unterminated 'omp declare target' or 'omp begin declare target' at the end of a compilation un...
void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, const FunctionDecl *Callee, SourceLocation Loc)
Finishes analysis of the deferred functions calls that may be declared as host/nohost during device/h...
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition: Sema.h:1038
sema::DelayedDiagnosticPool * getCurrentPool() const
Returns the current delayed-diagnostics pool.
Definition: Sema.h:1053
Custom deleter to allow FunctionScopeInfos to be kept alive for a short time after they've been poppe...
Definition: Sema.h:694
void operator()(sema::FunctionScopeInfo *Scope) const
Definition: Sema.cpp:2319
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:12138
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:493
SmallVector< DeclaratorDecl *, 4 > ExternalDeclarations
All the external declarations encoutered and used in the TU.
Definition: Sema.h:3115
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:13139
void LoadExternalWeakUndeclaredIdentifiers()
Load weak undeclared identifiers from the external source.
Definition: Sema.cpp:997
bool isExternalWithNoLinkageType(const ValueDecl *VD) const
Determine if VD, which must be a variable or function, is an external symbol that nonetheless can't b...
Definition: Sema.cpp:871
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
Definition: Sema.cpp:2491
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9015
@ NTCUC_BlockCapture
Definition: Sema.h:3651
void addImplicitTypedef(StringRef Name, QualType T)
Definition: Sema.cpp:307
void PrintContextStack()
Definition: Sema.h:13225
SemaOpenMP & OpenMP()
Definition: Sema.h:1179
void CheckDelegatingCtorCycles()
SmallVector< CXXMethodDecl *, 4 > DelayedDllExportMemberFunctions
Definition: Sema.h:5820
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:918
llvm::SmallSetVector< const TypedefNameDecl *, 4 > UnusedLocalTypedefNameCandidates
Set containing all typedefs that are likely unused.
Definition: Sema.h:3097
void emitAndClearUnusedLocalTypedefWarnings()
Definition: Sema.cpp:1088
std::unique_ptr< CXXFieldCollector > FieldCollector
FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
Definition: Sema.h:6042
SemaCUDA & CUDA()
Definition: Sema.h:1124
void Initialize()
Perform initialization that occurs after the parser has been initialized but before it parses anythin...
Definition: Sema.cpp:313
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:900
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2296
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2165
llvm::DenseSet< std::pair< Decl *, unsigned > > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition: Sema.h:13142
PragmaStack< FPOptionsOverride > FpPragmaStack
Definition: Sema.h:1709
void setFunctionHasBranchIntoScope()
Definition: Sema.cpp:2345
virtual void anchor()
This virtual key function only exists to limit the emission of debug info describing the Sema class.
Definition: Sema.cpp:305
void ActOnComment(SourceRange Comment)
Definition: Sema.cpp:2443
void ActOnEndOfTranslationUnit()
ActOnEndOfTranslationUnit - This is called at the very end of the translation unit when EOF is reache...
Definition: Sema.cpp:1172
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1710
void ActOnTranslationUnitScope(Scope *S)
Scope actions.
Definition: Sema.cpp:152
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
IdentifierInfo * getSuperIdentifier() const
Definition: Sema.cpp:2718
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1567
ASTContext & Context
Definition: Sema.h:962
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition: Sema.cpp:626
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:557
SemaObjC & ObjC()
Definition: Sema.h:1164
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain=false, bool(*IsPlausibleResult)(QualType)=nullptr)
Try to recover by turning the given expression into a call.
Definition: Sema.cpp:2673
SemaDiagnosticBuilder::DeferredDiagnosticsType DeviceDeferredDiags
Diagnostics that are emitted only if we discover that the given function must be codegen'ed.
Definition: Sema.h:1094
void CheckDelayedMemberExceptionSpecs()
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1496
UnusedFileScopedDeclsType UnusedFileScopedDecls
The set of file scoped decls seen so far that have not been used and must warn if not used.
Definition: Sema.h:3105
ASTContext & getASTContext() const
Definition: Sema.h:560
SmallVector< std::pair< FunctionDecl *, FunctionDecl * >, 2 > DelayedEquivalentExceptionSpecChecks
All the function redeclarations seen during a class definition that had their exception spec checks d...
Definition: Sema.h:6146
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:702
static const unsigned MaxAlignmentExponent
The maximum alignment, same as in llvm::Value.
Definition: Sema.h:890
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:20286
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:868
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1572
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition: Sema.cpp:2434
unsigned NumSFINAEErrors
The number of SFINAE diagnostics that have been trapped.
Definition: Sema.h:11069
void setFunctionHasIndirectGoto()
Definition: Sema.cpp:2355
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1586
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2184
void EmitCurrentDiagnostic(unsigned DiagID)
Cause the active diagnostic on the DiagosticsEngine to be emitted.
Definition: Sema.cpp:1592
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition: Sema.h:703
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition: Sema.cpp:215
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:84
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2202
void PopCompoundScope()
Definition: Sema.cpp:2334
const LangOptions & getLangOpts() const
Definition: Sema.h:553
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
ASTConsumer & getASTConsumer() const
Definition: Sema.h:561
void * OpaqueParser
Definition: Sema.h:1006
Preprocessor & PP
Definition: Sema.h:961
threadSafety::BeforeSet * ThreadSafetyDeclCache
Definition: Sema.h:999
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition: Sema.cpp:1984
const LangOptions & LangOpts
Definition: Sema.h:960
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2409
static const uint64_t MaximumAlignment
Definition: Sema.h:891
void PerformPendingInstantiations(bool LocalOnly=false)
Performs template instantiation for all implicit template instantiations we have seen until this poin...
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:6046
SemaHLSL & HLSL()
Definition: Sema.h:1129
void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind)
Definition: Sema.cpp:1107
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1829
IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName, unsigned Index)
Invent a new identifier for parameters of abbreviated templates.
Definition: Sema.cpp:118
SmallVector< PendingImplicitInstantiation, 1 > LateParsedInstantiations
Queue of implicit template instantiations that cannot be performed eagerly.
Definition: Sema.h:13523
SmallVector< std::pair< const CXXMethodDecl *, const CXXMethodDecl * >, 2 > DelayedOverridingExceptionSpecChecks
All the overriding functions seen during a class definition that had their exception spec checks dela...
Definition: Sema.h:6138
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1579
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:785
void PushCompoundScope(bool IsStmtExpr)
Definition: Sema.cpp:2329
bool isDeclaratorFunctionLike(Declarator &D)
Determine whether.
Definition: Sema.cpp:2762
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition: Sema.cpp:2148
FunctionEmissionStatus getEmissionStatus(const FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:20204
Module * getCurrentModule() const
Get the module unit whose scope we are currently within.
Definition: Sema.h:9613
static bool isCast(CheckedConversionKind CCK)
Definition: Sema.h:2115
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2365
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1097
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:7465
SemaOpenCL & OpenCL()
Definition: Sema.h:1174
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1547
bool DefineUsedVTables()
Define all of the vtables that have been used in this translation unit and reference any virtual memb...
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13490
SourceManager & getSourceManager() const
Definition: Sema.h:558
bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason)
makeUnavailableInSystemHeader - There is an error in the current context.
Definition: Sema.cpp:579
void getUndefinedButUsed(SmallVectorImpl< std::pair< NamedDecl *, SourceLocation > > &Undefined)
Obtain a sorted list of functions that are undefined but ODR-used.
Definition: Sema.cpp:882
void diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn when implicitly changing function effects.
Definition: Sema.cpp:642
ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value, bool SupressSimplerImplicitMoves=false)
Perform the initialization of a potentially-movable value, which is the result of return value.
Definition: SemaStmt.cpp:3373
void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, SourceLocation IncludeLoc)
Definition: SemaAttr.cpp:449
CanThrowResult canThrow(const Stmt *E)
bool AccessCheckingSFINAE
When true, access checking violations are treated as SFINAE failures rather than hard errors.
Definition: Sema.h:12094
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
@ NTCUK_Destruct
Definition: Sema.h:3665
@ NTCUK_Copy
Definition: Sema.h:3666
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:2196
void * VisContext
VisContext - Manages the stack for #pragma GCC visibility.
Definition: Sema.h:1748
void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel=0)
Definition: Sema.cpp:2724
void emitDeferredDiags()
Definition: Sema.cpp:1880
void setFunctionHasMustTail()
Definition: Sema.cpp:2360
bool WarnedStackExhausted
Definition: Sema.h:925
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:14205
TUFragmentKind
Definition: Sema.h:644
@ Global
The global module fragment, between 'module;' and a module-declaration.
Definition: Sema.h:646
@ Private
The private module fragment, between 'module :private;' and the end of the translation unit.
Definition: Sema.h:653
@ Normal
A normal translation unit fragment.
Definition: Sema.h:650
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2350
RedeclarationKind forRedeclarationInCurContext() const
void ActOnStartOfTranslationUnit()
This is called before the very first declaration in the translation unit is parsed.
Definition: Sema.cpp:1101
ASTConsumer & Consumer
Definition: Sema.h:963
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:4238
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:998
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1690
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:13519
ModuleLoader & getModuleLoader() const
Retrieve the module loader associated with the preprocessor.
Definition: Sema.cpp:88
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
std::pair< SourceLocation, bool > DeleteExprLoc
Definition: Sema.h:604
void RecordParsingTemplateParameterDepth(unsigned Depth)
This is used to inform Sema what the current TemplateParameterDepth is during Parsing.
Definition: Sema.cpp:2209
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8907
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:923
void DiagnoseUnterminatedPragmaAttribute()
Definition: SemaAttr.cpp:1130
void FreeVisContext()
FreeVisContext - Deallocate and null out VisContext.
Definition: SemaAttr.cpp:1235
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
llvm::MapVector< FieldDecl *, DeleteLocs > DeleteExprs
Delete-expressions to be analyzed at the end of translation unit.
Definition: Sema.h:8005
TentativeDefinitionsType TentativeDefinitions
All the tentative definitions encountered in the TU.
Definition: Sema.h:3112
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
DarwinSDKInfo * getDarwinSDKInfoForAvailabilityChecking()
Definition: Sema.cpp:102
const llvm::MapVector< FieldDecl *, DeleteLocs > & getMismatchingDeleteExpressions() const
Retrieves list of suspicious delete-expressions that will be checked at the end of translation unit.
Definition: Sema.cpp:2746
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7946
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1307
SourceManager & SourceMgr
Definition: Sema.h:965
DiagnosticsEngine & Diags
Definition: Sema.h:964
void DiagnoseUnterminatedPragmaAlignPack()
Definition: SemaAttr.cpp:488
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:554
FPOptions CurFPFeatures
Definition: Sema.h:958
LateTemplateParserCleanupCB * LateTemplateParserCleanup
Definition: Sema.h:1005
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9655
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:6076
void PrintStats() const
Print out statistics about the semantic analysis.
Definition: Sema.cpp:618
llvm::BumpPtrAllocator BumpAlloc
Definition: Sema.h:909
sema::LambdaScopeInfo * getEnclosingLambda() const
Get the innermost lambda enclosing the current location, if any.
Definition: Sema.cpp:2392
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:574
void addExternalSource(ExternalSemaSource *E)
Registers an external source.
Definition: Sema.cpp:604
SmallVector< CXXRecordDecl *, 4 > DelayedDllExportClasses
Definition: Sema.h:5819
llvm::MapVector< IdentifierInfo *, llvm::SetVector< WeakInfo, llvm::SmallVector< WeakInfo, 1u >, llvm::SmallDenseSet< WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly > > > WeakUndeclaredIdentifiers
WeakUndeclaredIdentifiers - Identifiers contained in #pragma weak before declared.
Definition: Sema.h:3087
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1967
DeclarationName VAListTagName
VAListTagName - The declaration name corresponding to __va_list_tag.
Definition: Sema.h:1021
sema::FunctionScopeInfo * getEnclosingFunction() const
Definition: Sema.cpp:2380
sema::CapturedRegionScopeInfo * getCurCapturedRegion()
Retrieve the current captured region, if any.
Definition: Sema.cpp:2738
void warnStackExhausted(SourceLocation Loc)
Warn that the stack is nearly exhausted.
Definition: Sema.cpp:566
void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E)
Warn when implicitly casting 0 to nullptr.
Definition: Sema.cpp:654
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
Definition: SemaDecl.cpp:13256
IdentifierResolver IdResolver
Definition: Sema.h:3016
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2341
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:600
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
void setEnd(SourceLocation e)
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3664
bool isUnion() const
Definition: Decl.h:3767
Exposes information about the current target.
Definition: TargetInfo.h:218
virtual bool hasLongDoubleType() const
Determine whether the long double type is supported on this target.
Definition: TargetInfo.h:711
virtual bool hasBitIntType() const
Determine whether the _BitInt type is supported on this target.
Definition: TargetInfo.h:666
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition: TargetInfo.h:655
virtual bool hasFloat16Type() const
Determine whether the _Float16 type is supported on this target.
Definition: TargetInfo.h:696
llvm::StringMap< bool > & getSupportedOpenCLOpts()
Get supported OpenCL extensions and optional core features.
Definition: TargetInfo.h:1765
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition: TargetInfo.h:708
virtual bool hasFPReturn() const
Determine whether return of a floating point value is supported on this target.
Definition: TargetInfo.h:715
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
Definition: TargetInfo.h:1033
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition: TargetInfo.h:693
bool hasAArch64SVETypes() const
Returns whether or not the AArch64 SVE built-in types are available on this target.
Definition: TargetInfo.h:1040
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition: TargetInfo.h:699
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1487
bool hasRISCVVTypes() const
Returns whether or not the RISC-V V built-in types are available on this target.
Definition: TargetInfo.h:1044
The type-property cache.
Definition: Type.cpp:4437
A container of type source information.
Definition: Type.h:7721
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isFloat16Type() const
Definition: Type.h:8328
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8359
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2483
bool isFloat128Type() const
Definition: Type.h:8344
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isBitIntType() const
Definition: Type.h:8241
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2695
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:2296
bool isIbm128Type() const
Definition: Type.h:8348
bool isBFloat16Type() const
Definition: Type.h:8340
bool isStructureOrClassType() const
Definition: Type.cpp:657
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2266
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2497
Linkage getLinkage() const
Determine the linkage of this type.
Definition: Type.cpp:4582
@ STK_FloatingComplex
Definition: Type.h:2677
@ STK_Floating
Definition: Type.h:2675
@ STK_BlockPointer
Definition: Type.h:2670
@ STK_Bool
Definition: Type.h:2673
@ STK_ObjCObjectPointer
Definition: Type.h:2671
@ STK_FixedPoint
Definition: Type.h:2678
@ STK_IntegralComplex
Definition: Type.h:2676
@ STK_CPointer
Definition: Type.h:2669
@ STK_Integral
Definition: Type.h:2674
@ STK_MemberPointer
Definition: Type.h:2672
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
bool isNullPtrType() const
Definition: Type.h:8352
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4693
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3409
Simple class containing the result of Sema::CorrectTypo.
A set of unresolved declarations.
Definition: UnresolvedSet.h:62
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:92
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:35
A set of unresolved declarations.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
void setType(QualType newType)
Definition: Decl.h:679
QualType getType() const
Definition: Decl.h:678
Represents a variable declaration or definition.
Definition: Decl.h:879
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2775
void setEscapingByref()
Definition: Decl.h:1552
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2348
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1290
const Expr * getInit() const
Definition: Decl.h:1316
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2327
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1243
bool isEscapingByref() const
Indicates the capture is a __block variable that is captured by a block that can potentially escape (...
Definition: Decl.cpp:2663
Declaration of a variable template.
void IssueWarnings(Policy P, FunctionScopeInfo *fscope, const Decl *D, QualType BlockType)
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:784
Retains information about a captured region.
Definition: ScopeInfo.h:810
Contains information about the compound statement currently being parsed.
Definition: ScopeInfo.h:67
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
SmallVector< CompoundScopeInfo, 4 > CompoundScopes
The stack of currently active compound statement scopes in the function.
Definition: ScopeInfo.h:228
llvm::SmallPtrSet< const BlockDecl *, 1 > Blocks
The set of blocks that are introduced in this function.
Definition: ScopeInfo.h:231
llvm::TinyPtrVector< VarDecl * > ByrefBlockVars
The set of __block variables that are introduced in this function.
Definition: ScopeInfo.h:234
void FileChanged(SourceLocation Loc, FileChangeReason Reason, SrcMgr::CharacteristicKind FileType, FileID PrevFID) override
Callback invoked whenever a source file is entered or exited.
Definition: Sema.cpp:170
Defines the clang::TargetInfo interface.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
Definition: SourceManager.h:81
void threadSafetyCleanup(BeforeSet *Cache)
The JSON file list parser is used to communicate input to InstallAPI.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus11
Definition: LangStandard.h:57
@ ExpectedVariableOrFunction
Definition: ParsedAttr.h:1093
@ Nullable
Values of this type can be null.
@ NonNull
Values of this type can never be null.
Expected< std::optional< DarwinSDKInfo > > parseDarwinSDKInfo(llvm::vfs::FileSystem &VFS, StringRef SDKRootPath)
Parse the SDK information from the SDKSettings.json file.
CapturedRegionKind
The different kinds of captured statement.
Definition: CapturedStmt.h:16
@ CR_OpenMP
Definition: CapturedStmt.h:19
@ SC_Register
Definition: Specifiers.h:257
@ SC_Static
Definition: Specifiers.h:252
@ Result
The result type of a method or function.
@ Class
The "class" keyword.
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
TranslationUnitKind
Describes the kind of translation unit being processed.
Definition: LangOptions.h:1065
@ TU_ClangModule
The translation unit is a clang module.
Definition: LangOptions.h:1074
@ TU_Prefix
The translation unit is a prefix to a translation unit, and is not complete.
Definition: LangOptions.h:1071
ComparisonCategoryType
An enumeration representing the different comparison categories types.
void FormatASTNodeDiagnosticArgument(DiagnosticsEngine::ArgumentKind Kind, intptr_t Val, StringRef Modifier, StringRef Argument, ArrayRef< DiagnosticsEngine::ArgumentValue > PrevArgs, SmallVectorImpl< char > &Output, void *Cookie, ArrayRef< intptr_t > QualTypeVals)
DiagnosticsEngine argument formatting function for diagnostics that involve AST nodes.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const FunctionProtoType * T
bool isExternalFormalLinkage(Linkage L)
Definition: Linkage.h:117
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
bool IsArmStreamingFunction(const FunctionDecl *FD, bool IncludeLocallyStreaming)
Returns whether the given FunctionDecl has an __arm[_locally]_streaming attribute.
Definition: Decl.cpp:5759
void runWithSufficientStackSpace(llvm::function_ref< void()> Diag, llvm::function_ref< void()> Fn)
Run a given function on a stack with "sufficient" space.
Definition: Stack.h:40
bool isExternallyVisible(Linkage L)
Definition: Linkage.h:90
CheckedConversionKind
The kind of conversion being performed.
Definition: Sema.h:414
unsigned long uint64_t
#define false
Definition: stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
bool shouldDiagnoseConversion(QualType SrcType, const FunctionEffectsRef &SrcFX, QualType DstType, const FunctionEffectsRef &DstFX) const
Return true if adding or removing the effect as part of a type conversion should generate a diagnosti...
Definition: Sema.cpp:2839
OverrideResult
Describes the result of effects differing between a base class's virtual method and an overriding met...
Definition: Sema.h:458
OverrideResult shouldDiagnoseMethodOverride(const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX, const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const
Return true if adding or removing the effect in a C++ virtual method override should generate a diagn...
Definition: Sema.cpp:2903
bool shouldDiagnoseRedeclaration(const FunctionDecl &OldFunction, const FunctionEffectsRef &OldFX, const FunctionDecl &NewFunction, const FunctionEffectsRef &NewFX) const
Return true if adding or removing the effect in a redeclaration should generate a diagnostic.
Definition: Sema.cpp:2877
FunctionEffectDifferences(const FunctionEffectsRef &Old, const FunctionEffectsRef &New)
Caller should short-circuit by checking for equality first.
Definition: Sema.cpp:2785
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition: Type.h:4820
EffectConditionExpr Cond
Definition: Type.h:4822
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
unsigned Bool
Whether we can use 'bool' rather than '_Bool' (even if the language doesn't actually have 'bool',...
unsigned EntireContentsOfLargeArray
Whether to print the entire array initializers, especially on non-type template parameters,...
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:12761