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