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