clang 20.0.0git
SemaExpr.cpp
Go to the documentation of this file.
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
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 semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "TreeTransform.h"
15#include "UsedDeclVisitor.h"
18#include "clang/AST/ASTLambda.h"
21#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
32#include "clang/AST/Type.h"
33#include "clang/AST/TypeLoc.h"
44#include "clang/Sema/DeclSpec.h"
49#include "clang/Sema/Lookup.h"
50#include "clang/Sema/Overload.h"
52#include "clang/Sema/Scope.h"
54#include "clang/Sema/SemaCUDA.h"
57#include "clang/Sema/SemaObjC.h"
60#include "clang/Sema/Template.h"
61#include "llvm/ADT/STLExtras.h"
62#include "llvm/ADT/STLForwardCompat.h"
63#include "llvm/ADT/StringExtras.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/ConvertUTF.h"
66#include "llvm/Support/SaveAndRestore.h"
67#include "llvm/Support/TypeSize.h"
68#include <optional>
69
70using namespace clang;
71using namespace sema;
72
73bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
74 // See if this is an auto-typed variable whose initializer we are parsing.
75 if (ParsingInitForAutoVars.count(D))
76 return false;
77
78 // See if this is a deleted function.
79 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
80 if (FD->isDeleted())
81 return false;
82
83 // If the function has a deduced return type, and we can't deduce it,
84 // then we can't use it either.
85 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
86 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
87 return false;
88
89 // See if this is an aligned allocation/deallocation function that is
90 // unavailable.
91 if (TreatUnavailableAsInvalid &&
93 return false;
94 }
95
96 // See if this function is unavailable.
97 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
98 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
99 return false;
100
101 if (isa<UnresolvedUsingIfExistsDecl>(D))
102 return false;
103
104 return true;
105}
106
108 // Warn if this is used but marked unused.
109 if (const auto *A = D->getAttr<UnusedAttr>()) {
110 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
111 // should diagnose them.
112 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
113 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
114 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
115 if (DC && !DC->hasAttr<UnusedAttr>())
116 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
117 }
118 }
119}
120
122 assert(Decl && Decl->isDeleted());
123
124 if (Decl->isDefaulted()) {
125 // If the method was explicitly defaulted, point at that declaration.
126 if (!Decl->isImplicit())
127 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
128
129 // Try to diagnose why this special member function was implicitly
130 // deleted. This might fail, if that reason no longer applies.
132 return;
133 }
134
135 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
136 if (Ctor && Ctor->isInheritingConstructor())
138
139 Diag(Decl->getLocation(), diag::note_availability_specified_here)
140 << Decl << 1;
141}
142
143/// Determine whether a FunctionDecl was ever declared with an
144/// explicit storage class.
146 for (auto *I : D->redecls()) {
147 if (I->getStorageClass() != SC_None)
148 return true;
149 }
150 return false;
151}
152
153/// Check whether we're in an extern inline function and referring to a
154/// variable or function with internal linkage (C11 6.7.4p3).
155///
156/// This is only a warning because we used to silently accept this code, but
157/// in many cases it will not behave correctly. This is not enabled in C++ mode
158/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
159/// and so while there may still be user mistakes, most of the time we can't
160/// prove that there are errors.
162 const NamedDecl *D,
164 // This is disabled under C++; there are too many ways for this to fire in
165 // contexts where the warning is a false positive, or where it is technically
166 // correct but benign.
167 if (S.getLangOpts().CPlusPlus)
168 return;
169
170 // Check if this is an inlined function or method.
171 FunctionDecl *Current = S.getCurFunctionDecl();
172 if (!Current)
173 return;
174 if (!Current->isInlined())
175 return;
176 if (!Current->isExternallyVisible())
177 return;
178
179 // Check if the decl has internal linkage.
180 if (D->getFormalLinkage() != Linkage::Internal)
181 return;
182
183 // Downgrade from ExtWarn to Extension if
184 // (1) the supposedly external inline function is in the main file,
185 // and probably won't be included anywhere else.
186 // (2) the thing we're referencing is a pure function.
187 // (3) the thing we're referencing is another inline function.
188 // This last can give us false negatives, but it's better than warning on
189 // wrappers for simple C library functions.
190 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
191 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
192 if (!DowngradeWarning && UsedFn)
193 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
194
195 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
196 : diag::ext_internal_in_extern_inline)
197 << /*IsVar=*/!UsedFn << D;
198
200
201 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
202 << D;
203}
204
206 const FunctionDecl *First = Cur->getFirstDecl();
207
208 // Suggest "static" on the function, if possible.
210 SourceLocation DeclBegin = First->getSourceRange().getBegin();
211 Diag(DeclBegin, diag::note_convert_inline_to_static)
212 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
213 }
214}
215
217 const ObjCInterfaceDecl *UnknownObjCClass,
218 bool ObjCPropertyAccess,
219 bool AvoidPartialAvailabilityChecks,
220 ObjCInterfaceDecl *ClassReceiver,
221 bool SkipTrailingRequiresClause) {
222 SourceLocation Loc = Locs.front();
223 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
224 // If there were any diagnostics suppressed by template argument deduction,
225 // emit them now.
226 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
227 if (Pos != SuppressedDiagnostics.end()) {
228 for (const PartialDiagnosticAt &Suppressed : Pos->second)
229 Diag(Suppressed.first, Suppressed.second);
230
231 // Clear out the list of suppressed diagnostics, so that we don't emit
232 // them again for this specialization. However, we don't obsolete this
233 // entry from the table, because we want to avoid ever emitting these
234 // diagnostics again.
235 Pos->second.clear();
236 }
237
238 // C++ [basic.start.main]p3:
239 // The function 'main' shall not be used within a program.
240 if (cast<FunctionDecl>(D)->isMain())
241 Diag(Loc, diag::ext_main_used);
242
243 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
244 }
245
246 // See if this is an auto-typed variable whose initializer we are parsing.
247 if (ParsingInitForAutoVars.count(D)) {
248 if (isa<BindingDecl>(D)) {
249 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
250 << D->getDeclName();
251 } else {
252 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
253 << D->getDeclName() << cast<VarDecl>(D)->getType();
254 }
255 return true;
256 }
257
258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
259 // See if this is a deleted function.
260 if (FD->isDeleted()) {
261 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
262 if (Ctor && Ctor->isInheritingConstructor())
263 Diag(Loc, diag::err_deleted_inherited_ctor_use)
264 << Ctor->getParent()
265 << Ctor->getInheritedConstructor().getConstructor()->getParent();
266 else {
267 StringLiteral *Msg = FD->getDeletedMessage();
268 Diag(Loc, diag::err_deleted_function_use)
269 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
270 }
272 return true;
273 }
274
275 // [expr.prim.id]p4
276 // A program that refers explicitly or implicitly to a function with a
277 // trailing requires-clause whose constraint-expression is not satisfied,
278 // other than to declare it, is ill-formed. [...]
279 //
280 // See if this is a function with constraints that need to be satisfied.
281 // Check this before deducing the return type, as it might instantiate the
282 // definition.
283 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
284 ConstraintSatisfaction Satisfaction;
285 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
286 /*ForOverloadResolution*/ true))
287 // A diagnostic will have already been generated (non-constant
288 // constraint expression, for example)
289 return true;
290 if (!Satisfaction.IsSatisfied) {
291 Diag(Loc,
292 diag::err_reference_to_function_with_unsatisfied_constraints)
293 << D;
294 DiagnoseUnsatisfiedConstraint(Satisfaction);
295 return true;
296 }
297 }
298
299 // If the function has a deduced return type, and we can't deduce it,
300 // then we can't use it either.
301 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
303 return true;
304
305 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
306 return true;
307
308 }
309
310 if (auto *Concept = dyn_cast<ConceptDecl>(D);
312 return true;
313
314 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
315 // Lambdas are only default-constructible or assignable in C++2a onwards.
316 if (MD->getParent()->isLambda() &&
317 ((isa<CXXConstructorDecl>(MD) &&
318 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
319 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
320 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
321 << !isa<CXXConstructorDecl>(MD);
322 }
323 }
324
325 auto getReferencedObjCProp = [](const NamedDecl *D) ->
326 const ObjCPropertyDecl * {
327 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
328 return MD->findPropertyDecl();
329 return nullptr;
330 };
331 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
333 return true;
335 return true;
336 }
337
338 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
339 // Only the variables omp_in and omp_out are allowed in the combiner.
340 // Only the variables omp_priv and omp_orig are allowed in the
341 // initializer-clause.
342 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
343 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
344 isa<VarDecl>(D)) {
345 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
347 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348 return true;
349 }
350
351 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
352 // List-items in map clauses on this construct may only refer to the declared
353 // variable var and entities that could be referenced by a procedure defined
354 // at the same location.
355 // [OpenMP 5.2] Also allow iterator declared variables.
356 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
357 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
358 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
360 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
361 return true;
362 }
363
364 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
365 Diag(Loc, diag::err_use_of_empty_using_if_exists);
366 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
367 return true;
368 }
369
370 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
371 AvoidPartialAvailabilityChecks, ClassReceiver);
372
373 DiagnoseUnusedOfDecl(*this, D, Loc);
374
376
377 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
378 if (getLangOpts().getFPEvalMethod() !=
381 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
382 Diag(D->getLocation(),
383 diag::err_type_available_only_in_default_eval_method)
384 << D->getName();
385 }
386
387 if (auto *VD = dyn_cast<ValueDecl>(D))
388 checkTypeSupport(VD->getType(), Loc, VD);
389
390 if (LangOpts.SYCLIsDevice ||
391 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
393 if (const auto *VD = dyn_cast<VarDecl>(D))
394 if (VD->getTLSKind() != VarDecl::TLS_None)
395 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
396 }
397
398 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
400 // C++ [expr.prim.req.nested] p3
401 // A local parameter shall only appear as an unevaluated operand
402 // (Clause 8) within the constraint-expression.
403 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
404 << D;
405 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
406 return true;
407 }
408
409 return false;
410}
411
413 ArrayRef<Expr *> Args) {
414 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
415 if (!Attr)
416 return;
417
418 // The number of formal parameters of the declaration.
419 unsigned NumFormalParams;
420
421 // The kind of declaration. This is also an index into a %select in
422 // the diagnostic.
423 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
424
425 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
426 NumFormalParams = MD->param_size();
427 CalleeKind = CK_Method;
428 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
429 NumFormalParams = FD->param_size();
430 CalleeKind = CK_Function;
431 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
432 QualType Ty = VD->getType();
433 const FunctionType *Fn = nullptr;
434 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
435 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
436 if (!Fn)
437 return;
438 CalleeKind = CK_Function;
439 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
440 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
441 CalleeKind = CK_Block;
442 } else {
443 return;
444 }
445
446 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
447 NumFormalParams = proto->getNumParams();
448 else
449 NumFormalParams = 0;
450 } else {
451 return;
452 }
453
454 // "NullPos" is the number of formal parameters at the end which
455 // effectively count as part of the variadic arguments. This is
456 // useful if you would prefer to not have *any* formal parameters,
457 // but the language forces you to have at least one.
458 unsigned NullPos = Attr->getNullPos();
459 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
460 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
461
462 // The number of arguments which should follow the sentinel.
463 unsigned NumArgsAfterSentinel = Attr->getSentinel();
464
465 // If there aren't enough arguments for all the formal parameters,
466 // the sentinel, and the args after the sentinel, complain.
467 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
468 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
469 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
470 return;
471 }
472
473 // Otherwise, find the sentinel expression.
474 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
475 if (!SentinelExpr)
476 return;
477 if (SentinelExpr->isValueDependent())
478 return;
479 if (Context.isSentinelNullExpr(SentinelExpr))
480 return;
481
482 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
483 // or 'NULL' if those are actually defined in the context. Only use
484 // 'nil' for ObjC methods, where it's much more likely that the
485 // variadic arguments form a list of object pointers.
486 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
487 std::string NullValue;
488 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
489 NullValue = "nil";
490 else if (getLangOpts().CPlusPlus11)
491 NullValue = "nullptr";
492 else if (PP.isMacroDefined("NULL"))
493 NullValue = "NULL";
494 else
495 NullValue = "(void*) 0";
496
497 if (MissingNilLoc.isInvalid())
498 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
499 else
500 Diag(MissingNilLoc, diag::warn_missing_sentinel)
501 << int(CalleeKind)
502 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
503 Diag(D->getLocation(), diag::note_sentinel_here)
504 << int(CalleeKind) << Attr->getRange();
505}
506
508 return E ? E->getSourceRange() : SourceRange();
509}
510
511//===----------------------------------------------------------------------===//
512// Standard Promotions and Conversions
513//===----------------------------------------------------------------------===//
514
515/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
517 // Handle any placeholder expressions which made it here.
518 if (E->hasPlaceholderType()) {
520 if (result.isInvalid()) return ExprError();
521 E = result.get();
522 }
523
524 QualType Ty = E->getType();
525 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
526
527 if (Ty->isFunctionType()) {
528 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
529 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
531 return ExprError();
532
534 CK_FunctionToPointerDecay).get();
535 } else if (Ty->isArrayType()) {
536 // In C90 mode, arrays only promote to pointers if the array expression is
537 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
538 // type 'array of type' is converted to an expression that has type 'pointer
539 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
540 // that has type 'array of type' ...". The relevant change is "an lvalue"
541 // (C90) to "an expression" (C99).
542 //
543 // C++ 4.2p1:
544 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
545 // T" can be converted to an rvalue of type "pointer to T".
546 //
547 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
549 CK_ArrayToPointerDecay);
550 if (Res.isInvalid())
551 return ExprError();
552 E = Res.get();
553 }
554 }
555 return E;
556}
557
559 // Check to see if we are dereferencing a null pointer. If so,
560 // and if not volatile-qualified, this is undefined behavior that the
561 // optimizer will delete, so warn about it. People sometimes try to use this
562 // to get a deterministic trap and are surprised by clang's behavior. This
563 // only handles the pattern "*null", which is a very syntactic check.
564 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
565 if (UO && UO->getOpcode() == UO_Deref &&
566 UO->getSubExpr()->getType()->isPointerType()) {
567 const LangAS AS =
568 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
569 if ((!isTargetAddressSpace(AS) ||
570 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
571 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
573 !UO->getType().isVolatileQualified()) {
574 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
575 S.PDiag(diag::warn_indirection_through_null)
576 << UO->getSubExpr()->getSourceRange());
577 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
578 S.PDiag(diag::note_indirection_through_null));
579 }
580 }
581}
582
583static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
584 SourceLocation AssignLoc,
585 const Expr* RHS) {
586 const ObjCIvarDecl *IV = OIRE->getDecl();
587 if (!IV)
588 return;
589
590 DeclarationName MemberName = IV->getDeclName();
592 if (!Member || !Member->isStr("isa"))
593 return;
594
595 const Expr *Base = OIRE->getBase();
596 QualType BaseType = Base->getType();
597 if (OIRE->isArrow())
598 BaseType = BaseType->getPointeeType();
599 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
600 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
601 ObjCInterfaceDecl *ClassDeclared = nullptr;
602 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
603 if (!ClassDeclared->getSuperClass()
604 && (*ClassDeclared->ivar_begin()) == IV) {
605 if (RHS) {
606 NamedDecl *ObjectSetClass =
608 &S.Context.Idents.get("object_setClass"),
610 if (ObjectSetClass) {
611 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
612 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
614 "object_setClass(")
616 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
617 << FixItHint::CreateInsertion(RHSLocEnd, ")");
618 }
619 else
620 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
621 } else {
622 NamedDecl *ObjectGetClass =
624 &S.Context.Idents.get("object_getClass"),
626 if (ObjectGetClass)
627 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
629 "object_getClass(")
631 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
632 else
633 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
634 }
635 S.Diag(IV->getLocation(), diag::note_ivar_decl);
636 }
637 }
638}
639
641 // Handle any placeholder expressions which made it here.
642 if (E->hasPlaceholderType()) {
644 if (result.isInvalid()) return ExprError();
645 E = result.get();
646 }
647
648 // C++ [conv.lval]p1:
649 // A glvalue of a non-function, non-array type T can be
650 // converted to a prvalue.
651 if (!E->isGLValue()) return E;
652
653 QualType T = E->getType();
654 assert(!T.isNull() && "r-value conversion on typeless expression?");
655
656 // lvalue-to-rvalue conversion cannot be applied to types that decay to
657 // pointers (i.e. function or array types).
659 return E;
660
661 // We don't want to throw lvalue-to-rvalue casts on top of
662 // expressions of certain types in C++.
663 if (getLangOpts().CPlusPlus) {
664 if (T == Context.OverloadTy || T->isRecordType() ||
665 (T->isDependentType() && !T->isAnyPointerType() &&
667 return E;
668 }
669
670 // The C standard is actually really unclear on this point, and
671 // DR106 tells us what the result should be but not why. It's
672 // generally best to say that void types just doesn't undergo
673 // lvalue-to-rvalue at all. Note that expressions of unqualified
674 // 'void' type are never l-values, but qualified void can be.
675 if (T->isVoidType())
676 return E;
677
678 // OpenCL usually rejects direct accesses to values of 'half' type.
679 if (getLangOpts().OpenCL &&
680 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
681 T->isHalfType()) {
682 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
683 << 0 << T;
684 return ExprError();
685 }
686
688 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
689 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
690 &Context.Idents.get("object_getClass"),
692 if (ObjectGetClass)
693 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
694 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
696 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
697 else
698 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
699 }
700 else if (const ObjCIvarRefExpr *OIRE =
701 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
702 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
703
704 // C++ [conv.lval]p1:
705 // [...] If T is a non-class type, the type of the prvalue is the
706 // cv-unqualified version of T. Otherwise, the type of the
707 // rvalue is T.
708 //
709 // C99 6.3.2.1p2:
710 // If the lvalue has qualified type, the value has the unqualified
711 // version of the type of the lvalue; otherwise, the value has the
712 // type of the lvalue.
713 if (T.hasQualifiers())
714 T = T.getUnqualifiedType();
715
716 // Under the MS ABI, lock down the inheritance model now.
717 if (T->isMemberPointerType() &&
719 (void)isCompleteType(E->getExprLoc(), T);
720
722 if (Res.isInvalid())
723 return Res;
724 E = Res.get();
725
726 // Loading a __weak object implicitly retains the value, so we need a cleanup to
727 // balance that.
730
733
734 // C++ [conv.lval]p3:
735 // If T is cv std::nullptr_t, the result is a null pointer constant.
736 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
737 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
739
740 // C11 6.3.2.1p2:
741 // ... if the lvalue has atomic type, the value has the non-atomic version
742 // of the type of the lvalue ...
743 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
744 T = Atomic->getValueType().getUnqualifiedType();
745 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
746 nullptr, VK_PRValue, FPOptionsOverride());
747 }
748
749 return Res;
750}
751
754 if (Res.isInvalid())
755 return ExprError();
756 Res = DefaultLvalueConversion(Res.get());
757 if (Res.isInvalid())
758 return ExprError();
759 return Res;
760}
761
763 QualType Ty = E->getType();
764 ExprResult Res = E;
765 // Only do implicit cast for a function type, but not for a pointer
766 // to function type.
767 if (Ty->isFunctionType()) {
769 CK_FunctionToPointerDecay);
770 if (Res.isInvalid())
771 return ExprError();
772 }
773 Res = DefaultLvalueConversion(Res.get());
774 if (Res.isInvalid())
775 return ExprError();
776 return Res.get();
777}
778
779/// UsualUnaryConversions - Performs various conversions that are common to most
780/// operators (C99 6.3). The conversions of array and function types are
781/// sometimes suppressed. For example, the array->pointer conversion doesn't
782/// apply if the array is an argument to the sizeof or address (&) operators.
783/// In these instances, this routine should *not* be called.
785 // First, convert to an r-value.
787 if (Res.isInvalid())
788 return ExprError();
789 E = Res.get();
790
791 QualType Ty = E->getType();
792 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
793
794 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
795 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
796 (getLangOpts().getFPEvalMethod() !=
799 switch (EvalMethod) {
800 default:
801 llvm_unreachable("Unrecognized float evaluation method");
802 break;
804 llvm_unreachable("Float evaluation method should be set by now");
805 break;
808 // Widen the expression to double.
809 return Ty->isComplexType()
812 CK_FloatingComplexCast)
813 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
814 break;
817 // Widen the expression to long double.
818 return Ty->isComplexType()
821 CK_FloatingComplexCast)
823 CK_FloatingCast);
824 break;
825 }
826 }
827
828 // Half FP have to be promoted to float unless it is natively supported
829 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
830 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
831
832 // Try to perform integral promotions if the object has a theoretically
833 // promotable type.
835 // C99 6.3.1.1p2:
836 //
837 // The following may be used in an expression wherever an int or
838 // unsigned int may be used:
839 // - an object or expression with an integer type whose integer
840 // conversion rank is less than or equal to the rank of int
841 // and unsigned int.
842 // - A bit-field of type _Bool, int, signed int, or unsigned int.
843 //
844 // If an int can represent all values of the original type, the
845 // value is converted to an int; otherwise, it is converted to an
846 // unsigned int. These are called the integer promotions. All
847 // other types are unchanged by the integer promotions.
848
850 if (!PTy.isNull()) {
851 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
852 return E;
853 }
856 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
857 return E;
858 }
859 }
860 return E;
861}
862
863/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
864/// do not have a prototype. Arguments that have type float or __fp16
865/// are promoted to double. All other argument types are converted by
866/// UsualUnaryConversions().
868 QualType Ty = E->getType();
869 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
870
872 if (Res.isInvalid())
873 return ExprError();
874 E = Res.get();
875
876 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
877 // promote to double.
878 // Note that default argument promotion applies only to float (and
879 // half/fp16); it does not apply to _Float16.
880 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
881 if (BTy && (BTy->getKind() == BuiltinType::Half ||
882 BTy->getKind() == BuiltinType::Float)) {
883 if (getLangOpts().OpenCL &&
884 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
885 if (BTy->getKind() == BuiltinType::Half) {
886 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
887 }
888 } else {
889 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
890 }
891 }
892 if (BTy &&
893 getLangOpts().getExtendIntArgs() ==
898 E = (Ty->isUnsignedIntegerType())
899 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
900 .get()
901 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
903 "Unexpected typesize for LongLongTy");
904 }
905
906 // C++ performs lvalue-to-rvalue conversion as a default argument
907 // promotion, even on class types, but note:
908 // C++11 [conv.lval]p2:
909 // When an lvalue-to-rvalue conversion occurs in an unevaluated
910 // operand or a subexpression thereof the value contained in the
911 // referenced object is not accessed. Otherwise, if the glvalue
912 // has a class type, the conversion copy-initializes a temporary
913 // of type T from the glvalue and the result of the conversion
914 // is a prvalue for the temporary.
915 // FIXME: add some way to gate this entire thing for correctness in
916 // potentially potentially evaluated contexts.
920 E->getExprLoc(), E);
921 if (Temp.isInvalid())
922 return ExprError();
923 E = Temp.get();
924 }
925
926 // C++ [expr.call]p7, per CWG722:
927 // An argument that has (possibly cv-qualified) type std::nullptr_t is
928 // converted to void* ([conv.ptr]).
929 // (This does not apply to C23 nullptr)
931 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
932
933 return E;
934}
935
937 if (Ty->isIncompleteType()) {
938 // C++11 [expr.call]p7:
939 // After these conversions, if the argument does not have arithmetic,
940 // enumeration, pointer, pointer to member, or class type, the program
941 // is ill-formed.
942 //
943 // Since we've already performed null pointer conversion, array-to-pointer
944 // decay and function-to-pointer decay, the only such type in C++ is cv
945 // void. This also handles initializer lists as variadic arguments.
946 if (Ty->isVoidType())
947 return VAK_Invalid;
948
949 if (Ty->isObjCObjectType())
950 return VAK_Invalid;
951 return VAK_Valid;
952 }
953
955 return VAK_Invalid;
956
957 if (Context.getTargetInfo().getTriple().isWasm() &&
959 return VAK_Invalid;
960 }
961
962 if (Ty.isCXX98PODType(Context))
963 return VAK_Valid;
964
965 // C++11 [expr.call]p7:
966 // Passing a potentially-evaluated argument of class type (Clause 9)
967 // having a non-trivial copy constructor, a non-trivial move constructor,
968 // or a non-trivial destructor, with no corresponding parameter,
969 // is conditionally-supported with implementation-defined semantics.
972 if (!Record->hasNonTrivialCopyConstructor() &&
973 !Record->hasNonTrivialMoveConstructor() &&
974 !Record->hasNonTrivialDestructor())
975 return VAK_ValidInCXX11;
976
977 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
978 return VAK_Valid;
979
980 if (Ty->isObjCObjectType())
981 return VAK_Invalid;
982
983 if (getLangOpts().MSVCCompat)
984 return VAK_MSVCUndefined;
985
986 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
987 // permitted to reject them. We should consider doing so.
988 return VAK_Undefined;
989}
990
992 // Don't allow one to pass an Objective-C interface to a vararg.
993 const QualType &Ty = E->getType();
995
996 // Complain about passing non-POD types through varargs.
997 switch (VAK) {
998 case VAK_ValidInCXX11:
1000 E->getBeginLoc(), nullptr,
1001 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1002 [[fallthrough]];
1003 case VAK_Valid:
1004 if (Ty->isRecordType()) {
1005 // This is unlikely to be what the user intended. If the class has a
1006 // 'c_str' member function, the user probably meant to call that.
1007 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1008 PDiag(diag::warn_pass_class_arg_to_vararg)
1009 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1010 }
1011 break;
1012
1013 case VAK_Undefined:
1014 case VAK_MSVCUndefined:
1015 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1016 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1017 << getLangOpts().CPlusPlus11 << Ty << CT);
1018 break;
1019
1020 case VAK_Invalid:
1022 Diag(E->getBeginLoc(),
1023 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1024 << Ty << CT;
1025 else if (Ty->isObjCObjectType())
1026 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1027 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1028 << Ty << CT);
1029 else
1030 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1031 << isa<InitListExpr>(E) << Ty << CT;
1032 break;
1033 }
1034}
1035
1037 FunctionDecl *FDecl) {
1038 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1039 // Strip the unbridged-cast placeholder expression off, if applicable.
1040 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1041 (CT == VariadicMethod ||
1042 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1044
1045 // Otherwise, do normal placeholder checking.
1046 } else {
1048 if (ExprRes.isInvalid())
1049 return ExprError();
1050 E = ExprRes.get();
1051 }
1052 }
1053
1055 if (ExprRes.isInvalid())
1056 return ExprError();
1057
1058 // Copy blocks to the heap.
1059 if (ExprRes.get()->getType()->isBlockPointerType())
1060 maybeExtendBlockObject(ExprRes);
1061
1062 E = ExprRes.get();
1063
1064 // Diagnostics regarding non-POD argument types are
1065 // emitted along with format string checking in Sema::CheckFunctionCall().
1067 // Turn this into a trap.
1068 CXXScopeSpec SS;
1069 SourceLocation TemplateKWLoc;
1070 UnqualifiedId Name;
1071 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1072 E->getBeginLoc());
1073 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1074 /*HasTrailingLParen=*/true,
1075 /*IsAddressOfOperand=*/false);
1076 if (TrapFn.isInvalid())
1077 return ExprError();
1078
1080 std::nullopt, E->getEndLoc());
1081 if (Call.isInvalid())
1082 return ExprError();
1083
1084 ExprResult Comma =
1085 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1086 if (Comma.isInvalid())
1087 return ExprError();
1088 return Comma.get();
1089 }
1090
1091 if (!getLangOpts().CPlusPlus &&
1093 diag::err_call_incomplete_argument))
1094 return ExprError();
1095
1096 return E;
1097}
1098
1099/// Convert complex integers to complex floats and real integers to
1100/// real floats as required for complex arithmetic. Helper function of
1101/// UsualArithmeticConversions()
1102///
1103/// \return false if the integer expression is an integer type and is
1104/// successfully converted to the (complex) float type.
1106 ExprResult &ComplexExpr,
1107 QualType IntTy,
1108 QualType ComplexTy,
1109 bool SkipCast) {
1110 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1111 if (SkipCast) return false;
1112 if (IntTy->isIntegerType()) {
1113 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1114 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1115 } else {
1116 assert(IntTy->isComplexIntegerType());
1117 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1118 CK_IntegralComplexToFloatingComplex);
1119 }
1120 return false;
1121}
1122
1123// This handles complex/complex, complex/float, or float/complex.
1124// When both operands are complex, the shorter operand is converted to the
1125// type of the longer, and that is the type of the result. This corresponds
1126// to what is done when combining two real floating-point operands.
1127// The fun begins when size promotion occur across type domains.
1128// From H&S 6.3.4: When one operand is complex and the other is a real
1129// floating-point type, the less precise type is converted, within it's
1130// real or complex domain, to the precision of the other type. For example,
1131// when combining a "long double" with a "double _Complex", the
1132// "double _Complex" is promoted to "long double _Complex".
1134 QualType ShorterType,
1135 QualType LongerType,
1136 bool PromotePrecision) {
1137 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1139 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1140
1141 if (PromotePrecision) {
1142 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1143 Shorter =
1144 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1145 } else {
1146 if (LongerIsComplex)
1147 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1148 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1149 }
1150 }
1151 return Result;
1152}
1153
1154/// Handle arithmetic conversion with complex types. Helper function of
1155/// UsualArithmeticConversions()
1157 ExprResult &RHS, QualType LHSType,
1158 QualType RHSType, bool IsCompAssign) {
1159 // Handle (complex) integer types.
1160 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1161 /*SkipCast=*/false))
1162 return LHSType;
1163 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1164 /*SkipCast=*/IsCompAssign))
1165 return RHSType;
1166
1167 // Compute the rank of the two types, regardless of whether they are complex.
1168 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1169 if (Order < 0)
1170 // Promote the precision of the LHS if not an assignment.
1171 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1172 /*PromotePrecision=*/!IsCompAssign);
1173 // Promote the precision of the RHS unless it is already the same as the LHS.
1174 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1175 /*PromotePrecision=*/Order > 0);
1176}
1177
1178/// Handle arithmetic conversion from integer to float. Helper function
1179/// of UsualArithmeticConversions()
1181 ExprResult &IntExpr,
1182 QualType FloatTy, QualType IntTy,
1183 bool ConvertFloat, bool ConvertInt) {
1184 if (IntTy->isIntegerType()) {
1185 if (ConvertInt)
1186 // Convert intExpr to the lhs floating point type.
1187 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1188 CK_IntegralToFloating);
1189 return FloatTy;
1190 }
1191
1192 // Convert both sides to the appropriate complex float.
1193 assert(IntTy->isComplexIntegerType());
1194 QualType result = S.Context.getComplexType(FloatTy);
1195
1196 // _Complex int -> _Complex float
1197 if (ConvertInt)
1198 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1199 CK_IntegralComplexToFloatingComplex);
1200
1201 // float -> _Complex float
1202 if (ConvertFloat)
1203 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1204 CK_FloatingRealToComplex);
1205
1206 return result;
1207}
1208
1209/// Handle arithmethic conversion with floating point types. Helper
1210/// function of UsualArithmeticConversions()
1212 ExprResult &RHS, QualType LHSType,
1213 QualType RHSType, bool IsCompAssign) {
1214 bool LHSFloat = LHSType->isRealFloatingType();
1215 bool RHSFloat = RHSType->isRealFloatingType();
1216
1217 // N1169 4.1.4: If one of the operands has a floating type and the other
1218 // operand has a fixed-point type, the fixed-point operand
1219 // is converted to the floating type [...]
1220 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1221 if (LHSFloat)
1222 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1223 else if (!IsCompAssign)
1224 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1225 return LHSFloat ? LHSType : RHSType;
1226 }
1227
1228 // If we have two real floating types, convert the smaller operand
1229 // to the bigger result.
1230 if (LHSFloat && RHSFloat) {
1231 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1232 if (order > 0) {
1233 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1234 return LHSType;
1235 }
1236
1237 assert(order < 0 && "illegal float comparison");
1238 if (!IsCompAssign)
1239 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1240 return RHSType;
1241 }
1242
1243 if (LHSFloat) {
1244 // Half FP has to be promoted to float unless it is natively supported
1245 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1246 LHSType = S.Context.FloatTy;
1247
1248 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1249 /*ConvertFloat=*/!IsCompAssign,
1250 /*ConvertInt=*/ true);
1251 }
1252 assert(RHSFloat);
1253 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1254 /*ConvertFloat=*/ true,
1255 /*ConvertInt=*/!IsCompAssign);
1256}
1257
1258/// Diagnose attempts to convert between __float128, __ibm128 and
1259/// long double if there is no support for such conversion.
1260/// Helper function of UsualArithmeticConversions().
1261static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1262 QualType RHSType) {
1263 // No issue if either is not a floating point type.
1264 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1265 return false;
1266
1267 // No issue if both have the same 128-bit float semantics.
1268 auto *LHSComplex = LHSType->getAs<ComplexType>();
1269 auto *RHSComplex = RHSType->getAs<ComplexType>();
1270
1271 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1272 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1273
1274 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1275 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1276
1277 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1278 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1279 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1280 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1281 return false;
1282
1283 return true;
1284}
1285
1286typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1287
1288namespace {
1289/// These helper callbacks are placed in an anonymous namespace to
1290/// permit their use as function template parameters.
1291ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1292 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1293}
1294
1295ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1296 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1297 CK_IntegralComplexCast);
1298}
1299}
1300
1301/// Handle integer arithmetic conversions. Helper function of
1302/// UsualArithmeticConversions()
1303template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1305 ExprResult &RHS, QualType LHSType,
1306 QualType RHSType, bool IsCompAssign) {
1307 // The rules for this case are in C99 6.3.1.8
1308 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1309 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1310 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1311 if (LHSSigned == RHSSigned) {
1312 // Same signedness; use the higher-ranked type
1313 if (order >= 0) {
1314 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1315 return LHSType;
1316 } else if (!IsCompAssign)
1317 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1318 return RHSType;
1319 } else if (order != (LHSSigned ? 1 : -1)) {
1320 // The unsigned type has greater than or equal rank to the
1321 // signed type, so use the unsigned type
1322 if (RHSSigned) {
1323 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1324 return LHSType;
1325 } else if (!IsCompAssign)
1326 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1327 return RHSType;
1328 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1329 // The two types are different widths; if we are here, that
1330 // means the signed type is larger than the unsigned type, so
1331 // use the signed type.
1332 if (LHSSigned) {
1333 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1334 return LHSType;
1335 } else if (!IsCompAssign)
1336 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1337 return RHSType;
1338 } else {
1339 // The signed type is higher-ranked than the unsigned type,
1340 // but isn't actually any bigger (like unsigned int and long
1341 // on most 32-bit systems). Use the unsigned type corresponding
1342 // to the signed type.
1343 QualType result =
1344 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1345 RHS = (*doRHSCast)(S, RHS.get(), result);
1346 if (!IsCompAssign)
1347 LHS = (*doLHSCast)(S, LHS.get(), result);
1348 return result;
1349 }
1350}
1351
1352/// Handle conversions with GCC complex int extension. Helper function
1353/// of UsualArithmeticConversions()
1355 ExprResult &RHS, QualType LHSType,
1356 QualType RHSType,
1357 bool IsCompAssign) {
1358 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1359 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1360
1361 if (LHSComplexInt && RHSComplexInt) {
1362 QualType LHSEltType = LHSComplexInt->getElementType();
1363 QualType RHSEltType = RHSComplexInt->getElementType();
1364 QualType ScalarType =
1365 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1366 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1367
1368 return S.Context.getComplexType(ScalarType);
1369 }
1370
1371 if (LHSComplexInt) {
1372 QualType LHSEltType = LHSComplexInt->getElementType();
1373 QualType ScalarType =
1374 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1375 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1377 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1378 CK_IntegralRealToComplex);
1379
1380 return ComplexType;
1381 }
1382
1383 assert(RHSComplexInt);
1384
1385 QualType RHSEltType = RHSComplexInt->getElementType();
1386 QualType ScalarType =
1387 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1388 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1390
1391 if (!IsCompAssign)
1392 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1393 CK_IntegralRealToComplex);
1394 return ComplexType;
1395}
1396
1397/// Return the rank of a given fixed point or integer type. The value itself
1398/// doesn't matter, but the values must be increasing with proper increasing
1399/// rank as described in N1169 4.1.1.
1400static unsigned GetFixedPointRank(QualType Ty) {
1401 const auto *BTy = Ty->getAs<BuiltinType>();
1402 assert(BTy && "Expected a builtin type.");
1403
1404 switch (BTy->getKind()) {
1405 case BuiltinType::ShortFract:
1406 case BuiltinType::UShortFract:
1407 case BuiltinType::SatShortFract:
1408 case BuiltinType::SatUShortFract:
1409 return 1;
1410 case BuiltinType::Fract:
1411 case BuiltinType::UFract:
1412 case BuiltinType::SatFract:
1413 case BuiltinType::SatUFract:
1414 return 2;
1415 case BuiltinType::LongFract:
1416 case BuiltinType::ULongFract:
1417 case BuiltinType::SatLongFract:
1418 case BuiltinType::SatULongFract:
1419 return 3;
1420 case BuiltinType::ShortAccum:
1421 case BuiltinType::UShortAccum:
1422 case BuiltinType::SatShortAccum:
1423 case BuiltinType::SatUShortAccum:
1424 return 4;
1425 case BuiltinType::Accum:
1426 case BuiltinType::UAccum:
1427 case BuiltinType::SatAccum:
1428 case BuiltinType::SatUAccum:
1429 return 5;
1430 case BuiltinType::LongAccum:
1431 case BuiltinType::ULongAccum:
1432 case BuiltinType::SatLongAccum:
1433 case BuiltinType::SatULongAccum:
1434 return 6;
1435 default:
1436 if (BTy->isInteger())
1437 return 0;
1438 llvm_unreachable("Unexpected fixed point or integer type");
1439 }
1440}
1441
1442/// handleFixedPointConversion - Fixed point operations between fixed
1443/// point types and integers or other fixed point types do not fall under
1444/// usual arithmetic conversion since these conversions could result in loss
1445/// of precsision (N1169 4.1.4). These operations should be calculated with
1446/// the full precision of their result type (N1169 4.1.6.2.1).
1448 QualType RHSTy) {
1449 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1450 "Expected at least one of the operands to be a fixed point type");
1451 assert((LHSTy->isFixedPointOrIntegerType() ||
1452 RHSTy->isFixedPointOrIntegerType()) &&
1453 "Special fixed point arithmetic operation conversions are only "
1454 "applied to ints or other fixed point types");
1455
1456 // If one operand has signed fixed-point type and the other operand has
1457 // unsigned fixed-point type, then the unsigned fixed-point operand is
1458 // converted to its corresponding signed fixed-point type and the resulting
1459 // type is the type of the converted operand.
1460 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1462 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1464
1465 // The result type is the type with the highest rank, whereby a fixed-point
1466 // conversion rank is always greater than an integer conversion rank; if the
1467 // type of either of the operands is a saturating fixedpoint type, the result
1468 // type shall be the saturating fixed-point type corresponding to the type
1469 // with the highest rank; the resulting value is converted (taking into
1470 // account rounding and overflow) to the precision of the resulting type.
1471 // Same ranks between signed and unsigned types are resolved earlier, so both
1472 // types are either signed or both unsigned at this point.
1473 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1474 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1475
1476 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1477
1479 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1480
1481 return ResultTy;
1482}
1483
1484/// Check that the usual arithmetic conversions can be performed on this pair of
1485/// expressions that might be of enumeration type.
1488 Sema::ArithConvKind ACK) {
1489 // C++2a [expr.arith.conv]p1:
1490 // If one operand is of enumeration type and the other operand is of a
1491 // different enumeration type or a floating-point type, this behavior is
1492 // deprecated ([depr.arith.conv.enum]).
1493 //
1494 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1495 // Eventually we will presumably reject these cases (in C++23 onwards?).
1497 R = RHS->getEnumCoercedType(S.Context);
1498 bool LEnum = L->isUnscopedEnumerationType(),
1499 REnum = R->isUnscopedEnumerationType();
1500 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1501 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1502 (REnum && L->isFloatingType())) {
1503 S.Diag(Loc, S.getLangOpts().CPlusPlus26
1504 ? diag::err_arith_conv_enum_float_cxx26
1505 : S.getLangOpts().CPlusPlus20
1506 ? diag::warn_arith_conv_enum_float_cxx20
1507 : diag::warn_arith_conv_enum_float)
1508 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1509 << L << R;
1510 } else if (!IsCompAssign && LEnum && REnum &&
1512 unsigned DiagID;
1513 // In C++ 26, usual arithmetic conversions between 2 different enum types
1514 // are ill-formed.
1515 if (S.getLangOpts().CPlusPlus26)
1516 DiagID = diag::err_conv_mixed_enum_types_cxx26;
1517 else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1518 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1519 // If either enumeration type is unnamed, it's less likely that the
1520 // user cares about this, but this situation is still deprecated in
1521 // C++2a. Use a different warning group.
1522 DiagID = S.getLangOpts().CPlusPlus20
1523 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1524 : diag::warn_arith_conv_mixed_anon_enum_types;
1525 } else if (ACK == Sema::ACK_Conditional) {
1526 // Conditional expressions are separated out because they have
1527 // historically had a different warning flag.
1528 DiagID = S.getLangOpts().CPlusPlus20
1529 ? diag::warn_conditional_mixed_enum_types_cxx20
1530 : diag::warn_conditional_mixed_enum_types;
1531 } else if (ACK == Sema::ACK_Comparison) {
1532 // Comparison expressions are separated out because they have
1533 // historically had a different warning flag.
1534 DiagID = S.getLangOpts().CPlusPlus20
1535 ? diag::warn_comparison_mixed_enum_types_cxx20
1536 : diag::warn_comparison_mixed_enum_types;
1537 } else {
1538 DiagID = S.getLangOpts().CPlusPlus20
1539 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1540 : diag::warn_arith_conv_mixed_enum_types;
1541 }
1542 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1543 << (int)ACK << L << R;
1544 }
1545}
1546
1547/// UsualArithmeticConversions - Performs various conversions that are common to
1548/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1549/// routine returns the first non-arithmetic type found. The client is
1550/// responsible for emitting appropriate error diagnostics.
1553 ArithConvKind ACK) {
1554 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1555
1556 if (ACK != ACK_CompAssign) {
1557 LHS = UsualUnaryConversions(LHS.get());
1558 if (LHS.isInvalid())
1559 return QualType();
1560 }
1561
1562 RHS = UsualUnaryConversions(RHS.get());
1563 if (RHS.isInvalid())
1564 return QualType();
1565
1566 // For conversion purposes, we ignore any qualifiers.
1567 // For example, "const float" and "float" are equivalent.
1568 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1569 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1570
1571 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1572 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1573 LHSType = AtomicLHS->getValueType();
1574
1575 // If both types are identical, no conversion is needed.
1576 if (Context.hasSameType(LHSType, RHSType))
1577 return Context.getCommonSugaredType(LHSType, RHSType);
1578
1579 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1580 // The caller can deal with this (e.g. pointer + int).
1581 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1582 return QualType();
1583
1584 // Apply unary and bitfield promotions to the LHS's type.
1585 QualType LHSUnpromotedType = LHSType;
1586 if (Context.isPromotableIntegerType(LHSType))
1587 LHSType = Context.getPromotedIntegerType(LHSType);
1588 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1589 if (!LHSBitfieldPromoteTy.isNull())
1590 LHSType = LHSBitfieldPromoteTy;
1591 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1592 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1593
1594 // If both types are identical, no conversion is needed.
1595 if (Context.hasSameType(LHSType, RHSType))
1596 return Context.getCommonSugaredType(LHSType, RHSType);
1597
1598 // At this point, we have two different arithmetic types.
1599
1600 // Diagnose attempts to convert between __ibm128, __float128 and long double
1601 // where such conversions currently can't be handled.
1602 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1603 return QualType();
1604
1605 // Handle complex types first (C99 6.3.1.8p1).
1606 if (LHSType->isComplexType() || RHSType->isComplexType())
1607 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1608 ACK == ACK_CompAssign);
1609
1610 // Now handle "real" floating types (i.e. float, double, long double).
1611 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1612 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1613 ACK == ACK_CompAssign);
1614
1615 // Handle GCC complex int extension.
1616 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1617 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1618 ACK == ACK_CompAssign);
1619
1620 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1621 return handleFixedPointConversion(*this, LHSType, RHSType);
1622
1623 // Finally, we have two differing integer types.
1624 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1625 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1626}
1627
1628//===----------------------------------------------------------------------===//
1629// Semantic Analysis for various Expression Types
1630//===----------------------------------------------------------------------===//
1631
1632
1634 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1635 bool PredicateIsExpr, void *ControllingExprOrType,
1636 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1637 unsigned NumAssocs = ArgTypes.size();
1638 assert(NumAssocs == ArgExprs.size());
1639
1640 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1641 for (unsigned i = 0; i < NumAssocs; ++i) {
1642 if (ArgTypes[i])
1643 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1644 else
1645 Types[i] = nullptr;
1646 }
1647
1648 // If we have a controlling type, we need to convert it from a parsed type
1649 // into a semantic type and then pass that along.
1650 if (!PredicateIsExpr) {
1651 TypeSourceInfo *ControllingType;
1652 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1653 &ControllingType);
1654 assert(ControllingType && "couldn't get the type out of the parser");
1655 ControllingExprOrType = ControllingType;
1656 }
1657
1659 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1660 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1661 delete [] Types;
1662 return ER;
1663}
1664
1666 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1667 bool PredicateIsExpr, void *ControllingExprOrType,
1669 unsigned NumAssocs = Types.size();
1670 assert(NumAssocs == Exprs.size());
1671 assert(ControllingExprOrType &&
1672 "Must have either a controlling expression or a controlling type");
1673
1674 Expr *ControllingExpr = nullptr;
1675 TypeSourceInfo *ControllingType = nullptr;
1676 if (PredicateIsExpr) {
1677 // Decay and strip qualifiers for the controlling expression type, and
1678 // handle placeholder type replacement. See committee discussion from WG14
1679 // DR423.
1683 reinterpret_cast<Expr *>(ControllingExprOrType));
1684 if (R.isInvalid())
1685 return ExprError();
1686 ControllingExpr = R.get();
1687 } else {
1688 // The extension form uses the type directly rather than converting it.
1689 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1690 if (!ControllingType)
1691 return ExprError();
1692 }
1693
1694 bool TypeErrorFound = false,
1695 IsResultDependent = ControllingExpr
1696 ? ControllingExpr->isTypeDependent()
1697 : ControllingType->getType()->isDependentType(),
1698 ContainsUnexpandedParameterPack =
1699 ControllingExpr
1700 ? ControllingExpr->containsUnexpandedParameterPack()
1701 : ControllingType->getType()->containsUnexpandedParameterPack();
1702
1703 // The controlling expression is an unevaluated operand, so side effects are
1704 // likely unintended.
1705 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1706 ControllingExpr->HasSideEffects(Context, false))
1707 Diag(ControllingExpr->getExprLoc(),
1708 diag::warn_side_effects_unevaluated_context);
1709
1710 for (unsigned i = 0; i < NumAssocs; ++i) {
1711 if (Exprs[i]->containsUnexpandedParameterPack())
1712 ContainsUnexpandedParameterPack = true;
1713
1714 if (Types[i]) {
1715 if (Types[i]->getType()->containsUnexpandedParameterPack())
1716 ContainsUnexpandedParameterPack = true;
1717
1718 if (Types[i]->getType()->isDependentType()) {
1719 IsResultDependent = true;
1720 } else {
1721 // We relax the restriction on use of incomplete types and non-object
1722 // types with the type-based extension of _Generic. Allowing incomplete
1723 // objects means those can be used as "tags" for a type-safe way to map
1724 // to a value. Similarly, matching on function types rather than
1725 // function pointer types can be useful. However, the restriction on VM
1726 // types makes sense to retain as there are open questions about how
1727 // the selection can be made at compile time.
1728 //
1729 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1730 // complete object type other than a variably modified type."
1731 unsigned D = 0;
1732 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1733 D = diag::err_assoc_type_incomplete;
1734 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1735 D = diag::err_assoc_type_nonobject;
1736 else if (Types[i]->getType()->isVariablyModifiedType())
1737 D = diag::err_assoc_type_variably_modified;
1738 else if (ControllingExpr) {
1739 // Because the controlling expression undergoes lvalue conversion,
1740 // array conversion, and function conversion, an association which is
1741 // of array type, function type, or is qualified can never be
1742 // reached. We will warn about this so users are less surprised by
1743 // the unreachable association. However, we don't have to handle
1744 // function types; that's not an object type, so it's handled above.
1745 //
1746 // The logic is somewhat different for C++ because C++ has different
1747 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1748 // If T is a non-class type, the type of the prvalue is the cv-
1749 // unqualified version of T. Otherwise, the type of the prvalue is T.
1750 // The result of these rules is that all qualified types in an
1751 // association in C are unreachable, and in C++, only qualified non-
1752 // class types are unreachable.
1753 //
1754 // NB: this does not apply when the first operand is a type rather
1755 // than an expression, because the type form does not undergo
1756 // conversion.
1757 unsigned Reason = 0;
1758 QualType QT = Types[i]->getType();
1759 if (QT->isArrayType())
1760 Reason = 1;
1761 else if (QT.hasQualifiers() &&
1762 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1763 Reason = 2;
1764
1765 if (Reason)
1766 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1767 diag::warn_unreachable_association)
1768 << QT << (Reason - 1);
1769 }
1770
1771 if (D != 0) {
1772 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1773 << Types[i]->getTypeLoc().getSourceRange()
1774 << Types[i]->getType();
1775 TypeErrorFound = true;
1776 }
1777
1778 // C11 6.5.1.1p2 "No two generic associations in the same generic
1779 // selection shall specify compatible types."
1780 for (unsigned j = i+1; j < NumAssocs; ++j)
1781 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1782 Context.typesAreCompatible(Types[i]->getType(),
1783 Types[j]->getType())) {
1784 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1785 diag::err_assoc_compatible_types)
1786 << Types[j]->getTypeLoc().getSourceRange()
1787 << Types[j]->getType()
1788 << Types[i]->getType();
1789 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1790 diag::note_compat_assoc)
1791 << Types[i]->getTypeLoc().getSourceRange()
1792 << Types[i]->getType();
1793 TypeErrorFound = true;
1794 }
1795 }
1796 }
1797 }
1798 if (TypeErrorFound)
1799 return ExprError();
1800
1801 // If we determined that the generic selection is result-dependent, don't
1802 // try to compute the result expression.
1803 if (IsResultDependent) {
1804 if (ControllingExpr)
1805 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1806 Types, Exprs, DefaultLoc, RParenLoc,
1807 ContainsUnexpandedParameterPack);
1808 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1809 Exprs, DefaultLoc, RParenLoc,
1810 ContainsUnexpandedParameterPack);
1811 }
1812
1813 SmallVector<unsigned, 1> CompatIndices;
1814 unsigned DefaultIndex = -1U;
1815 // Look at the canonical type of the controlling expression in case it was a
1816 // deduced type like __auto_type. However, when issuing diagnostics, use the
1817 // type the user wrote in source rather than the canonical one.
1818 for (unsigned i = 0; i < NumAssocs; ++i) {
1819 if (!Types[i])
1820 DefaultIndex = i;
1821 else if (ControllingExpr &&
1823 ControllingExpr->getType().getCanonicalType(),
1824 Types[i]->getType()))
1825 CompatIndices.push_back(i);
1826 else if (ControllingType &&
1828 ControllingType->getType().getCanonicalType(),
1829 Types[i]->getType()))
1830 CompatIndices.push_back(i);
1831 }
1832
1833 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1834 TypeSourceInfo *ControllingType) {
1835 // We strip parens here because the controlling expression is typically
1836 // parenthesized in macro definitions.
1837 if (ControllingExpr)
1838 ControllingExpr = ControllingExpr->IgnoreParens();
1839
1840 SourceRange SR = ControllingExpr
1841 ? ControllingExpr->getSourceRange()
1842 : ControllingType->getTypeLoc().getSourceRange();
1843 QualType QT = ControllingExpr ? ControllingExpr->getType()
1844 : ControllingType->getType();
1845
1846 return std::make_pair(SR, QT);
1847 };
1848
1849 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1850 // type compatible with at most one of the types named in its generic
1851 // association list."
1852 if (CompatIndices.size() > 1) {
1853 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1854 SourceRange SR = P.first;
1855 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1856 << SR << P.second << (unsigned)CompatIndices.size();
1857 for (unsigned I : CompatIndices) {
1858 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1859 diag::note_compat_assoc)
1860 << Types[I]->getTypeLoc().getSourceRange()
1861 << Types[I]->getType();
1862 }
1863 return ExprError();
1864 }
1865
1866 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1867 // its controlling expression shall have type compatible with exactly one of
1868 // the types named in its generic association list."
1869 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1870 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1871 SourceRange SR = P.first;
1872 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1873 return ExprError();
1874 }
1875
1876 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1877 // type name that is compatible with the type of the controlling expression,
1878 // then the result expression of the generic selection is the expression
1879 // in that generic association. Otherwise, the result expression of the
1880 // generic selection is the expression in the default generic association."
1881 unsigned ResultIndex =
1882 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1883
1884 if (ControllingExpr) {
1886 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1887 ContainsUnexpandedParameterPack, ResultIndex);
1888 }
1890 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1891 ContainsUnexpandedParameterPack, ResultIndex);
1892}
1893
1895 switch (Kind) {
1896 default:
1897 llvm_unreachable("unexpected TokenKind");
1898 case tok::kw___func__:
1899 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
1900 case tok::kw___FUNCTION__:
1902 case tok::kw___FUNCDNAME__:
1903 return PredefinedIdentKind::FuncDName; // [MS]
1904 case tok::kw___FUNCSIG__:
1905 return PredefinedIdentKind::FuncSig; // [MS]
1906 case tok::kw_L__FUNCTION__:
1907 return PredefinedIdentKind::LFunction; // [MS]
1908 case tok::kw_L__FUNCSIG__:
1909 return PredefinedIdentKind::LFuncSig; // [MS]
1910 case tok::kw___PRETTY_FUNCTION__:
1912 }
1913}
1914
1915/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1916/// to determine the value of a PredefinedExpr. This can be either a
1917/// block, lambda, captured statement, function, otherwise a nullptr.
1919 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
1920 DC = DC->getParent();
1921 return cast_or_null<Decl>(DC);
1922}
1923
1924/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1925/// location of the token and the offset of the ud-suffix within it.
1927 unsigned Offset) {
1928 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1929 S.getLangOpts());
1930}
1931
1932/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1933/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1935 IdentifierInfo *UDSuffix,
1936 SourceLocation UDSuffixLoc,
1937 ArrayRef<Expr*> Args,
1938 SourceLocation LitEndLoc) {
1939 assert(Args.size() <= 2 && "too many arguments for literal operator");
1940
1941 QualType ArgTy[2];
1942 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1943 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1944 if (ArgTy[ArgIdx]->isArrayType())
1945 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1946 }
1947
1948 DeclarationName OpName =
1950 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1951 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1952
1953 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1954 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1955 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1956 /*AllowStringTemplatePack*/ false,
1957 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1958 return ExprError();
1959
1960 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1961}
1962
1964 // StringToks needs backing storage as it doesn't hold array elements itself
1965 std::vector<Token> ExpandedToks;
1966 if (getLangOpts().MicrosoftExt)
1967 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
1968
1969 StringLiteralParser Literal(StringToks, PP,
1971 if (Literal.hadError)
1972 return ExprError();
1973
1974 SmallVector<SourceLocation, 4> StringTokLocs;
1975 for (const Token &Tok : StringToks)
1976 StringTokLocs.push_back(Tok.getLocation());
1977
1979 Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {},
1980 &StringTokLocs[0], StringTokLocs.size());
1981
1982 if (!Literal.getUDSuffix().empty()) {
1983 SourceLocation UDSuffixLoc =
1984 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1985 Literal.getUDSuffixOffset());
1986 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1987 }
1988
1989 return Lit;
1990}
1991
1992std::vector<Token>
1994 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
1995 // local macros that expand to string literals that may be concatenated.
1996 // These macros are expanded here (in Sema), because StringLiteralParser
1997 // (in Lex) doesn't know the enclosing function (because it hasn't been
1998 // parsed yet).
1999 assert(getLangOpts().MicrosoftExt);
2000
2001 // Note: Although function local macros are defined only inside functions,
2002 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2003 // expansion of macros into empty string literals without additional checks.
2004 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2005 if (!CurrentDecl)
2006 CurrentDecl = Context.getTranslationUnitDecl();
2007
2008 std::vector<Token> ExpandedToks;
2009 ExpandedToks.reserve(Toks.size());
2010 for (const Token &Tok : Toks) {
2011 if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2012 assert(tok::isStringLiteral(Tok.getKind()));
2013 ExpandedToks.emplace_back(Tok);
2014 continue;
2015 }
2016 if (isa<TranslationUnitDecl>(CurrentDecl))
2017 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2018 // Stringify predefined expression
2019 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2020 << Tok.getKind();
2021 SmallString<64> Str;
2022 llvm::raw_svector_ostream OS(Str);
2023 Token &Exp = ExpandedToks.emplace_back();
2024 Exp.startToken();
2025 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2026 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2027 OS << 'L';
2028 Exp.setKind(tok::wide_string_literal);
2029 } else {
2030 Exp.setKind(tok::string_literal);
2031 }
2032 OS << '"'
2034 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2035 << '"';
2036 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2037 }
2038 return ExpandedToks;
2039}
2040
2043 assert(!StringToks.empty() && "Must have at least one string!");
2044
2045 // StringToks needs backing storage as it doesn't hold array elements itself
2046 std::vector<Token> ExpandedToks;
2047 if (getLangOpts().MicrosoftExt)
2048 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2049
2050 StringLiteralParser Literal(StringToks, PP);
2051 if (Literal.hadError)
2052 return ExprError();
2053
2054 SmallVector<SourceLocation, 4> StringTokLocs;
2055 for (const Token &Tok : StringToks)
2056 StringTokLocs.push_back(Tok.getLocation());
2057
2058 QualType CharTy = Context.CharTy;
2060 if (Literal.isWide()) {
2061 CharTy = Context.getWideCharType();
2063 } else if (Literal.isUTF8()) {
2064 if (getLangOpts().Char8)
2065 CharTy = Context.Char8Ty;
2066 else if (getLangOpts().C23)
2067 CharTy = Context.UnsignedCharTy;
2069 } else if (Literal.isUTF16()) {
2070 CharTy = Context.Char16Ty;
2072 } else if (Literal.isUTF32()) {
2073 CharTy = Context.Char32Ty;
2075 } else if (Literal.isPascal()) {
2076 CharTy = Context.UnsignedCharTy;
2077 }
2078
2079 // Warn on u8 string literals before C++20 and C23, whose type
2080 // was an array of char before but becomes an array of char8_t.
2081 // In C++20, it cannot be used where a pointer to char is expected.
2082 // In C23, it might have an unexpected value if char was signed.
2083 if (Kind == StringLiteralKind::UTF8 &&
2085 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2086 : !getLangOpts().C23)) {
2087 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2088 ? diag::warn_cxx20_compat_utf8_string
2089 : diag::warn_c23_compat_utf8_string);
2090
2091 // Create removals for all 'u8' prefixes in the string literal(s). This
2092 // ensures C++20/C23 compatibility (but may change the program behavior when
2093 // built by non-Clang compilers for which the execution character set is
2094 // not always UTF-8).
2095 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2096 SourceLocation RemovalDiagLoc;
2097 for (const Token &Tok : StringToks) {
2098 if (Tok.getKind() == tok::utf8_string_literal) {
2099 if (RemovalDiagLoc.isInvalid())
2100 RemovalDiagLoc = Tok.getLocation();
2102 Tok.getLocation(),
2103 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2105 }
2106 }
2107 Diag(RemovalDiagLoc, RemovalDiag);
2108 }
2109
2110 QualType StrTy =
2111 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2112
2113 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2114 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2115 Kind, Literal.Pascal, StrTy,
2116 &StringTokLocs[0],
2117 StringTokLocs.size());
2118 if (Literal.getUDSuffix().empty())
2119 return Lit;
2120
2121 // We're building a user-defined literal.
2122 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2123 SourceLocation UDSuffixLoc =
2124 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2125 Literal.getUDSuffixOffset());
2126
2127 // Make sure we're allowed user-defined literals here.
2128 if (!UDLScope)
2129 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2130
2131 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2132 // operator "" X (str, len)
2133 QualType SizeType = Context.getSizeType();
2134
2135 DeclarationName OpName =
2137 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2138 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2139
2140 QualType ArgTy[] = {
2141 Context.getArrayDecayedType(StrTy), SizeType
2142 };
2143
2144 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2145 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2146 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2147 /*AllowStringTemplatePack*/ true,
2148 /*DiagnoseMissing*/ true, Lit)) {
2149
2150 case LOLR_Cooked: {
2151 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2152 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2153 StringTokLocs[0]);
2154 Expr *Args[] = { Lit, LenArg };
2155
2156 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2157 }
2158
2159 case LOLR_Template: {
2160 TemplateArgumentListInfo ExplicitArgs;
2161 TemplateArgument Arg(Lit);
2162 TemplateArgumentLocInfo ArgInfo(Lit);
2163 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2164 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2165 StringTokLocs.back(), &ExplicitArgs);
2166 }
2167
2169 TemplateArgumentListInfo ExplicitArgs;
2170
2171 unsigned CharBits = Context.getIntWidth(CharTy);
2172 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2173 llvm::APSInt Value(CharBits, CharIsUnsigned);
2174
2175 TemplateArgument TypeArg(CharTy);
2177 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2178
2179 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2180 Value = Lit->getCodeUnit(I);
2181 TemplateArgument Arg(Context, Value, CharTy);
2183 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2184 }
2185 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2186 StringTokLocs.back(), &ExplicitArgs);
2187 }
2188 case LOLR_Raw:
2190 llvm_unreachable("unexpected literal operator lookup result");
2191 case LOLR_Error:
2192 return ExprError();
2193 }
2194 llvm_unreachable("unexpected literal operator lookup result");
2195}
2196
2200 const CXXScopeSpec *SS) {
2201 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2202 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2203}
2204
2207 const DeclarationNameInfo &NameInfo,
2208 const CXXScopeSpec *SS, NamedDecl *FoundD,
2209 SourceLocation TemplateKWLoc,
2210 const TemplateArgumentListInfo *TemplateArgs) {
2213 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2214 TemplateArgs);
2215}
2216
2217// CUDA/HIP: Check whether a captured reference variable is referencing a
2218// host variable in a device or host device lambda.
2220 VarDecl *VD) {
2221 if (!S.getLangOpts().CUDA || !VD->hasInit())
2222 return false;
2223 assert(VD->getType()->isReferenceType());
2224
2225 // Check whether the reference variable is referencing a host variable.
2226 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2227 if (!DRE)
2228 return false;
2229 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2230 if (!Referee || !Referee->hasGlobalStorage() ||
2231 Referee->hasAttr<CUDADeviceAttr>())
2232 return false;
2233
2234 // Check whether the current function is a device or host device lambda.
2235 // Check whether the reference variable is a capture by getDeclContext()
2236 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2237 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2238 if (MD && MD->getParent()->isLambda() &&
2239 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2240 VD->getDeclContext() != MD)
2241 return true;
2242
2243 return false;
2244}
2245
2247 // A declaration named in an unevaluated operand never constitutes an odr-use.
2249 return NOUR_Unevaluated;
2250
2251 // C++2a [basic.def.odr]p4:
2252 // A variable x whose name appears as a potentially-evaluated expression e
2253 // is odr-used by e unless [...] x is a reference that is usable in
2254 // constant expressions.
2255 // CUDA/HIP:
2256 // If a reference variable referencing a host variable is captured in a
2257 // device or host device lambda, the value of the referee must be copied
2258 // to the capture and the reference variable must be treated as odr-use
2259 // since the value of the referee is not known at compile time and must
2260 // be loaded from the captured.
2261 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2262 if (VD->getType()->isReferenceType() &&
2263 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2265 VD->isUsableInConstantExpressions(Context))
2266 return NOUR_Constant;
2267 }
2268
2269 // All remaining non-variable cases constitute an odr-use. For variables, we
2270 // need to wait and see how the expression is used.
2271 return NOUR_None;
2272}
2273
2276 const DeclarationNameInfo &NameInfo,
2277 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2278 SourceLocation TemplateKWLoc,
2279 const TemplateArgumentListInfo *TemplateArgs) {
2280 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2281 NeedToCaptureVariable(D, NameInfo.getLoc());
2282
2284 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2285 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2287
2288 // C++ [except.spec]p17:
2289 // An exception-specification is considered to be needed when:
2290 // - in an expression, the function is the unique lookup result or
2291 // the selected member of a set of overloaded functions.
2292 //
2293 // We delay doing this until after we've built the function reference and
2294 // marked it as used so that:
2295 // a) if the function is defaulted, we get errors from defining it before /
2296 // instead of errors from computing its exception specification, and
2297 // b) if the function is a defaulted comparison, we can use the body we
2298 // build when defining it as input to the exception specification
2299 // computation rather than computing a new body.
2300 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2301 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2302 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2304 }
2305 }
2306
2307 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2309 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2311
2312 const auto *FD = dyn_cast<FieldDecl>(D);
2313 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2314 FD = IFD->getAnonField();
2315 if (FD) {
2316 UnusedPrivateFields.remove(FD);
2317 // Just in case we're building an illegal pointer-to-member.
2318 if (FD->isBitField())
2320 }
2321
2322 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2323 // designates a bit-field.
2324 if (const auto *BD = dyn_cast<BindingDecl>(D))
2325 if (const auto *BE = BD->getBinding())
2326 E->setObjectKind(BE->getObjectKind());
2327
2328 return E;
2329}
2330
2331void
2334 DeclarationNameInfo &NameInfo,
2335 const TemplateArgumentListInfo *&TemplateArgs) {
2336 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2337 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2338 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2339
2340 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2341 Id.TemplateId->NumArgs);
2342 translateTemplateArguments(TemplateArgsPtr, Buffer);
2343
2344 TemplateName TName = Id.TemplateId->Template.get();
2345 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2346 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2347 TemplateArgs = &Buffer;
2348 } else {
2349 NameInfo = GetNameFromUnqualifiedId(Id);
2350 TemplateArgs = nullptr;
2351 }
2352}
2353
2355 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2357 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2358 DeclContext *Ctx =
2359 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2360 if (!TC) {
2361 // Emit a special diagnostic for failed member lookups.
2362 // FIXME: computing the declaration context might fail here (?)
2363 if (Ctx)
2364 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2365 << SS.getRange();
2366 else
2367 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2368 return;
2369 }
2370
2371 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2372 bool DroppedSpecifier =
2373 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2374 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2375 ? diag::note_implicit_param_decl
2376 : diag::note_previous_decl;
2377 if (!Ctx)
2378 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2379 SemaRef.PDiag(NoteID));
2380 else
2381 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2382 << Typo << Ctx << DroppedSpecifier
2383 << SS.getRange(),
2384 SemaRef.PDiag(NoteID));
2385}
2386
2388 // During a default argument instantiation the CurContext points
2389 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2390 // function parameter list, hence add an explicit check.
2391 bool isDefaultArgument =
2392 !CodeSynthesisContexts.empty() &&
2393 CodeSynthesisContexts.back().Kind ==
2395 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2396 bool isInstance = CurMethod && CurMethod->isInstance() &&
2397 R.getNamingClass() == CurMethod->getParent() &&
2398 !isDefaultArgument;
2399
2400 // There are two ways we can find a class-scope declaration during template
2401 // instantiation that we did not find in the template definition: if it is a
2402 // member of a dependent base class, or if it is declared after the point of
2403 // use in the same class. Distinguish these by comparing the class in which
2404 // the member was found to the naming class of the lookup.
2405 unsigned DiagID = diag::err_found_in_dependent_base;
2406 unsigned NoteID = diag::note_member_declared_at;
2408 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2409 : diag::err_found_later_in_class;
2410 } else if (getLangOpts().MSVCCompat) {
2411 DiagID = diag::ext_found_in_dependent_base;
2412 NoteID = diag::note_dependent_member_use;
2413 }
2414
2415 if (isInstance) {
2416 // Give a code modification hint to insert 'this->'.
2417 Diag(R.getNameLoc(), DiagID)
2418 << R.getLookupName()
2419 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2421 } else {
2422 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2423 // they're not shadowed).
2424 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2425 }
2426
2427 for (const NamedDecl *D : R)
2428 Diag(D->getLocation(), NoteID);
2429
2430 // Return true if we are inside a default argument instantiation
2431 // and the found name refers to an instance member function, otherwise
2432 // the caller will try to create an implicit member call and this is wrong
2433 // for default arguments.
2434 //
2435 // FIXME: Is this special case necessary? We could allow the caller to
2436 // diagnose this.
2437 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2438 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2439 return true;
2440 }
2441
2442 // Tell the callee to try to recover.
2443 return false;
2444}
2445
2448 TemplateArgumentListInfo *ExplicitTemplateArgs,
2449 ArrayRef<Expr *> Args, DeclContext *LookupCtx,
2450 TypoExpr **Out) {
2451 DeclarationName Name = R.getLookupName();
2452
2453 unsigned diagnostic = diag::err_undeclared_var_use;
2454 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2455 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2456 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2457 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2458 diagnostic = diag::err_undeclared_use;
2459 diagnostic_suggest = diag::err_undeclared_use_suggest;
2460 }
2461
2462 // If the original lookup was an unqualified lookup, fake an
2463 // unqualified lookup. This is useful when (for example) the
2464 // original lookup would not have found something because it was a
2465 // dependent name.
2466 DeclContext *DC =
2467 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2468 while (DC) {
2469 if (isa<CXXRecordDecl>(DC)) {
2470 LookupQualifiedName(R, DC);
2471
2472 if (!R.empty()) {
2473 // Don't give errors about ambiguities in this lookup.
2475
2476 // If there's a best viable function among the results, only mention
2477 // that one in the notes.
2478 OverloadCandidateSet Candidates(R.getNameLoc(),
2480 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2482 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2483 OR_Success) {
2484 R.clear();
2485 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2486 R.resolveKind();
2487 }
2488
2490 }
2491
2492 R.clear();
2493 }
2494
2495 DC = DC->getLookupParent();
2496 }
2497
2498 // We didn't find anything, so try to correct for a typo.
2499 TypoCorrection Corrected;
2500 if (S && Out) {
2501 SourceLocation TypoLoc = R.getNameLoc();
2502 assert(!ExplicitTemplateArgs &&
2503 "Diagnosing an empty lookup with explicit template args!");
2504 *Out = CorrectTypoDelayed(
2505 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2506 [=](const TypoCorrection &TC) {
2507 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2508 diagnostic, diagnostic_suggest);
2509 },
2510 nullptr, CTK_ErrorRecovery, LookupCtx);
2511 if (*Out)
2512 return true;
2513 } else if (S && (Corrected =
2515 &SS, CCC, CTK_ErrorRecovery, LookupCtx))) {
2516 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2517 bool DroppedSpecifier =
2518 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2519 R.setLookupName(Corrected.getCorrection());
2520
2521 bool AcceptableWithRecovery = false;
2522 bool AcceptableWithoutRecovery = false;
2523 NamedDecl *ND = Corrected.getFoundDecl();
2524 if (ND) {
2525 if (Corrected.isOverloaded()) {
2529 for (NamedDecl *CD : Corrected) {
2530 if (FunctionTemplateDecl *FTD =
2531 dyn_cast<FunctionTemplateDecl>(CD))
2533 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2534 Args, OCS);
2535 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2536 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2538 Args, OCS);
2539 }
2540 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2541 case OR_Success:
2542 ND = Best->FoundDecl;
2543 Corrected.setCorrectionDecl(ND);
2544 break;
2545 default:
2546 // FIXME: Arbitrarily pick the first declaration for the note.
2547 Corrected.setCorrectionDecl(ND);
2548 break;
2549 }
2550 }
2551 R.addDecl(ND);
2552 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2553 CXXRecordDecl *Record = nullptr;
2554 if (Corrected.getCorrectionSpecifier()) {
2555 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2556 Record = Ty->getAsCXXRecordDecl();
2557 }
2558 if (!Record)
2559 Record = cast<CXXRecordDecl>(
2562 }
2563
2564 auto *UnderlyingND = ND->getUnderlyingDecl();
2565 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2566 isa<FunctionTemplateDecl>(UnderlyingND);
2567 // FIXME: If we ended up with a typo for a type name or
2568 // Objective-C class name, we're in trouble because the parser
2569 // is in the wrong place to recover. Suggest the typo
2570 // correction, but don't make it a fix-it since we're not going
2571 // to recover well anyway.
2572 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2573 getAsTypeTemplateDecl(UnderlyingND) ||
2574 isa<ObjCInterfaceDecl>(UnderlyingND);
2575 } else {
2576 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2577 // because we aren't able to recover.
2578 AcceptableWithoutRecovery = true;
2579 }
2580
2581 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2582 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2583 ? diag::note_implicit_param_decl
2584 : diag::note_previous_decl;
2585 if (SS.isEmpty())
2586 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2587 PDiag(NoteID), AcceptableWithRecovery);
2588 else
2589 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2590 << Name << computeDeclContext(SS, false)
2591 << DroppedSpecifier << SS.getRange(),
2592 PDiag(NoteID), AcceptableWithRecovery);
2593
2594 // Tell the callee whether to try to recover.
2595 return !AcceptableWithRecovery;
2596 }
2597 }
2598 R.clear();
2599
2600 // Emit a special diagnostic for failed member lookups.
2601 // FIXME: computing the declaration context might fail here (?)
2602 if (!SS.isEmpty()) {
2603 Diag(R.getNameLoc(), diag::err_no_member)
2604 << Name << computeDeclContext(SS, false)
2605 << SS.getRange();
2606 return true;
2607 }
2608
2609 // Give up, we can't recover.
2610 Diag(R.getNameLoc(), diagnostic) << Name;
2611 return true;
2612}
2613
2614/// In Microsoft mode, if we are inside a template class whose parent class has
2615/// dependent base classes, and we can't resolve an unqualified identifier, then
2616/// assume the identifier is a member of a dependent base class. We can only
2617/// recover successfully in static methods, instance methods, and other contexts
2618/// where 'this' is available. This doesn't precisely match MSVC's
2619/// instantiation model, but it's close enough.
2620static Expr *
2622 DeclarationNameInfo &NameInfo,
2623 SourceLocation TemplateKWLoc,
2624 const TemplateArgumentListInfo *TemplateArgs) {
2625 // Only try to recover from lookup into dependent bases in static methods or
2626 // contexts where 'this' is available.
2627 QualType ThisType = S.getCurrentThisType();
2628 const CXXRecordDecl *RD = nullptr;
2629 if (!ThisType.isNull())
2630 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2631 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2632 RD = MD->getParent();
2633 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2634 return nullptr;
2635
2636 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2637 // is available, suggest inserting 'this->' as a fixit.
2638 SourceLocation Loc = NameInfo.getLoc();
2639 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2640 DB << NameInfo.getName() << RD;
2641
2642 if (!ThisType.isNull()) {
2643 DB << FixItHint::CreateInsertion(Loc, "this->");
2645 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2646 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2647 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2648 }
2649
2650 // Synthesize a fake NNS that points to the derived class. This will
2651 // perform name lookup during template instantiation.
2652 CXXScopeSpec SS;
2653 auto *NNS =
2654 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2655 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2657 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2658 TemplateArgs);
2659}
2660
2663 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2664 bool HasTrailingLParen, bool IsAddressOfOperand,
2666 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2667 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2668 "cannot be direct & operand and have a trailing lparen");
2669 if (SS.isInvalid())
2670 return ExprError();
2671
2672 TemplateArgumentListInfo TemplateArgsBuffer;
2673
2674 // Decompose the UnqualifiedId into the following data.
2675 DeclarationNameInfo NameInfo;
2676 const TemplateArgumentListInfo *TemplateArgs;
2677 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2678
2679 DeclarationName Name = NameInfo.getName();
2680 IdentifierInfo *II = Name.getAsIdentifierInfo();
2681 SourceLocation NameLoc = NameInfo.getLoc();
2682
2683 if (II && II->isEditorPlaceholder()) {
2684 // FIXME: When typed placeholders are supported we can create a typed
2685 // placeholder expression node.
2686 return ExprError();
2687 }
2688
2689 // This specially handles arguments of attributes appertains to a type of C
2690 // struct field such that the name lookup within a struct finds the member
2691 // name, which is not the case for other contexts in C.
2692 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2693 // See if this is reference to a field of struct.
2694 LookupResult R(*this, NameInfo, LookupMemberName);
2695 // LookupName handles a name lookup from within anonymous struct.
2696 if (LookupName(R, S)) {
2697 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2698 QualType type = VD->getType().getNonReferenceType();
2699 // This will eventually be translated into MemberExpr upon
2700 // the use of instantiated struct fields.
2701 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2702 }
2703 }
2704 }
2705
2706 // Perform the required lookup.
2707 LookupResult R(*this, NameInfo,
2711 if (TemplateKWLoc.isValid() || TemplateArgs) {
2712 // Lookup the template name again to correctly establish the context in
2713 // which it was found. This is really unfortunate as we already did the
2714 // lookup to determine that it was a template name in the first place. If
2715 // this becomes a performance hit, we can work harder to preserve those
2716 // results until we get here but it's likely not worth it.
2717 AssumedTemplateKind AssumedTemplate;
2718 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2719 /*EnteringContext=*/false, TemplateKWLoc,
2720 &AssumedTemplate))
2721 return ExprError();
2722
2724 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2725 IsAddressOfOperand, TemplateArgs);
2726 } else {
2727 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2728 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2729 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2730
2731 // If the result might be in a dependent base class, this is a dependent
2732 // id-expression.
2734 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2735 IsAddressOfOperand, TemplateArgs);
2736
2737 // If this reference is in an Objective-C method, then we need to do
2738 // some special Objective-C lookup, too.
2739 if (IvarLookupFollowUp) {
2740 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2741 if (E.isInvalid())
2742 return ExprError();
2743
2744 if (Expr *Ex = E.getAs<Expr>())
2745 return Ex;
2746 }
2747 }
2748
2749 if (R.isAmbiguous())
2750 return ExprError();
2751
2752 // This could be an implicitly declared function reference if the language
2753 // mode allows it as a feature.
2754 if (R.empty() && HasTrailingLParen && II &&
2755 getLangOpts().implicitFunctionsAllowed()) {
2756 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2757 if (D) R.addDecl(D);
2758 }
2759
2760 // Determine whether this name might be a candidate for
2761 // argument-dependent lookup.
2762 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2763
2764 if (R.empty() && !ADL) {
2765 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2766 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2767 TemplateKWLoc, TemplateArgs))
2768 return E;
2769 }
2770
2771 // Don't diagnose an empty lookup for inline assembly.
2772 if (IsInlineAsmIdentifier)
2773 return ExprError();
2774
2775 // If this name wasn't predeclared and if this is not a function
2776 // call, diagnose the problem.
2777 TypoExpr *TE = nullptr;
2778 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2779 : nullptr);
2780 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2781 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2782 "Typo correction callback misconfigured");
2783 if (CCC) {
2784 // Make sure the callback knows what the typo being diagnosed is.
2785 CCC->setTypoName(II);
2786 if (SS.isValid())
2787 CCC->setTypoNNS(SS.getScopeRep());
2788 }
2789 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2790 // a template name, but we happen to have always already looked up the name
2791 // before we get here if it must be a template name.
2792 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2793 std::nullopt, nullptr, &TE)) {
2794 if (TE && KeywordReplacement) {
2795 auto &State = getTypoExprState(TE);
2796 auto BestTC = State.Consumer->getNextCorrection();
2797 if (BestTC.isKeyword()) {
2798 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2799 if (State.DiagHandler)
2800 State.DiagHandler(BestTC);
2801 KeywordReplacement->startToken();
2802 KeywordReplacement->setKind(II->getTokenID());
2803 KeywordReplacement->setIdentifierInfo(II);
2804 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2805 // Clean up the state associated with the TypoExpr, since it has
2806 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2807 clearDelayedTypo(TE);
2808 // Signal that a correction to a keyword was performed by returning a
2809 // valid-but-null ExprResult.
2810 return (Expr*)nullptr;
2811 }
2812 State.Consumer->resetCorrectionStream();
2813 }
2814 return TE ? TE : ExprError();
2815 }
2816
2817 assert(!R.empty() &&
2818 "DiagnoseEmptyLookup returned false but added no results");
2819
2820 // If we found an Objective-C instance variable, let
2821 // LookupInObjCMethod build the appropriate expression to
2822 // reference the ivar.
2823 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2824 R.clear();
2825 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2826 // In a hopelessly buggy code, Objective-C instance variable
2827 // lookup fails and no expression will be built to reference it.
2828 if (!E.isInvalid() && !E.get())
2829 return ExprError();
2830 return E;
2831 }
2832 }
2833
2834 // This is guaranteed from this point on.
2835 assert(!R.empty() || ADL);
2836
2837 // Check whether this might be a C++ implicit instance member access.
2838 // C++ [class.mfct.non-static]p3:
2839 // When an id-expression that is not part of a class member access
2840 // syntax and not used to form a pointer to member is used in the
2841 // body of a non-static member function of class X, if name lookup
2842 // resolves the name in the id-expression to a non-static non-type
2843 // member of some class C, the id-expression is transformed into a
2844 // class member access expression using (*this) as the
2845 // postfix-expression to the left of the . operator.
2846 //
2847 // But we don't actually need to do this for '&' operands if R
2848 // resolved to a function or overloaded function set, because the
2849 // expression is ill-formed if it actually works out to be a
2850 // non-static member function:
2851 //
2852 // C++ [expr.ref]p4:
2853 // Otherwise, if E1.E2 refers to a non-static member function. . .
2854 // [t]he expression can be used only as the left-hand operand of a
2855 // member function call.
2856 //
2857 // There are other safeguards against such uses, but it's important
2858 // to get this right here so that we don't end up making a
2859 // spuriously dependent expression if we're inside a dependent
2860 // instance method.
2861 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2862 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2863 S);
2864
2865 if (TemplateArgs || TemplateKWLoc.isValid()) {
2866
2867 // In C++1y, if this is a variable template id, then check it
2868 // in BuildTemplateIdExpr().
2869 // The single lookup result must be a variable template declaration.
2870 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2871 Id.TemplateId->Kind == TNK_Var_template) {
2872 assert(R.getAsSingle<VarTemplateDecl>() &&
2873 "There should only be one declaration found.");
2874 }
2875
2876 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2877 }
2878
2879 return BuildDeclarationNameExpr(SS, R, ADL);
2880}
2881
2883 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2884 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
2885 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2886 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
2887
2888 if (R.isAmbiguous())
2889 return ExprError();
2890
2892 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2893 NameInfo, /*TemplateArgs=*/nullptr);
2894
2895 if (R.empty()) {
2896 // Don't diagnose problems with invalid record decl, the secondary no_member
2897 // diagnostic during template instantiation is likely bogus, e.g. if a class
2898 // is invalid because it's derived from an invalid base class, then missing
2899 // members were likely supposed to be inherited.
2901 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2902 if (CD->isInvalidDecl())
2903 return ExprError();
2904 Diag(NameInfo.getLoc(), diag::err_no_member)
2905 << NameInfo.getName() << DC << SS.getRange();
2906 return ExprError();
2907 }
2908
2909 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2910 // Diagnose a missing typename if this resolved unambiguously to a type in
2911 // a dependent context. If we can recover with a type, downgrade this to
2912 // a warning in Microsoft compatibility mode.
2913 unsigned DiagID = diag::err_typename_missing;
2914 if (RecoveryTSI && getLangOpts().MSVCCompat)
2915 DiagID = diag::ext_typename_missing;
2917 auto D = Diag(Loc, DiagID);
2918 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2919 << SourceRange(Loc, NameInfo.getEndLoc());
2920
2921 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2922 // context.
2923 if (!RecoveryTSI)
2924 return ExprError();
2925
2926 // Only issue the fixit if we're prepared to recover.
2927 D << FixItHint::CreateInsertion(Loc, "typename ");
2928
2929 // Recover by pretending this was an elaborated type.
2931 TypeLocBuilder TLB;
2932 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2933
2938
2939 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2940
2941 return ExprEmpty();
2942 }
2943
2944 // If necessary, build an implicit class member access.
2945 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2947 /*TemplateKWLoc=*/SourceLocation(),
2948 R, /*TemplateArgs=*/nullptr,
2949 /*S=*/nullptr);
2950
2951 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
2952}
2953
2956 NestedNameSpecifier *Qualifier,
2957 NamedDecl *FoundDecl,
2958 NamedDecl *Member) {
2959 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2960 if (!RD)
2961 return From;
2962
2963 QualType DestRecordType;
2964 QualType DestType;
2965 QualType FromRecordType;
2966 QualType FromType = From->getType();
2967 bool PointerConversions = false;
2968 if (isa<FieldDecl>(Member)) {
2969 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2970 auto FromPtrType = FromType->getAs<PointerType>();
2971 DestRecordType = Context.getAddrSpaceQualType(
2972 DestRecordType, FromPtrType
2973 ? FromType->getPointeeType().getAddressSpace()
2974 : FromType.getAddressSpace());
2975
2976 if (FromPtrType) {
2977 DestType = Context.getPointerType(DestRecordType);
2978 FromRecordType = FromPtrType->getPointeeType();
2979 PointerConversions = true;
2980 } else {
2981 DestType = DestRecordType;
2982 FromRecordType = FromType;
2983 }
2984 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
2985 if (!Method->isImplicitObjectMemberFunction())
2986 return From;
2987
2988 DestType = Method->getThisType().getNonReferenceType();
2989 DestRecordType = Method->getFunctionObjectParameterType();
2990
2991 if (FromType->getAs<PointerType>()) {
2992 FromRecordType = FromType->getPointeeType();
2993 PointerConversions = true;
2994 } else {
2995 FromRecordType = FromType;
2996 DestType = DestRecordType;
2997 }
2998
2999 LangAS FromAS = FromRecordType.getAddressSpace();
3000 LangAS DestAS = DestRecordType.getAddressSpace();
3001 if (FromAS != DestAS) {
3002 QualType FromRecordTypeWithoutAS =
3003 Context.removeAddrSpaceQualType(FromRecordType);
3004 QualType FromTypeWithDestAS =
3005 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3006 if (PointerConversions)
3007 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3008 From = ImpCastExprToType(From, FromTypeWithDestAS,
3009 CK_AddressSpaceConversion, From->getValueKind())
3010 .get();
3011 }
3012 } else {
3013 // No conversion necessary.
3014 return From;
3015 }
3016
3017 if (DestType->isDependentType() || FromType->isDependentType())
3018 return From;
3019
3020 // If the unqualified types are the same, no conversion is necessary.
3021 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3022 return From;
3023
3024 SourceRange FromRange = From->getSourceRange();
3025 SourceLocation FromLoc = FromRange.getBegin();
3026
3027 ExprValueKind VK = From->getValueKind();
3028
3029 // C++ [class.member.lookup]p8:
3030 // [...] Ambiguities can often be resolved by qualifying a name with its
3031 // class name.
3032 //
3033 // If the member was a qualified name and the qualified referred to a
3034 // specific base subobject type, we'll cast to that intermediate type
3035 // first and then to the object in which the member is declared. That allows
3036 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3037 //
3038 // class Base { public: int x; };
3039 // class Derived1 : public Base { };
3040 // class Derived2 : public Base { };
3041 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3042 //
3043 // void VeryDerived::f() {
3044 // x = 17; // error: ambiguous base subobjects
3045 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3046 // }
3047 if (Qualifier && Qualifier->getAsType()) {
3048 QualType QType = QualType(Qualifier->getAsType(), 0);
3049 assert(QType->isRecordType() && "lookup done with non-record type");
3050
3051 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3052
3053 // In C++98, the qualifier type doesn't actually have to be a base
3054 // type of the object type, in which case we just ignore it.
3055 // Otherwise build the appropriate casts.
3056 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3057 CXXCastPath BasePath;
3058 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3059 FromLoc, FromRange, &BasePath))
3060 return ExprError();
3061
3062 if (PointerConversions)
3063 QType = Context.getPointerType(QType);
3064 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3065 VK, &BasePath).get();
3066
3067 FromType = QType;
3068 FromRecordType = QRecordType;
3069
3070 // If the qualifier type was the same as the destination type,
3071 // we're done.
3072 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3073 return From;
3074 }
3075 }
3076
3077 CXXCastPath BasePath;
3078 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3079 FromLoc, FromRange, &BasePath,
3080 /*IgnoreAccess=*/true))
3081 return ExprError();
3082
3083 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3084 VK, &BasePath);
3085}
3086
3088 const LookupResult &R,
3089 bool HasTrailingLParen) {
3090 // Only when used directly as the postfix-expression of a call.
3091 if (!HasTrailingLParen)
3092 return false;
3093
3094 // Never if a scope specifier was provided.
3095 if (SS.isNotEmpty())
3096 return false;
3097
3098 // Only in C++ or ObjC++.
3099 if (!getLangOpts().CPlusPlus)
3100 return false;
3101
3102 // Turn off ADL when we find certain kinds of declarations during
3103 // normal lookup:
3104 for (const NamedDecl *D : R) {
3105 // C++0x [basic.lookup.argdep]p3:
3106 // -- a declaration of a class member
3107 // Since using decls preserve this property, we check this on the
3108 // original decl.
3109 if (D->isCXXClassMember())
3110 return false;
3111
3112 // C++0x [basic.lookup.argdep]p3:
3113 // -- a block-scope function declaration that is not a
3114 // using-declaration
3115 // NOTE: we also trigger this for function templates (in fact, we
3116 // don't check the decl type at all, since all other decl types
3117 // turn off ADL anyway).
3118 if (isa<UsingShadowDecl>(D))
3119 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3121 return false;
3122
3123 // C++0x [basic.lookup.argdep]p3:
3124 // -- a declaration that is neither a function or a function
3125 // template
3126 // And also for builtin functions.
3127 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3128 // But also builtin functions.
3129 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3130 return false;
3131 } else if (!isa<FunctionTemplateDecl>(D))
3132 return false;
3133 }
3134
3135 return true;
3136}
3137
3138
3139/// Diagnoses obvious problems with the use of the given declaration
3140/// as an expression. This is only actually called for lookups that
3141/// were not overloaded, and it doesn't promise that the declaration
3142/// will in fact be used.
3144 bool AcceptInvalid) {
3145 if (D->isInvalidDecl() && !AcceptInvalid)
3146 return true;
3147
3148 if (isa<TypedefNameDecl>(D)) {
3149 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3150 return true;
3151 }
3152
3153 if (isa<ObjCInterfaceDecl>(D)) {
3154 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3155 return true;
3156 }
3157
3158 if (isa<NamespaceDecl>(D)) {
3159 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3160 return true;
3161 }
3162
3163 return false;
3164}
3165
3166// Certain multiversion types should be treated as overloaded even when there is
3167// only one result.
3169 assert(R.isSingleResult() && "Expected only a single result");
3170 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3171 return FD &&
3172 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3173}
3174
3176 LookupResult &R, bool NeedsADL,
3177 bool AcceptInvalidDecl) {
3178 // If this is a single, fully-resolved result and we don't need ADL,
3179 // just build an ordinary singleton decl ref.
3180 if (!NeedsADL && R.isSingleResult() &&
3184 R.getRepresentativeDecl(), nullptr,
3185 AcceptInvalidDecl);
3186
3187 // We only need to check the declaration if there's exactly one
3188 // result, because in the overloaded case the results can only be
3189 // functions and function templates.
3191 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3192 AcceptInvalidDecl))
3193 return ExprError();
3194
3195 // Otherwise, just build an unresolved lookup expression. Suppress
3196 // any lookup-related diagnostics; we'll hash these out later, when
3197 // we've picked a target.
3199
3202 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3203 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3204
3205 return ULE;
3206}
3207
3209 SourceLocation loc,
3210 ValueDecl *var);
3211
3213 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3214 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3215 bool AcceptInvalidDecl) {
3216 assert(D && "Cannot refer to a NULL declaration");
3217 assert(!isa<FunctionTemplateDecl>(D) &&
3218 "Cannot refer unambiguously to a function template");
3219
3220 SourceLocation Loc = NameInfo.getLoc();
3221 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3222 // Recovery from invalid cases (e.g. D is an invalid Decl).
3223 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3224 // diagnostics, as invalid decls use int as a fallback type.
3225 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3226 }
3227
3228 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3229 // Specifically diagnose references to class templates that are missing
3230 // a template argument list.
3231 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3232 return ExprError();
3233 }
3234
3235 // Make sure that we're referring to a value.
3236 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3237 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3238 Diag(D->getLocation(), diag::note_declared_at);
3239 return ExprError();
3240 }
3241
3242 // Check whether this declaration can be used. Note that we suppress
3243 // this check when we're going to perform argument-dependent lookup
3244 // on this function name, because this might not be the function
3245 // that overload resolution actually selects.
3246 if (DiagnoseUseOfDecl(D, Loc))
3247 return ExprError();
3248
3249 auto *VD = cast<ValueDecl>(D);
3250
3251 // Only create DeclRefExpr's for valid Decl's.
3252 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3253 return ExprError();
3254
3255 // Handle members of anonymous structs and unions. If we got here,
3256 // and the reference is to a class member indirect field, then this
3257 // must be the subject of a pointer-to-member expression.
3258 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3259 IndirectField && !IndirectField->isCXXClassMember())
3261 IndirectField);
3262
3263 QualType type = VD->getType();
3264 if (type.isNull())
3265 return ExprError();
3266 ExprValueKind valueKind = VK_PRValue;
3267
3268 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3269 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3270 // is expanded by some outer '...' in the context of the use.
3271 type = type.getNonPackExpansionType();
3272
3273 switch (D->getKind()) {
3274 // Ignore all the non-ValueDecl kinds.
3275#define ABSTRACT_DECL(kind)
3276#define VALUE(type, base)
3277#define DECL(type, base) case Decl::type:
3278#include "clang/AST/DeclNodes.inc"
3279 llvm_unreachable("invalid value decl kind");
3280
3281 // These shouldn't make it here.
3282 case Decl::ObjCAtDefsField:
3283 llvm_unreachable("forming non-member reference to ivar?");
3284
3285 // Enum constants are always r-values and never references.
3286 // Unresolved using declarations are dependent.
3287 case Decl::EnumConstant:
3288 case Decl::UnresolvedUsingValue:
3289 case Decl::OMPDeclareReduction:
3290 case Decl::OMPDeclareMapper:
3291 valueKind = VK_PRValue;
3292 break;
3293
3294 // Fields and indirect fields that got here must be for
3295 // pointer-to-member expressions; we just call them l-values for
3296 // internal consistency, because this subexpression doesn't really
3297 // exist in the high-level semantics.
3298 case Decl::Field:
3299 case Decl::IndirectField:
3300 case Decl::ObjCIvar:
3301 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3302 "building reference to field in C?");
3303
3304 // These can't have reference type in well-formed programs, but
3305 // for internal consistency we do this anyway.
3306 type = type.getNonReferenceType();
3307 valueKind = VK_LValue;
3308 break;
3309
3310 // Non-type template parameters are either l-values or r-values
3311 // depending on the type.
3312 case Decl::NonTypeTemplateParm: {
3313 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3314 type = reftype->getPointeeType();
3315 valueKind = VK_LValue; // even if the parameter is an r-value reference
3316 break;
3317 }
3318
3319 // [expr.prim.id.unqual]p2:
3320 // If the entity is a template parameter object for a template
3321 // parameter of type T, the type of the expression is const T.
3322 // [...] The expression is an lvalue if the entity is a [...] template
3323 // parameter object.
3324 if (type->isRecordType()) {
3325 type = type.getUnqualifiedType().withConst();
3326 valueKind = VK_LValue;
3327 break;
3328 }
3329
3330 // For non-references, we need to strip qualifiers just in case
3331 // the template parameter was declared as 'const int' or whatever.
3332 valueKind = VK_PRValue;
3333 type = type.getUnqualifiedType();
3334 break;
3335 }
3336
3337 case Decl::Var:
3338 case Decl::VarTemplateSpecialization:
3339 case Decl::VarTemplatePartialSpecialization:
3340 case Decl::Decomposition:
3341 case Decl::OMPCapturedExpr:
3342 // In C, "extern void blah;" is valid and is an r-value.
3343 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3344 type->isVoidType()) {
3345 valueKind = VK_PRValue;
3346 break;
3347 }
3348 [[fallthrough]];
3349
3350 case Decl::ImplicitParam:
3351 case Decl::ParmVar: {
3352 // These are always l-values.
3353 valueKind = VK_LValue;
3354 type = type.getNonReferenceType();
3355
3356 // FIXME: Does the addition of const really only apply in
3357 // potentially-evaluated contexts? Since the variable isn't actually
3358 // captured in an unevaluated context, it seems that the answer is no.
3359 if (!isUnevaluatedContext()) {
3360 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3361 if (!CapturedType.isNull())
3362 type = CapturedType;
3363 }
3364
3365 break;
3366 }
3367
3368 case Decl::Binding:
3369 // These are always lvalues.
3370 valueKind = VK_LValue;
3371 type = type.getNonReferenceType();
3372 break;
3373
3374 case Decl::Function: {
3375 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3378 valueKind = VK_PRValue;
3379 break;
3380 }
3381 }
3382
3383 const FunctionType *fty = type->castAs<FunctionType>();
3384
3385 // If we're referring to a function with an __unknown_anytype
3386 // result type, make the entire expression __unknown_anytype.
3387 if (fty->getReturnType() == Context.UnknownAnyTy) {
3389 valueKind = VK_PRValue;
3390 break;
3391 }
3392
3393 // Functions are l-values in C++.
3394 if (getLangOpts().CPlusPlus) {
3395 valueKind = VK_LValue;
3396 break;
3397 }
3398
3399 // C99 DR 316 says that, if a function type comes from a
3400 // function definition (without a prototype), that type is only
3401 // used for checking compatibility. Therefore, when referencing
3402 // the function, we pretend that we don't have the full function
3403 // type.
3404 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3406 fty->getExtInfo());
3407
3408 // Functions are r-values in C.
3409 valueKind = VK_PRValue;
3410 break;
3411 }
3412
3413 case Decl::CXXDeductionGuide:
3414 llvm_unreachable("building reference to deduction guide");
3415
3416 case Decl::MSProperty:
3417 case Decl::MSGuid:
3418 case Decl::TemplateParamObject:
3419 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3420 // capture in OpenMP, or duplicated between host and device?
3421 valueKind = VK_LValue;
3422 break;
3423
3424 case Decl::UnnamedGlobalConstant:
3425 valueKind = VK_LValue;
3426 break;
3427
3428 case Decl::CXXMethod:
3429 // If we're referring to a method with an __unknown_anytype
3430 // result type, make the entire expression __unknown_anytype.
3431 // This should only be possible with a type written directly.
3432 if (const FunctionProtoType *proto =
3433 dyn_cast<FunctionProtoType>(VD->getType()))
3434 if (proto->getReturnType() == Context.UnknownAnyTy) {
3436 valueKind = VK_PRValue;
3437 break;
3438 }
3439
3440 // C++ methods are l-values if static, r-values if non-static.
3441 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3442 valueKind = VK_LValue;
3443 break;
3444 }
3445 [[fallthrough]];
3446
3447 case Decl::CXXConversion:
3448 case Decl::CXXDestructor:
3449 case Decl::CXXConstructor:
3450 valueKind = VK_PRValue;
3451 break;
3452 }
3453
3454 auto *E =
3455 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3456 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3457 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3458 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3459 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3460 // diagnostics).
3461 if (VD->isInvalidDecl() && E)
3462 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3463 return E;
3464}
3465
3466static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3468 Target.resize(CharByteWidth * (Source.size() + 1));
3469 char *ResultPtr = &Target[0];
3470 const llvm::UTF8 *ErrorPtr;
3471 bool success =
3472 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3473 (void)success;
3474 assert(success);
3475 Target.resize(ResultPtr - &Target[0]);
3476}
3477
3480 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3481 if (!currentDecl) {
3482 Diag(Loc, diag::ext_predef_outside_function);
3483 currentDecl = Context.getTranslationUnitDecl();
3484 }
3485
3486 QualType ResTy;
3487 StringLiteral *SL = nullptr;
3488 if (cast<DeclContext>(currentDecl)->isDependentContext())
3489 ResTy = Context.DependentTy;
3490 else {
3491 // Pre-defined identifiers are of type char[x], where x is the length of
3492 // the string.
3493 bool ForceElaboratedPrinting =
3494 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3495 auto Str =
3496 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3497 unsigned Length = Str.length();
3498
3499 llvm::APInt LengthI(32, Length + 1);
3502 ResTy =
3504 SmallString<32> RawChars;
3506 Str, RawChars);
3507 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3509 /*IndexTypeQuals*/ 0);
3511 /*Pascal*/ false, ResTy, Loc);
3512 } else {
3514 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3516 /*IndexTypeQuals*/ 0);
3518 /*Pascal*/ false, ResTy, Loc);
3519 }
3520 }
3521
3522 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3523 SL);
3524}
3525
3528}
3529
3531 SmallString<16> CharBuffer;
3532 bool Invalid = false;
3533 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3534 if (Invalid)
3535 return ExprError();
3536
3537 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3538 PP, Tok.getKind());
3539 if (Literal.hadError())
3540 return ExprError();
3541
3542 QualType Ty;
3543 if (Literal.isWide())
3544 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3545 else if (Literal.isUTF8() && getLangOpts().C23)
3546 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3547 else if (Literal.isUTF8() && getLangOpts().Char8)
3548 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3549 else if (Literal.isUTF16())
3550 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3551 else if (Literal.isUTF32())
3552 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3553 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3554 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3555 else
3556 Ty = Context.CharTy; // 'x' -> char in C++;
3557 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3558
3560 if (Literal.isWide())
3562 else if (Literal.isUTF16())
3564 else if (Literal.isUTF32())
3566 else if (Literal.isUTF8())
3568
3569 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3570 Tok.getLocation());
3571
3572 if (Literal.getUDSuffix().empty())
3573 return Lit;
3574
3575 // We're building a user-defined literal.
3576 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3577 SourceLocation UDSuffixLoc =
3578 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3579
3580 // Make sure we're allowed user-defined literals here.
3581 if (!UDLScope)
3582 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3583
3584 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3585 // operator "" X (ch)
3586 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3587 Lit, Tok.getLocation());
3588}
3589
3591 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3592 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3593 Context.IntTy, Loc);
3594}
3595
3598 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3599
3600 using llvm::APFloat;
3601 APFloat Val(Format);
3602
3603 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3604 if (RM == llvm::RoundingMode::Dynamic)
3605 RM = llvm::RoundingMode::NearestTiesToEven;
3606 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3607
3608 // Overflow is always an error, but underflow is only an error if
3609 // we underflowed to zero (APFloat reports denormals as underflow).
3610 if ((result & APFloat::opOverflow) ||
3611 ((result & APFloat::opUnderflow) && Val.isZero())) {
3612 unsigned diagnostic;
3613 SmallString<20> buffer;
3614 if (result & APFloat::opOverflow) {
3615 diagnostic = diag::warn_float_overflow;
3616 APFloat::getLargest(Format).toString(buffer);
3617 } else {
3618 diagnostic = diag::warn_float_underflow;
3619 APFloat::getSmallest(Format).toString(buffer);
3620 }
3621
3622 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3623 }
3624
3625 bool isExact = (result == APFloat::opOK);
3626 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3627}
3628
3630 assert(E && "Invalid expression");
3631
3632 if (E->isValueDependent())
3633 return false;
3634
3635 QualType QT = E->getType();
3636 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3637 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3638 return true;
3639 }
3640
3641 llvm::APSInt ValueAPS;
3643
3644 if (R.isInvalid())
3645 return true;
3646
3647 // GCC allows the value of unroll count to be 0.
3648 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3649 // "The values of 0 and 1 block any unrolling of the loop."
3650 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3651 // '#pragma unroll' cases.
3652 bool ValueIsPositive =
3653 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3654 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3655 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3656 << toString(ValueAPS, 10) << ValueIsPositive;
3657 return true;
3658 }
3659
3660 return false;
3661}
3662
3664 // Fast path for a single digit (which is quite common). A single digit
3665 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3666 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3667 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3668 return ActOnIntegerConstant(Tok.getLocation(), Val);
3669 }
3670
3671 SmallString<128> SpellingBuffer;
3672 // NumericLiteralParser wants to overread by one character. Add padding to
3673 // the buffer in case the token is copied to the buffer. If getSpelling()
3674 // returns a StringRef to the memory buffer, it should have a null char at
3675 // the EOF, so it is also safe.
3676 SpellingBuffer.resize(Tok.getLength() + 1);
3677
3678 // Get the spelling of the token, which eliminates trigraphs, etc.
3679 bool Invalid = false;
3680 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3681 if (Invalid)
3682 return ExprError();
3683
3684 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3687 if (Literal.hadError)
3688 return ExprError();
3689
3690 if (Literal.hasUDSuffix()) {
3691 // We're building a user-defined literal.
3692 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3693 SourceLocation UDSuffixLoc =
3694 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3695
3696 // Make sure we're allowed user-defined literals here.
3697 if (!UDLScope)
3698 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3699
3700 QualType CookedTy;
3701 if (Literal.isFloatingLiteral()) {
3702 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3703 // long double, the literal is treated as a call of the form
3704 // operator "" X (f L)
3705 CookedTy = Context.LongDoubleTy;
3706 } else {
3707 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3708 // unsigned long long, the literal is treated as a call of the form
3709 // operator "" X (n ULL)
3710 CookedTy = Context.UnsignedLongLongTy;
3711 }
3712
3713 DeclarationName OpName =
3715 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3716 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3717
3718 SourceLocation TokLoc = Tok.getLocation();
3719
3720 // Perform literal operator lookup to determine if we're building a raw
3721 // literal or a cooked one.
3722 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3723 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3724 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3725 /*AllowStringTemplatePack*/ false,
3726 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3728 // Lookup failure for imaginary constants isn't fatal, there's still the
3729 // GNU extension producing _Complex types.
3730 break;
3731 case LOLR_Error:
3732 return ExprError();
3733 case LOLR_Cooked: {
3734 Expr *Lit;
3735 if (Literal.isFloatingLiteral()) {
3736 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3737 } else {
3738 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3739 if (Literal.GetIntegerValue(ResultVal))
3740 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3741 << /* Unsigned */ 1;
3742 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3743 Tok.getLocation());
3744 }
3745 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3746 }
3747
3748 case LOLR_Raw: {
3749 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3750 // literal is treated as a call of the form
3751 // operator "" X ("n")
3752 unsigned Length = Literal.getUDSuffixOffset();
3755 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3756 Expr *Lit =
3757 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3759 /*Pascal*/ false, StrTy, &TokLoc, 1);
3760 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3761 }
3762
3763 case LOLR_Template: {
3764 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3765 // template), L is treated as a call fo the form
3766 // operator "" X <'c1', 'c2', ... 'ck'>()
3767 // where n is the source character sequence c1 c2 ... ck.
3768 TemplateArgumentListInfo ExplicitArgs;
3769 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3770 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3771 llvm::APSInt Value(CharBits, CharIsUnsigned);
3772 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3773 Value = TokSpelling[I];
3776 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3777 }
3778 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
3779 &ExplicitArgs);
3780 }
3782 llvm_unreachable("unexpected literal operator lookup result");
3783 }
3784 }
3785
3786 Expr *Res;
3787
3788 if (Literal.isFixedPointLiteral()) {
3789 QualType Ty;
3790
3791 if (Literal.isAccum) {
3792 if (Literal.isHalf) {
3793 Ty = Context.ShortAccumTy;
3794 } else if (Literal.isLong) {
3795 Ty = Context.LongAccumTy;
3796 } else {
3797 Ty = Context.AccumTy;
3798 }
3799 } else if (Literal.isFract) {
3800 if (Literal.isHalf) {
3801 Ty = Context.ShortFractTy;
3802 } else if (Literal.isLong) {
3803 Ty = Context.LongFractTy;
3804 } else {
3805 Ty = Context.FractTy;
3806 }
3807 }
3808
3809 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3810
3811 bool isSigned = !Literal.isUnsigned;
3812 unsigned scale = Context.getFixedPointScale(Ty);
3813 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3814
3815 llvm::APInt Val(bit_width, 0, isSigned);
3816 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3817 bool ValIsZero = Val.isZero() && !Overflowed;
3818
3819 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3820 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3821 // Clause 6.4.4 - The value of a constant shall be in the range of
3822 // representable values for its type, with exception for constants of a
3823 // fract type with a value of exactly 1; such a constant shall denote
3824 // the maximal value for the type.
3825 --Val;
3826 else if (Val.ugt(MaxVal) || Overflowed)
3827 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3828
3830 Tok.getLocation(), scale);
3831 } else if (Literal.isFloatingLiteral()) {
3832 QualType Ty;
3833 if (Literal.isHalf){
3834 if (getLangOpts().HLSL ||
3835 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3836 Ty = Context.HalfTy;
3837 else {
3838 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3839 return ExprError();
3840 }
3841 } else if (Literal.isFloat)
3842 Ty = Context.FloatTy;
3843 else if (Literal.isLong)
3845 else if (Literal.isFloat16)
3846 Ty = Context.Float16Ty;
3847 else if (Literal.isFloat128)
3848 Ty = Context.Float128Ty;
3849 else if (getLangOpts().HLSL)
3850 Ty = Context.FloatTy;
3851 else
3852 Ty = Context.DoubleTy;
3853
3854 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3855
3856 if (Ty == Context.DoubleTy) {
3857 if (getLangOpts().SinglePrecisionConstants) {
3858 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3859 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3860 }
3861 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3862 "cl_khr_fp64", getLangOpts())) {
3863 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3864 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3866 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3867 }
3868 }
3869 } else if (!Literal.isIntegerLiteral()) {
3870 return ExprError();
3871 } else {
3872 QualType Ty;
3873
3874 // 'z/uz' literals are a C++23 feature.
3875 if (Literal.isSizeT)
3878 ? diag::warn_cxx20_compat_size_t_suffix
3879 : diag::ext_cxx23_size_t_suffix
3880 : diag::err_cxx23_size_t_suffix);
3881
3882 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
3883 // but we do not currently support the suffix in C++ mode because it's not
3884 // entirely clear whether WG21 will prefer this suffix to return a library
3885 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
3886 // literals are a C++ extension.
3887 if (Literal.isBitInt)
3888 PP.Diag(Tok.getLocation(),
3889 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
3890 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
3891 : diag::ext_c23_bitint_suffix);
3892
3893 // Get the value in the widest-possible width. What is "widest" depends on
3894 // whether the literal is a bit-precise integer or not. For a bit-precise
3895 // integer type, try to scan the source to determine how many bits are
3896 // needed to represent the value. This may seem a bit expensive, but trying
3897 // to get the integer value from an overly-wide APInt is *extremely*
3898 // expensive, so the naive approach of assuming
3899 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3900 unsigned BitsNeeded =
3901 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3902 Literal.getLiteralDigits(), Literal.getRadix())
3904 llvm::APInt ResultVal(BitsNeeded, 0);
3905
3906 if (Literal.GetIntegerValue(ResultVal)) {
3907 // If this value didn't fit into uintmax_t, error and force to ull.
3908 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3909 << /* Unsigned */ 1;
3911 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3912 "long long is not intmax_t?");
3913 } else {
3914 // If this value fits into a ULL, try to figure out what else it fits into
3915 // according to the rules of C99 6.4.4.1p5.
3916
3917 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3918 // be an unsigned int.
3919 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3920
3921 // HLSL doesn't really have `long` or `long long`. We support the `ll`
3922 // suffix for portability of code with C++, but both `l` and `ll` are
3923 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
3924 // same.
3925 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
3926 Literal.isLong = true;
3927 Literal.isLongLong = false;
3928 }
3929
3930 // Check from smallest to largest, picking the smallest type we can.
3931 unsigned Width = 0;
3932
3933 // Microsoft specific integer suffixes are explicitly sized.
3934 if (Literal.MicrosoftInteger) {
3935 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3936 Width = 8;
3937 Ty = Context.CharTy;
3938 } else {
3939 Width = Literal.MicrosoftInteger;
3940 Ty = Context.getIntTypeForBitwidth(Width,
3941 /*Signed=*/!Literal.isUnsigned);
3942 }
3943 }
3944
3945 // Bit-precise integer literals are automagically-sized based on the
3946 // width required by the literal.
3947 if (Literal.isBitInt) {
3948 // The signed version has one more bit for the sign value. There are no
3949 // zero-width bit-precise integers, even if the literal value is 0.
3950 Width = std::max(ResultVal.getActiveBits(), 1u) +
3951 (Literal.isUnsigned ? 0u : 1u);
3952
3953 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
3954 // and reset the type to the largest supported width.
3955 unsigned int MaxBitIntWidth =
3957 if (Width > MaxBitIntWidth) {
3958 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3959 << Literal.isUnsigned;
3960 Width = MaxBitIntWidth;
3961 }
3962
3963 // Reset the result value to the smaller APInt and select the correct
3964 // type to be used. Note, we zext even for signed values because the
3965 // literal itself is always an unsigned value (a preceeding - is a
3966 // unary operator, not part of the literal).
3967 ResultVal = ResultVal.zextOrTrunc(Width);
3968 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
3969 }
3970
3971 // Check C++23 size_t literals.
3972 if (Literal.isSizeT) {
3973 assert(!Literal.MicrosoftInteger &&
3974 "size_t literals can't be Microsoft literals");
3975 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3977
3978 // Does it fit in size_t?
3979 if (ResultVal.isIntN(SizeTSize)) {
3980 // Does it fit in ssize_t?
3981 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3983 else if (AllowUnsigned)
3984 Ty = Context.getSizeType();
3985 Width = SizeTSize;
3986 }
3987 }
3988
3989 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3990 !Literal.isSizeT) {
3991 // Are int/unsigned possibilities?
3992 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3993
3994 // Does it fit in a unsigned int?
3995 if (ResultVal.isIntN(IntSize)) {
3996 // Does it fit in a signed int?
3997 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3998 Ty = Context.IntTy;
3999 else if (AllowUnsigned)
4001 Width = IntSize;
4002 }
4003 }
4004
4005 // Are long/unsigned long possibilities?
4006 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4007 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4008
4009 // Does it fit in a unsigned long?
4010 if (ResultVal.isIntN(LongSize)) {
4011 // Does it fit in a signed long?
4012 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4013 Ty = Context.LongTy;
4014 else if (AllowUnsigned)
4016 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4017 // is compatible.
4018 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4019 const unsigned LongLongSize =
4021 Diag(Tok.getLocation(),
4023 ? Literal.isLong
4024 ? diag::warn_old_implicitly_unsigned_long_cxx
4025 : /*C++98 UB*/ diag::
4026 ext_old_implicitly_unsigned_long_cxx
4027 : diag::warn_old_implicitly_unsigned_long)
4028 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4029 : /*will be ill-formed*/ 1);
4031 }
4032 Width = LongSize;
4033 }
4034 }
4035
4036 // Check long long if needed.
4037 if (Ty.isNull() && !Literal.isSizeT) {
4038 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4039
4040 // Does it fit in a unsigned long long?
4041 if (ResultVal.isIntN(LongLongSize)) {
4042 // Does it fit in a signed long long?
4043 // To be compatible with MSVC, hex integer literals ending with the
4044 // LL or i64 suffix are always signed in Microsoft mode.
4045 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4046 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4047 Ty = Context.LongLongTy;
4048 else if (AllowUnsigned)
4050 Width = LongLongSize;
4051
4052 // 'long long' is a C99 or C++11 feature, whether the literal
4053 // explicitly specified 'long long' or we needed the extra width.
4054 if (getLangOpts().CPlusPlus)
4055 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4056 ? diag::warn_cxx98_compat_longlong
4057 : diag::ext_cxx11_longlong);
4058 else if (!getLangOpts().C99)
4059 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4060 }
4061 }
4062
4063 // If we still couldn't decide a type, we either have 'size_t' literal
4064 // that is out of range, or a decimal literal that does not fit in a
4065 // signed long long and has no U suffix.
4066 if (Ty.isNull()) {
4067 if (Literal.isSizeT)
4068 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4069 << Literal.isUnsigned;
4070 else
4071 Diag(Tok.getLocation(),
4072 diag::ext_integer_literal_too_large_for_signed);
4075 }
4076
4077 if (ResultVal.getBitWidth() != Width)
4078 ResultVal = ResultVal.trunc(Width);
4079 }
4080 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4081 }
4082
4083 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4084 if (Literal.isImaginary) {
4085 Res = new (Context) ImaginaryLiteral(Res,
4087
4088 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4089 }
4090 return Res;
4091}
4092
4094 assert(E && "ActOnParenExpr() missing expr");
4095 QualType ExprTy = E->getType();
4096 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4097 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4098 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4099 return new (Context) ParenExpr(L, R, E);
4100}
4101
4104 SourceRange ArgRange) {
4105 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4106 // scalar or vector data type argument..."
4107 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4108 // type (C99 6.2.5p18) or void.
4109 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4110 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4111 << T << ArgRange;
4112 return true;
4113 }
4114
4115 assert((T->isVoidType() || !T->isIncompleteType()) &&
4116 "Scalar types should always be complete");
4117 return false;
4118}
4119
4122 SourceRange ArgRange) {
4123 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4124 if (!T->isVectorType() && !T->isSizelessVectorType())
4125 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4126 << ""
4127 << "__builtin_vectorelements" << T << ArgRange;
4128
4129 return false;
4130}
4131
4134 SourceRange ArgRange) {
4135 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4136 return true;
4137
4138 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4140 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4141 return true;
4142 }
4143
4144 return false;
4145}
4146
4149 SourceRange ArgRange,
4150 UnaryExprOrTypeTrait TraitKind) {
4151 // Invalid types must be hard errors for SFINAE in C++.
4152 if (S.LangOpts.CPlusPlus)
4153 return true;
4154
4155 // C99 6.5.3.4p1:
4156 if (T->isFunctionType() &&
4157 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4158 TraitKind == UETT_PreferredAlignOf)) {
4159 // sizeof(function)/alignof(function) is allowed as an extension.
4160 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4161 << getTraitSpelling(TraitKind) << ArgRange;
4162 return false;
4163 }
4164
4165 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4166 // this is an error (OpenCL v1.1 s6.3.k)
4167 if (T->isVoidType()) {
4168 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4169 : diag::ext_sizeof_alignof_void_type;
4170 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4171 return false;
4172 }
4173
4174 return true;
4175}
4176
4179 SourceRange ArgRange,
4180 UnaryExprOrTypeTrait TraitKind) {
4181 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4182 // runtime doesn't allow it.
4184 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4185 << T << (TraitKind == UETT_SizeOf)
4186 << ArgRange;
4187 return true;
4188 }
4189
4190 return false;
4191}
4192
4193/// Check whether E is a pointer from a decayed array type (the decayed
4194/// pointer type is equal to T) and emit a warning if it is.
4196 const Expr *E) {
4197 // Don't warn if the operation changed the type.
4198 if (T != E->getType())
4199 return;
4200
4201 // Now look for array decays.
4202 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4203 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4204 return;
4205
4206 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4207 << ICE->getType()
4208 << ICE->getSubExpr()->getType();
4209}
4210
4212 UnaryExprOrTypeTrait ExprKind) {
4213 QualType ExprTy = E->getType();
4214 assert(!ExprTy->isReferenceType());
4215
4216 bool IsUnevaluatedOperand =
4217 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4218 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4219 ExprKind == UETT_VecStep);
4220 if (IsUnevaluatedOperand) {
4222 if (Result.isInvalid())
4223 return true;
4224 E = Result.get();
4225 }
4226
4227 // The operand for sizeof and alignof is in an unevaluated expression context,
4228 // so side effects could result in unintended consequences.
4229 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4230 // used to build SFINAE gadgets.
4231 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4232 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4234 !E->getType()->isVariableArrayType() &&
4235 E->HasSideEffects(Context, false))
4236 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4237
4238 if (ExprKind == UETT_VecStep)
4239 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4240 E->getSourceRange());
4241
4242 if (ExprKind == UETT_VectorElements)
4243 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4244 E->getSourceRange());
4245
4246 // Explicitly list some types as extensions.
4247 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4248 E->getSourceRange(), ExprKind))
4249 return false;
4250
4251 // WebAssembly tables are always illegal operands to unary expressions and
4252 // type traits.
4253 if (Context.getTargetInfo().getTriple().isWasm() &&
4255 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4256 << getTraitSpelling(ExprKind);
4257 return true;
4258 }
4259
4260 // 'alignof' applied to an expression only requires the base element type of
4261 // the expression to be complete. 'sizeof' requires the expression's type to
4262 // be complete (and will attempt to complete it if it's an array of unknown
4263 // bound).
4264 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4267 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4268 getTraitSpelling(ExprKind), E->getSourceRange()))
4269 return true;
4270 } else {
4272 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4273 getTraitSpelling(ExprKind), E->getSourceRange()))
4274 return true;
4275 }
4276
4277 // Completing the expression's type may have changed it.
4278 ExprTy = E->getType();
4279 assert(!ExprTy->isReferenceType());
4280
4281 if (ExprTy->isFunctionType()) {
4282 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4283 << getTraitSpelling(ExprKind) << E->getSourceRange();
4284 return true;
4285 }
4286
4287 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4288 E->getSourceRange(), ExprKind))
4289 return true;
4290
4291 if (ExprKind == UETT_SizeOf) {
4292 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4293 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4294 QualType OType = PVD->getOriginalType();
4295 QualType Type = PVD->getType();
4296 if (Type->isPointerType() && OType->isArrayType()) {
4297 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4298 << Type << OType;
4299 Diag(PVD->getLocation(), diag::note_declared_at);
4300 }
4301 }
4302 }
4303
4304 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4305 // decays into a pointer and returns an unintended result. This is most
4306 // likely a typo for "sizeof(array) op x".
4307 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4308 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4309 BO->getLHS());
4310 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4311 BO->getRHS());
4312 }
4313 }
4314
4315 return false;
4316}
4317
4318static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4319 // Cannot know anything else if the expression is dependent.
4320 if (E->isTypeDependent())
4321 return false;
4322
4323 if (E->getObjectKind() == OK_BitField) {
4324 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4325 << 1 << E->getSourceRange();
4326 return true;
4327 }
4328
4329 ValueDecl *D = nullptr;
4330 Expr *Inner = E->IgnoreParens();
4331 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4332 D = DRE->getDecl();
4333 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4334 D = ME->getMemberDecl();
4335 }
4336
4337 // If it's a field, require the containing struct to have a
4338 // complete definition so that we can compute the layout.
4339 //
4340 // This can happen in C++11 onwards, either by naming the member
4341 // in a way that is not transformed into a member access expression
4342 // (in an unevaluated operand, for instance), or by naming the member
4343 // in a trailing-return-type.
4344 //
4345 // For the record, since __alignof__ on expressions is a GCC
4346 // extension, GCC seems to permit this but always gives the
4347 // nonsensical answer 0.
4348 //
4349 // We don't really need the layout here --- we could instead just
4350 // directly check for all the appropriate alignment-lowing
4351 // attributes --- but that would require duplicating a lot of
4352 // logic that just isn't worth duplicating for such a marginal
4353 // use-case.
4354 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4355 // Fast path this check, since we at least know the record has a
4356 // definition if we can find a member of it.
4357 if (!FD->getParent()->isCompleteDefinition()) {
4358 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4359 << E->getSourceRange();
4360 return true;
4361 }
4362
4363 // Otherwise, if it's a field, and the field doesn't have
4364 // reference type, then it must have a complete type (or be a
4365 // flexible array member, which we explicitly want to
4366 // white-list anyway), which makes the following checks trivial.
4367 if (!FD->getType()->isReferenceType())
4368 return false;
4369 }
4370
4371 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4372}
4373
4375 E = E->IgnoreParens();
4376
4377 // Cannot know anything else if the expression is dependent.
4378 if (E->isTypeDependent())
4379 return false;
4380
4381 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4382}
4383
4385 CapturingScopeInfo *CSI) {
4386 assert(T->isVariablyModifiedType());
4387 assert(CSI != nullptr);
4388
4389 // We're going to walk down into the type and look for VLA expressions.
4390 do {
4391 const Type *Ty = T.getTypePtr();
4392 switch (Ty->getTypeClass()) {
4393#define TYPE(Class, Base)
4394#define ABSTRACT_TYPE(Class, Base)
4395#define NON_CANONICAL_TYPE(Class, Base)
4396#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4397#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4398#include "clang/AST/TypeNodes.inc"
4399 T = QualType();
4400 break;
4401 // These types are never variably-modified.
4402 case Type::Builtin:
4403 case Type::Complex:
4404 case Type::Vector:
4405 case Type::ExtVector:
4406 case Type::ConstantMatrix:
4407 case Type::Record:
4408 case Type::Enum:
4409 case Type::TemplateSpecialization:
4410 case Type::ObjCObject:
4411 case Type::ObjCInterface:
4412 case Type::ObjCObjectPointer:
4413 case Type::ObjCTypeParam:
4414 case Type::Pipe:
4415 case Type::BitInt:
4416 llvm_unreachable("type class is never variably-modified!");
4417 case Type::Elaborated:
4418 T = cast<ElaboratedType>(Ty)->getNamedType();
4419 break;
4420 case Type::Adjusted:
4421 T = cast<AdjustedType>(Ty)->getOriginalType();
4422 break;
4423 case Type::Decayed:
4424 T = cast<DecayedType>(Ty)->getPointeeType();
4425 break;
4426 case Type::ArrayParameter:
4427 T = cast<ArrayParameterType>(Ty)->getElementType();
4428 break;
4429 case Type::Pointer:
4430 T = cast<PointerType>(Ty)->getPointeeType();
4431 break;
4432 case Type::BlockPointer:
4433 T = cast<BlockPointerType>(Ty)->getPointeeType();
4434 break;
4435 case Type::LValueReference:
4436 case Type::RValueReference:
4437 T = cast<ReferenceType>(Ty)->getPointeeType();
4438 break;
4439 case Type::MemberPointer:
4440 T = cast<MemberPointerType>(Ty)->getPointeeType();
4441 break;
4442 case Type::ConstantArray:
4443 case Type::IncompleteArray:
4444 // Losing element qualification here is fine.
4445 T = cast<ArrayType>(Ty)->getElementType();
4446 break;
4447 case Type::VariableArray: {
4448 // Losing element qualification here is fine.
4449 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4450
4451 // Unknown size indication requires no size computation.
4452 // Otherwise, evaluate and record it.
4453 auto Size = VAT->getSizeExpr();
4454 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4455 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4456 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4457
4458 T = VAT->getElementType();
4459 break;
4460 }
4461 case Type::FunctionProto:
4462 case Type::FunctionNoProto:
4463 T = cast<FunctionType>(Ty)->getReturnType();
4464 break;
4465 case Type::Paren:
4466 case Type::TypeOf:
4467 case Type::UnaryTransform:
4468 case Type::Attributed:
4469 case Type::BTFTagAttributed:
4470 case Type::SubstTemplateTypeParm:
4471 case Type::MacroQualified:
4472 case Type::CountAttributed:
4473 // Keep walking after single level desugaring.
4474 T = T.getSingleStepDesugaredType(Context);
4475 break;
4476 case Type::Typedef:
4477 T = cast<TypedefType>(Ty)->desugar();
4478 break;
4479 case Type::Decltype:
4480 T = cast<DecltypeType>(Ty)->desugar();
4481 break;
4482 case Type::PackIndexing:
4483 T = cast<PackIndexingType>(Ty)->desugar();
4484 break;
4485 case Type::Using:
4486 T = cast<UsingType>(Ty)->desugar();
4487 break;
4488 case Type::Auto:
4489 case Type::DeducedTemplateSpecialization:
4490 T = cast<DeducedType>(Ty)->getDeducedType();
4491 break;
4492 case Type::TypeOfExpr:
4493 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4494 break;
4495 case Type::Atomic:
4496 T = cast<AtomicType>(Ty)->getValueType();
4497 break;
4498 }
4499 } while (!T.isNull() && T->isVariablyModifiedType());
4500}
4501
4503 SourceLocation OpLoc,
4504 SourceRange ExprRange,
4505 UnaryExprOrTypeTrait ExprKind,
4506 StringRef KWName) {
4507 if (ExprType->isDependentType())
4508 return false;
4509
4510 // C++ [expr.sizeof]p2:
4511 // When applied to a reference or a reference type, the result
4512 // is the size of the referenced type.
4513 // C++11 [expr.alignof]p3:
4514 // When alignof is applied to a reference type, the result
4515 // shall be the alignment of the referenced type.
4516 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4517 ExprType = Ref->getPointeeType();
4518
4519 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4520 // When alignof or _Alignof is applied to an array type, the result
4521 // is the alignment of the element type.
4522 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4523 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4524 // If the trait is 'alignof' in C before C2y, the ability to apply the
4525 // trait to an incomplete array is an extension.
4526 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4527 ExprType->isIncompleteArrayType())
4528 Diag(OpLoc, getLangOpts().C2y
4529 ? diag::warn_c2y_compat_alignof_incomplete_array
4530 : diag::ext_c2y_alignof_incomplete_array);
4531 ExprType = Context.getBaseElementType(ExprType);
4532 }
4533
4534 if (ExprKind == UETT_VecStep)
4535 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4536
4537 if (ExprKind == UETT_VectorElements)
4538 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4539 ExprRange);
4540
4541 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4542 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4543 ExprRange);
4544
4545 // Explicitly list some types as extensions.
4546 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4547 ExprKind))
4548 return false;
4549
4551 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4552 KWName, ExprRange))
4553 return true;
4554
4555 if (ExprType->isFunctionType()) {
4556 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4557 return true;
4558 }
4559
4560 // WebAssembly tables are always illegal operands to unary expressions and
4561 // type traits.
4562 if (Context.getTargetInfo().getTriple().isWasm() &&
4563 ExprType->isWebAssemblyTableType()) {
4564 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4565 << getTraitSpelling(ExprKind);
4566 return true;
4567 }
4568
4569 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4570 ExprKind))
4571 return true;
4572
4573 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4574 if (auto *TT = ExprType->getAs<TypedefType>()) {
4575 for (auto I = FunctionScopes.rbegin(),
4576 E = std::prev(FunctionScopes.rend());
4577 I != E; ++I) {
4578 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4579 if (CSI == nullptr)
4580 break;
4581 DeclContext *DC = nullptr;
4582 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4583 DC = LSI->CallOperator;
4584 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4585 DC = CRSI->TheCapturedDecl;
4586 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4587 DC = BSI->TheDecl;
4588 if (DC) {
4589 if (DC->containsDecl(TT->getDecl()))
4590 break;
4591 captureVariablyModifiedType(Context, ExprType, CSI);
4592 }
4593 }
4594 }
4595 }
4596
4597 return false;
4598}
4599
4601 SourceLocation OpLoc,
4602 UnaryExprOrTypeTrait ExprKind,
4603 SourceRange R) {
4604 if (!TInfo)
4605 return ExprError();
4606
4607 QualType T = TInfo->getType();
4608
4609 if (!T->isDependentType() &&
4610 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4611 getTraitSpelling(ExprKind)))
4612 return ExprError();
4613
4614 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4615 // properly deal with VLAs in nested calls of sizeof and typeof.
4616 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4617 TInfo->getType()->isVariablyModifiedType())
4618 TInfo = TransformToPotentiallyEvaluated(TInfo);
4619
4620 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4621 return new (Context) UnaryExprOrTypeTraitExpr(
4622 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4623}
4624
4627 UnaryExprOrTypeTrait ExprKind) {
4629 if (PE.isInvalid())
4630 return ExprError();
4631
4632 E = PE.get();
4633
4634 // Verify that the operand is valid.
4635 bool isInvalid = false;
4636 if (E->isTypeDependent()) {
4637 // Delay type-checking for type-dependent expressions.
4638 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4639 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4640 } else if (ExprKind == UETT_VecStep) {
4642 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4643 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4644 isInvalid = true;
4645 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4646 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4647 isInvalid = true;
4648 } else if (ExprKind == UETT_VectorElements) {
4649 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);
4650 } else {
4652 }
4653
4654 if (isInvalid)
4655 return ExprError();
4656
4657 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4659 if (PE.isInvalid()) return ExprError();
4660 E = PE.get();
4661 }
4662
4663 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4664 return new (Context) UnaryExprOrTypeTraitExpr(
4665 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4666}
4667
4670 UnaryExprOrTypeTrait ExprKind, bool IsType,
4671 void *TyOrEx, SourceRange ArgRange) {
4672 // If error parsing type, ignore.
4673 if (!TyOrEx) return ExprError();
4674
4675 if (IsType) {
4676 TypeSourceInfo *TInfo;
4677 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4678 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4679 }
4680
4681 Expr *ArgEx = (Expr *)TyOrEx;
4682 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4683 return Result;
4684}
4685
4687 SourceLocation OpLoc, SourceRange R) {
4688 if (!TInfo)
4689 return true;
4690 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4691 UETT_AlignOf, KWName);
4692}
4693
4695 SourceLocation OpLoc, SourceRange R) {
4696 TypeSourceInfo *TInfo;
4698 &TInfo);
4699 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4700}
4701
4703 bool IsReal) {
4704 if (V.get()->isTypeDependent())
4705 return S.Context.DependentTy;
4706
4707 // _Real and _Imag are only l-values for normal l-values.
4708 if (V.get()->getObjectKind() != OK_Ordinary) {
4709 V = S.DefaultLvalueConversion(V.get());
4710 if (V.isInvalid())
4711 return QualType();
4712 }
4713
4714 // These operators return the element type of a complex type.
4715 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4716 return CT->getElementType();
4717
4718 // Otherwise they pass through real integer and floating point types here.
4719 if (V.get()->getType()->isArithmeticType())
4720 return V.get()->getType();
4721
4722 // Test for placeholders.
4723 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4724 if (PR.isInvalid()) return QualType();
4725 if (PR.get() != V.get()) {
4726 V = PR;
4727 return CheckRealImagOperand(S, V, Loc, IsReal);
4728 }
4729
4730 // Reject anything else.
4731 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4732 << (IsReal ? "__real" : "__imag");
4733 return QualType();
4734}
4735
4736
4737
4740 tok::TokenKind Kind, Expr *Input) {
4742 switch (Kind) {
4743 default: llvm_unreachable("Unknown unary op!");
4744 case tok::plusplus: Opc = UO_PostInc; break;
4745 case tok::minusminus: Opc = UO_PostDec; break;
4746 }
4747
4748 // Since this might is a postfix expression, get rid of ParenListExprs.
4750 if (Result.isInvalid()) return ExprError();
4751 Input = Result.get();
4752
4753 return BuildUnaryOp(S, OpLoc, Opc, Input);
4754}
4755
4756/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4757///
4758/// \return true on error
4760 SourceLocation opLoc,
4761 Expr *op) {
4762 assert(op->getType()->isObjCObjectPointerType());
4764 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4765 return false;
4766
4767 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4769 << op->getSourceRange();
4770 return true;
4771}
4772
4774 auto *BaseNoParens = Base->IgnoreParens();
4775 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4776 return MSProp->getPropertyDecl()->getType()->isArrayType();
4777 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4778}
4779
4780// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4781// Typically this is DependentTy, but can sometimes be more precise.
4782//
4783// There are cases when we could determine a non-dependent type:
4784// - LHS and RHS may have non-dependent types despite being type-dependent
4785// (e.g. unbounded array static members of the current instantiation)
4786// - one may be a dependent-sized array with known element type
4787// - one may be a dependent-typed valid index (enum in current instantiation)
4788//
4789// We *always* return a dependent type, in such cases it is DependentTy.
4790// This avoids creating type-dependent expressions with non-dependent types.
4791// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4793 const ASTContext &Ctx) {
4794 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4795 QualType LTy = LHS->getType(), RTy = RHS->getType();
4797 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4798 if (const PointerType *PT = LTy->getAs<PointerType>())
4799 Result = PT->getPointeeType();
4800 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4801 Result = AT->getElementType();
4802 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4803 if (const PointerType *PT = RTy->getAs<PointerType>())
4804 Result = PT->getPointeeType();
4805 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4806 Result = AT->getElementType();
4807 }
4808 // Ensure we return a dependent type.
4809 return Result->isDependentType() ? Result : Ctx.DependentTy;
4810}
4811
4813 SourceLocation lbLoc,
4814 MultiExprArg ArgExprs,
4815 SourceLocation rbLoc) {
4816
4817 if (base && !base->getType().isNull() &&
4818 base->hasPlaceholderType(BuiltinType::ArraySection)) {
4819 auto *AS = cast<ArraySectionExpr>(base);
4820 if (AS->isOMPArraySection())
4822 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
4823 /*Length*/ nullptr,
4824 /*Stride=*/nullptr, rbLoc);
4825
4826 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
4827 SourceLocation(), /*Length*/ nullptr,
4828 rbLoc);
4829 }
4830
4831 // Since this might be a postfix expression, get rid of ParenListExprs.
4832 if (isa<ParenListExpr>(base)) {
4834 if (result.isInvalid())
4835 return ExprError();
4836 base = result.get();
4837 }
4838
4839 // Check if base and idx form a MatrixSubscriptExpr.
4840 //
4841 // Helper to check for comma expressions, which are not allowed as indices for
4842 // matrix subscript expressions.
4843 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4844 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4845 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4846 << SourceRange(base->getBeginLoc(), rbLoc);
4847 return true;
4848 }
4849 return false;
4850 };
4851 // The matrix subscript operator ([][])is considered a single operator.
4852 // Separating the index expressions by parenthesis is not allowed.
4853 if (base && !base->getType().isNull() &&
4854 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4855 !isa<MatrixSubscriptExpr>(base)) {
4856 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4857 << SourceRange(base->getBeginLoc(), rbLoc);
4858 return ExprError();
4859 }
4860 // If the base is a MatrixSubscriptExpr, try to create a new
4861 // MatrixSubscriptExpr.
4862 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4863 if (matSubscriptE) {
4864 assert(ArgExprs.size() == 1);
4865 if (CheckAndReportCommaError(ArgExprs.front()))
4866 return ExprError();
4867
4868 assert(matSubscriptE->isIncomplete() &&
4869 "base has to be an incomplete matrix subscript");
4870 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4871 matSubscriptE->getRowIdx(),
4872 ArgExprs.front(), rbLoc);
4873 }
4874 if (base->getType()->isWebAssemblyTableType()) {
4875 Diag(base->getExprLoc(), diag::err_wasm_table_art)
4876 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
4877 return ExprError();
4878 }
4879
4880 // Handle any non-overload placeholder types in the base and index
4881 // expressions. We can't handle overloads here because the other
4882 // operand might be an overloadable type, in which case the overload
4883 // resolution for the operator overload should get the first crack
4884 // at the overload.
4885 bool IsMSPropertySubscript = false;
4886 if (base->getType()->isNonOverloadPlaceholderType()) {
4887 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4888 if (!IsMSPropertySubscript) {
4889 ExprResult result = CheckPlaceholderExpr(base);
4890 if (result.isInvalid())
4891 return ExprError();
4892 base = result.get();
4893 }
4894 }
4895
4896 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4897 if (base->getType()->isMatrixType()) {
4898 assert(ArgExprs.size() == 1);
4899 if (CheckAndReportCommaError(ArgExprs.front()))
4900 return ExprError();
4901
4902 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4903 rbLoc);
4904 }
4905
4906 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4907 Expr *idx = ArgExprs[0];
4908 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4909 (isa<CXXOperatorCallExpr>(idx) &&
4910 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4911 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4912 << SourceRange(base->getBeginLoc(), rbLoc);
4913 }
4914 }
4915
4916 if (ArgExprs.size() == 1 &&
4917 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4918 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4919 if (result.isInvalid())
4920 return ExprError();
4921 ArgExprs[0] = result.get();
4922 } else {
4923 if (CheckArgsForPlaceholders(ArgExprs))
4924 return ExprError();
4925 }
4926
4927 // Build an unanalyzed expression if either operand is type-dependent.
4928 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4929 (base->isTypeDependent() ||
4931 !isa<PackExpansionExpr>(ArgExprs[0])) {
4932 return new (Context) ArraySubscriptExpr(
4933 base, ArgExprs.front(),
4934 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4935 VK_LValue, OK_Ordinary, rbLoc);
4936 }
4937
4938 // MSDN, property (C++)
4939 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4940 // This attribute can also be used in the declaration of an empty array in a
4941 // class or structure definition. For example:
4942 // __declspec(property(get=GetX, put=PutX)) int x[];
4943 // The above statement indicates that x[] can be used with one or more array
4944 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4945 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4946 if (IsMSPropertySubscript) {
4947 assert(ArgExprs.size() == 1);
4948 // Build MS property subscript expression if base is MS property reference
4949 // or MS property subscript.
4950 return new (Context)
4951 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4952 VK_LValue, OK_Ordinary, rbLoc);
4953 }
4954
4955 // Use C++ overloaded-operator rules if either operand has record
4956 // type. The spec says to do this if either type is *overloadable*,
4957 // but enum types can't declare subscript operators or conversion
4958 // operators, so there's nothing interesting for overload resolution
4959 // to do if there aren't any record types involved.
4960 //
4961 // ObjC pointers have their own subscripting logic that is not tied
4962 // to overload resolution and so should not take this path.
4963 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4964 ((base->getType()->isRecordType() ||
4965 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
4966 ArgExprs[0]->getType()->isRecordType())))) {
4967 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4968 }
4969
4970 ExprResult Res =
4971 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4972
4973 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4974 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4975
4976 return Res;
4977}
4978
4981 InitializationKind Kind =
4983 InitializationSequence InitSeq(*this, Entity, Kind, E);
4984 return InitSeq.Perform(*this, Entity, Kind, E);
4985}
4986
4988 Expr *ColumnIdx,
4989 SourceLocation RBLoc) {
4991 if (BaseR.isInvalid())
4992 return BaseR;
4993 Base = BaseR.get();
4994
4995 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4996 if (RowR.isInvalid())
4997 return RowR;
4998 RowIdx = RowR.get();
4999
5000 if (!ColumnIdx)
5001 return new (Context) MatrixSubscriptExpr(
5002 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5003
5004 // Build an unanalyzed expression if any of the operands is type-dependent.
5005 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5006 ColumnIdx->isTypeDependent())
5007 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5008 Context.DependentTy, RBLoc);
5009
5010 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5011 if (ColumnR.isInvalid())
5012 return ColumnR;
5013 ColumnIdx = ColumnR.get();
5014
5015 // Check that IndexExpr is an integer expression. If it is a constant
5016 // expression, check that it is less than Dim (= the number of elements in the
5017 // corresponding dimension).
5018 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5019 bool IsColumnIdx) -> Expr * {
5020 if (!IndexExpr->getType()->isIntegerType() &&
5021 !IndexExpr->isTypeDependent()) {
5022 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5023 << IsColumnIdx;
5024 return nullptr;
5025 }
5026
5027 if (std::optional<llvm::APSInt> Idx =
5028 IndexExpr->getIntegerConstantExpr(Context)) {
5029 if ((*Idx < 0 || *Idx >= Dim)) {
5030 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5031 << IsColumnIdx << Dim;
5032 return nullptr;
5033 }
5034 }
5035
5036 ExprResult ConvExpr =
5038 assert(!ConvExpr.isInvalid() &&
5039 "should be able to convert any integer type to size type");
5040 return ConvExpr.get();
5041 };
5042
5043 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5044 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5045 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5046 if (!RowIdx || !ColumnIdx)
5047 return ExprError();
5048
5049 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5050 MTy->getElementType(), RBLoc);
5051}
5052
5053void Sema::CheckAddressOfNoDeref(const Expr *E) {
5054 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5055 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5056
5057 // For expressions like `&(*s).b`, the base is recorded and what should be
5058 // checked.
5059 const MemberExpr *Member = nullptr;
5060 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5061 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5062
5063 LastRecord.PossibleDerefs.erase(StrippedExpr);
5064}
5065
5066void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5068 return;
5069
5070 QualType ResultTy = E->getType();
5071 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5072
5073 // Bail if the element is an array since it is not memory access.
5074 if (isa<ArrayType>(ResultTy))
5075 return;
5076
5077 if (ResultTy->hasAttr(attr::NoDeref)) {
5078 LastRecord.PossibleDerefs.insert(E);
5079 return;
5080 }
5081
5082 // Check if the base type is a pointer to a member access of a struct
5083 // marked with noderef.
5084 const Expr *Base = E->getBase();
5085 QualType BaseTy = Base->getType();
5086 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5087 // Not a pointer access
5088 return;
5089
5090 const MemberExpr *Member = nullptr;
5091 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5092 Member->isArrow())
5093 Base = Member->getBase();
5094
5095 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5096 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5097 LastRecord.PossibleDerefs.insert(E);
5098 }
5099}
5100
5103 Expr *Idx, SourceLocation RLoc) {
5104 Expr *LHSExp = Base;
5105 Expr *RHSExp = Idx;
5106
5109
5110 // Per C++ core issue 1213, the result is an xvalue if either operand is
5111 // a non-lvalue array, and an lvalue otherwise.
5112 if (getLangOpts().CPlusPlus11) {
5113 for (auto *Op : {LHSExp, RHSExp}) {
5114 Op = Op->IgnoreImplicit();
5115 if (Op->getType()->isArrayType() && !Op->isLValue())
5116 VK = VK_XValue;
5117 }
5118 }
5119
5120 // Perform default conversions.
5121 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5123 if (Result.isInvalid())
5124 return ExprError();
5125 LHSExp = Result.get();
5126 }
5128 if (Result.isInvalid())
5129 return ExprError();
5130 RHSExp = Result.get();
5131
5132 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5133
5134 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5135 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5136 // in the subscript position. As a result, we need to derive the array base
5137 // and index from the expression types.
5138 Expr *BaseExpr, *IndexExpr;
5139 QualType ResultType;
5140 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5141 BaseExpr = LHSExp;
5142 IndexExpr = RHSExp;
5143 ResultType =
5145 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5146 BaseExpr = LHSExp;
5147 IndexExpr = RHSExp;
5148 ResultType = PTy->getPointeeType();
5149 } else if (const ObjCObjectPointerType *PTy =
5150 LHSTy->getAs<ObjCObjectPointerType>()) {
5151 BaseExpr = LHSExp;
5152 IndexExpr = RHSExp;
5153
5154 // Use custom logic if this should be the pseudo-object subscript
5155 // expression.
5157 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5158 nullptr, nullptr);
5159
5160 ResultType = PTy->getPointeeType();
5161 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5162 // Handle the uncommon case of "123[Ptr]".
5163 BaseExpr = RHSExp;
5164 IndexExpr = LHSExp;
5165 ResultType = PTy->getPointeeType();
5166 } else if (const ObjCObjectPointerType *PTy =
5167 RHSTy->getAs<ObjCObjectPointerType>()) {
5168 // Handle the uncommon case of "123[Ptr]".
5169 BaseExpr = RHSExp;
5170 IndexExpr = LHSExp;
5171 ResultType = PTy->getPointeeType();
5173 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5174 << ResultType << BaseExpr->getSourceRange();
5175 return ExprError();
5176 }
5177 } else if (LHSTy->isSubscriptableVectorType()) {
5178 if (LHSTy->isBuiltinType() &&
5179 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5180 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5181 if (BTy->isSVEBool())
5182 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5183 << LHSExp->getSourceRange()
5184 << RHSExp->getSourceRange());
5185 ResultType = BTy->getSveEltType(Context);
5186 } else {
5187 const VectorType *VTy = LHSTy->getAs<VectorType>();
5188 ResultType = VTy->getElementType();
5189 }
5190 BaseExpr = LHSExp; // vectors: V[123]
5191 IndexExpr = RHSExp;
5192 // We apply C++ DR1213 to vector subscripting too.
5193 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5194 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5195 if (Materialized.isInvalid())
5196 return ExprError();
5197 LHSExp = Materialized.get();
5198 }
5199 VK = LHSExp->getValueKind();
5200 if (VK != VK_PRValue)
5201 OK = OK_VectorComponent;
5202
5203 QualType BaseType = BaseExpr->getType();
5204 Qualifiers BaseQuals = BaseType.getQualifiers();
5205 Qualifiers MemberQuals = ResultType.getQualifiers();
5206 Qualifiers Combined = BaseQuals + MemberQuals;
5207 if (Combined != MemberQuals)
5208 ResultType = Context.getQualifiedType(ResultType, Combined);
5209 } else if (LHSTy->isArrayType()) {
5210 // If we see an array that wasn't promoted by
5211 // DefaultFunctionArrayLvalueConversion, it must be an array that
5212 // wasn't promoted because of the C90 rule that doesn't
5213 // allow promoting non-lvalue arrays. Warn, then
5214 // force the promotion here.
5215 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5216 << LHSExp->getSourceRange();
5217 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5218 CK_ArrayToPointerDecay).get();
5219 LHSTy = LHSExp->getType();
5220
5221 BaseExpr = LHSExp;
5222 IndexExpr = RHSExp;
5223 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5224 } else if (RHSTy->isArrayType()) {
5225 // Same as previous, except for 123[f().a] case
5226 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5227 << RHSExp->getSourceRange();
5228 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5229 CK_ArrayToPointerDecay).get();
5230 RHSTy = RHSExp->getType();
5231
5232 BaseExpr = RHSExp;
5233 IndexExpr = LHSExp;
5234 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5235 } else {
5236 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5237 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5238 }
5239 // C99 6.5.2.1p1
5240 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5241 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5242 << IndexExpr->getSourceRange());
5243
5244 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5245 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5246 !IndexExpr->isTypeDependent()) {
5247 std::optional<llvm::APSInt> IntegerContantExpr =
5249 if (!IntegerContantExpr.has_value() ||
5250 IntegerContantExpr.value().isNegative())
5251 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5252 }
5253
5254 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5255 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5256 // type. Note that Functions are not objects, and that (in C99 parlance)
5257 // incomplete types are not object types.
5258 if (ResultType->isFunctionType()) {
5259 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5260 << ResultType << BaseExpr->getSourceRange();
5261 return ExprError();
5262 }
5263
5264 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5265 // GNU extension: subscripting on pointer to void
5266 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5267 << BaseExpr->getSourceRange();
5268
5269 // C forbids expressions of unqualified void type from being l-values.
5270 // See IsCForbiddenLValueType.
5271 if (!ResultType.hasQualifiers())
5272 VK = VK_PRValue;
5273 } else if (!ResultType->isDependentType() &&
5274 !ResultType.isWebAssemblyReferenceType() &&
5276 LLoc, ResultType,
5277 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5278 return ExprError();
5279
5280 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5281 !ResultType.isCForbiddenLValueType());
5282
5284 FunctionScopes.size() > 1) {
5285 if (auto *TT =
5286 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5287 for (auto I = FunctionScopes.rbegin(),
5288 E = std::prev(FunctionScopes.rend());
5289 I != E; ++I) {
5290 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5291 if (CSI == nullptr)
5292 break;
5293 DeclContext *DC = nullptr;
5294 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5295 DC = LSI->CallOperator;
5296 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5297 DC = CRSI->TheCapturedDecl;
5298 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5299 DC = BSI->TheDecl;
5300 if (DC) {
5301 if (DC->containsDecl(TT->getDecl()))
5302 break;
5304 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5305 }
5306 }
5307 }
5308 }
5309
5310 return new (Context)
5311 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5312}
5313
5315 ParmVarDecl *Param, Expr *RewrittenInit,
5316 bool SkipImmediateInvocations) {
5317 if (Param->hasUnparsedDefaultArg()) {
5318 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5319 // If we've already cleared out the location for the default argument,
5320 // that means we're parsing it right now.
5321 if (!UnparsedDefaultArgLocs.count(Param)) {
5322 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5323 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5324 Param->setInvalidDecl();
5325 return true;
5326 }
5327
5328 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5329 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5331 diag::note_default_argument_declared_here);
5332 return true;
5333 }
5334
5335 if (Param->hasUninstantiatedDefaultArg()) {
5336 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5337 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5338 return true;
5339 }
5340
5341 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5342 assert(Init && "default argument but no initializer?");
5343
5344 // If the default expression creates temporaries, we need to
5345 // push them to the current stack of expression temporaries so they'll
5346 // be properly destroyed.
5347 // FIXME: We should really be rebuilding the default argument with new
5348 // bound temporaries; see the comment in PR5810.
5349 // We don't need to do that with block decls, though, because
5350 // blocks in default argument expression can never capture anything.
5351 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5352 // Set the "needs cleanups" bit regardless of whether there are
5353 // any explicit objects.
5354 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5355 // Append all the objects to the cleanup list. Right now, this
5356 // should always be a no-op, because blocks in default argument
5357 // expressions should never be able to capture anything.
5358 assert(!InitWithCleanup->getNumObjects() &&
5359 "default argument expression has capturing blocks?");
5360 }
5361 // C++ [expr.const]p15.1:
5362 // An expression or conversion is in an immediate function context if it is
5363 // potentially evaluated and [...] its innermost enclosing non-block scope
5364 // is a function parameter scope of an immediate function.
5366 *this,
5370 Param);
5371 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5372 SkipImmediateInvocations;
5373 runWithSufficientStackSpace(CallLoc, [&] {
5374 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5375 });
5376 return false;
5377}
5378
5379struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
5381 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {}
5382
5383 bool HasImmediateCalls = false;
5384 bool shouldVisitImplicitCode() const { return true; }
5385
5387 if (const FunctionDecl *FD = E->getDirectCallee())
5388 HasImmediateCalls |= FD->isImmediateFunction();
5390 }
5391
5393 if (const FunctionDecl *FD = E->getConstructor())
5394 HasImmediateCalls |= FD->isImmediateFunction();
5396 }
5397
5398 // SourceLocExpr are not immediate invocations
5399 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5400 // need to be rebuilt so that they refer to the correct SourceLocation and
5401 // DeclContext.
5403 HasImmediateCalls = true;
5405 }
5406
5407 // A nested lambda might have parameters with immediate invocations
5408 // in their default arguments.
5409 // The compound statement is not visited (as it does not constitute a
5410 // subexpression).
5411 // FIXME: We should consider visiting and transforming captures
5412 // with init expressions.
5414 return VisitCXXMethodDecl(E->getCallOperator());
5415 }
5416
5418 return TraverseStmt(E->getExpr());
5419 }
5420
5422 return TraverseStmt(E->getExpr());
5423 }
5424};
5425
5427 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5429 : TreeTransform(SemaRef) {}
5430
5431 // Lambda can only have immediate invocations in the default
5432 // args of their parameters, which is transformed upon calling the closure.
5433 // The body is not a subexpression, so we have nothing to do.
5434 // FIXME: Immediate calls in capture initializers should be transformed.
5437
5438 // Make sure we don't rebuild the this pointer as it would
5439 // cause it to incorrectly point it to the outermost class
5440 // in the case of nested struct initialization.
5442
5443 // Rewrite to source location to refer to the context in which they are used.
5445 if (E->getParentContext() == SemaRef.CurContext)
5446 return E;
5447 return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getType(),
5448 E->getBeginLoc(), E->getEndLoc(),
5449 SemaRef.CurContext);
5450 }
5451};
5452
5454 FunctionDecl *FD, ParmVarDecl *Param,
5455 Expr *Init) {
5456 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5457
5458 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5459 bool InLifetimeExtendingContext = isInLifetimeExtendingContext();
5460 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5461 InitializationContext =
5463 if (!InitializationContext.has_value())
5464 InitializationContext.emplace(CallLoc, Param, CurContext);
5465
5466 if (!Init && !Param->hasUnparsedDefaultArg()) {
5467 // Mark that we are replacing a default argument first.
5468 // If we are instantiating a template we won't have to
5469 // retransform immediate calls.
5470 // C++ [expr.const]p15.1:
5471 // An expression or conversion is in an immediate function context if it
5472 // is potentially evaluated and [...] its innermost enclosing non-block
5473 // scope is a function parameter scope of an immediate function.
5475 *this,
5479 Param);
5480
5481 if (Param->hasUninstantiatedDefaultArg()) {
5482 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5483 return ExprError();
5484 }
5485 // CWG2631
5486 // An immediate invocation that is not evaluated where it appears is
5487 // evaluated and checked for whether it is a constant expression at the
5488 // point where the enclosing initializer is used in a function call.
5490 if (!NestedDefaultChecking)
5491 V.TraverseDecl(Param);
5492
5493 // Rewrite the call argument that was created from the corresponding
5494 // parameter's default argument.
5495 if (V.HasImmediateCalls || InLifetimeExtendingContext) {
5496 if (V.HasImmediateCalls)
5497 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5498 CallLoc, Param, CurContext};
5499 // Pass down lifetime extending flag, and collect temporaries in
5500 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5503 ExprResult Res;
5504 runWithSufficientStackSpace(CallLoc, [&] {
5505 Res = Immediate.TransformInitializer(Param->getInit(),
5506 /*NotCopy=*/false);
5507 });
5508 if (Res.isInvalid())
5509 return ExprError();
5510 Res = ConvertParamDefaultArgument(Param, Res.get(),
5511 Res.get()->getBeginLoc());
5512 if (Res.isInvalid())
5513 return ExprError();
5514 Init = Res.get();
5515 }
5516 }
5517
5519 CallLoc, FD, Param, Init,
5520 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5521 return ExprError();
5522
5523 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5524 Init, InitializationContext->Context);
5525}
5526
5528 assert(Field->hasInClassInitializer());
5529
5530 // If we might have already tried and failed to instantiate, don't try again.
5531 if (Field->isInvalidDecl())
5532 return ExprError();
5533
5534 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5535
5536 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5537
5538 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5539 InitializationContext =
5541 if (!InitializationContext.has_value())
5542 InitializationContext.emplace(Loc, Field, CurContext);
5543
5544 Expr *Init = nullptr;
5545
5546 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5547
5550
5551 if (!Field->getInClassInitializer()) {
5552 // Maybe we haven't instantiated the in-class initializer. Go check the
5553 // pattern FieldDecl to see if it has one.
5554 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5555 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5557 ClassPattern->lookup(Field->getDeclName());
5558
5559 FieldDecl *Pattern = nullptr;
5560 for (auto *L : Lookup) {
5561 if ((Pattern = dyn_cast<FieldDecl>(L)))
5562 break;
5563 }
5564 assert(Pattern && "We must have set the Pattern!");
5565 if (!Pattern->hasInClassInitializer() ||
5566 InstantiateInClassInitializer(Loc, Field, Pattern,
5568 Field->setInvalidDecl();
5569 return ExprError();
5570 }
5571 }
5572 }
5573
5574 // CWG2631
5575 // An immediate invocation that is not evaluated where it appears is
5576 // evaluated and checked for whether it is a constant expression at the
5577 // point where the enclosing initializer is used in a [...] a constructor
5578 // definition, or an aggregate initialization.
5580 if (!NestedDefaultChecking)
5581 V.TraverseDecl(Field);
5582 if (V.HasImmediateCalls) {
5583 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5584 CurContext};
5585 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5586 NestedDefaultChecking;
5587
5589 ExprResult Res;
5591 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5592 /*CXXDirectInit=*/false);
5593 });
5594 if (!Res.isInvalid())
5595 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5596 if (Res.isInvalid()) {
5597 Field->setInvalidDecl();
5598 return ExprError();
5599 }
5600 Init = Res.get();
5601 }
5602
5603 if (Field->getInClassInitializer()) {
5604 Expr *E = Init ? Init : Field->getInClassInitializer();
5605 if (!NestedDefaultChecking)
5607 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5608 });
5609 // C++11 [class.base.init]p7:
5610 // The initialization of each base and member constitutes a
5611 // full-expression.
5612 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5613 if (Res.isInvalid()) {
5614 Field->setInvalidDecl();
5615 return ExprError();
5616 }
5617 Init = Res.get();
5618
5619 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5620 Field, InitializationContext->Context,
5621 Init);
5622 }
5623
5624 // DR1351:
5625 // If the brace-or-equal-initializer of a non-static data member
5626 // invokes a defaulted default constructor of its class or of an
5627 // enclosing class in a potentially evaluated subexpression, the
5628 // program is ill-formed.
5629 //
5630 // This resolution is unworkable: the exception specification of the
5631 // default constructor can be needed in an unevaluated context, in
5632 // particular, in the operand of a noexcept-expression, and we can be
5633 // unable to compute an exception specification for an enclosed class.
5634 //
5635 // Any attempt to resolve the exception specification of a defaulted default
5636 // constructor before the initializer is lexically complete will ultimately
5637 // come here at which point we can diagnose it.
5638 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5639 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5640 << OutermostClass << Field;
5641 Diag(Field->getEndLoc(),
5642 diag::note_default_member_initializer_not_yet_parsed);
5643 // Recover by marking the field invalid, unless we're in a SFINAE context.
5644 if (!isSFINAEContext())
5645 Field->setInvalidDecl();
5646 return ExprError();
5647}
5648
5651 Expr *Fn) {
5652 if (Proto && Proto->isVariadic()) {
5653 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5654 return VariadicConstructor;
5655 else if (Fn && Fn->getType()->isBlockPointerType())
5656 return VariadicBlock;
5657 else if (FDecl) {
5658 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5659 if (Method->isInstance())
5660 return VariadicMethod;
5661 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5662 return VariadicMethod;
5663 return VariadicFunction;
5664 }
5665 return VariadicDoesNotApply;
5666}
5667
5668namespace {
5669class FunctionCallCCC final : public FunctionCallFilterCCC {
5670public:
5671 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5672 unsigned NumArgs, MemberExpr *ME)
5673 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5674 FunctionName(FuncName) {}
5675
5676 bool ValidateCandidate(const TypoCorrection &candidate) override {
5677 if (!candidate.getCorrectionSpecifier() ||
5678 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5679 return false;
5680 }
5681
5683 }
5684
5685 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5686 return std::make_unique<FunctionCallCCC>(*this);
5687 }
5688
5689private:
5690 const IdentifierInfo *const FunctionName;
5691};
5692}
5693
5695 FunctionDecl *FDecl,
5696 ArrayRef<Expr *> Args) {
5697 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5698 DeclarationName FuncName = FDecl->getDeclName();
5699 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5700
5701 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5702 if (TypoCorrection Corrected = S.CorrectTypo(
5704 S.getScopeForContext(S.CurContext), nullptr, CCC,
5706 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5707 if (Corrected.isOverloaded()) {
5710 for (NamedDecl *CD : Corrected) {
5711 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5713 OCS);
5714 }
5715 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5716 case OR_Success:
5717 ND = Best->FoundDecl;
5718 Corrected.setCorrectionDecl(ND);
5719 break;
5720 default:
5721 break;
5722 }
5723 }
5724 ND = ND->getUnderlyingDecl();
5725 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5726 return Corrected;
5727 }
5728 }
5729 return TypoCorrection();
5730}
5731
5732// [C++26][[expr.unary.op]/p4
5733// A pointer to member is only formed when an explicit &
5734// is used and its operand is a qualified-id not enclosed in parentheses.
5736 if (!isa<ParenExpr>(Fn))
5737 return false;
5738
5739 Fn = Fn->IgnoreParens();
5740
5741 auto *UO = dyn_cast<UnaryOperator>(Fn);
5742 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
5743 return false;
5744 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
5745 return DRE->hasQualifier();
5746 }
5747 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
5748 return OVL->getQualifier();
5749 return false;
5750}
5751
5752bool
5754 FunctionDecl *FDecl,
5755 const FunctionProtoType *Proto,
5756 ArrayRef<Expr *> Args,
5757 SourceLocation RParenLoc,
5758 bool IsExecConfig) {
5759 // Bail out early if calling a builtin with custom typechecking.
5760 if (FDecl)
5761 if (unsigned ID = FDecl->getBuiltinID())
5763 return false;
5764
5765 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5766 // assignment, to the types of the corresponding parameter, ...
5767
5768 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
5769 bool HasExplicitObjectParameter =
5770 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
5771 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
5772 unsigned NumParams = Proto->getNumParams();
5773 bool Invalid = false;
5774 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5775 unsigned FnKind = Fn->getType()->isBlockPointerType()
5776 ? 1 /* block */
5777 : (IsExecConfig ? 3 /* kernel function (exec config) */
5778 : 0 /* function */);
5779
5780 // If too few arguments are available (and we don't have default
5781 // arguments for the remaining parameters), don't make the call.
5782 if (Args.size() < NumParams) {
5783 if (Args.size() < MinArgs) {
5784 TypoCorrection TC;
5785 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5786 unsigned diag_id =
5787 MinArgs == NumParams && !Proto->isVariadic()
5788 ? diag::err_typecheck_call_too_few_args_suggest
5789 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5791 TC, PDiag(diag_id)
5792 << FnKind << MinArgs - ExplicitObjectParameterOffset
5793 << static_cast<unsigned>(Args.size()) -
5794 ExplicitObjectParameterOffset
5795 << HasExplicitObjectParameter << TC.getCorrectionRange());
5796 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
5797 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5798 ->getDeclName())
5799 Diag(RParenLoc,
5800 MinArgs == NumParams && !Proto->isVariadic()
5801 ? diag::err_typecheck_call_too_few_args_one
5802 : diag::err_typecheck_call_too_few_args_at_least_one)
5803 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5804 << HasExplicitObjectParameter << Fn->getSourceRange();
5805 else
5806 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5807 ? diag::err_typecheck_call_too_few_args
5808 : diag::err_typecheck_call_too_few_args_at_least)
5809 << FnKind << MinArgs - ExplicitObjectParameterOffset
5810 << static_cast<unsigned>(Args.size()) -
5811 ExplicitObjectParameterOffset
5812 << HasExplicitObjectParameter << Fn->getSourceRange();
5813
5814 // Emit the location of the prototype.
5815 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5816 Diag(FDecl->getLocation(), diag::note_callee_decl)
5817 << FDecl << FDecl->getParametersSourceRange();
5818
5819 return true;
5820 }
5821 // We reserve space for the default arguments when we create
5822 // the call expression, before calling ConvertArgumentsForCall.
5823 assert((Call->getNumArgs() == NumParams) &&
5824 "We should have reserved space for the default arguments before!");
5825 }
5826
5827 // If too many are passed and not variadic, error on the extras and drop
5828 // them.
5829 if (Args.size() > NumParams) {
5830 if (!Proto->isVariadic()) {
5831 TypoCorrection TC;
5832 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5833 unsigned diag_id =
5834 MinArgs == NumParams && !Proto->isVariadic()
5835 ? diag::err_typecheck_call_too_many_args_suggest
5836 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5838 TC, PDiag(diag_id)
5839 << FnKind << NumParams - ExplicitObjectParameterOffset
5840 << static_cast<unsigned>(Args.size()) -
5841 ExplicitObjectParameterOffset
5842 << HasExplicitObjectParameter << TC.getCorrectionRange());
5843 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
5844 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5845 ->getDeclName())
5846 Diag(Args[NumParams]->getBeginLoc(),
5847 MinArgs == NumParams
5848 ? diag::err_typecheck_call_too_many_args_one
5849 : diag::err_typecheck_call_too_many_args_at_most_one)
5850 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5851 << static_cast<unsigned>(Args.size()) -
5852 ExplicitObjectParameterOffset
5853 << HasExplicitObjectParameter << Fn->getSourceRange()
5854 << SourceRange(Args[NumParams]->getBeginLoc(),
5855 Args.back()->getEndLoc());
5856 else
5857 Diag(Args[NumParams]->getBeginLoc(),
5858 MinArgs == NumParams
5859 ? diag::err_typecheck_call_too_many_args
5860 : diag::err_typecheck_call_too_many_args_at_most)
5861 << FnKind << NumParams - ExplicitObjectParameterOffset
5862 << static_cast<unsigned>(Args.size()) -
5863 ExplicitObjectParameterOffset
5864 << HasExplicitObjectParameter << Fn->getSourceRange()
5865 << SourceRange(Args[NumParams]->getBeginLoc(),
5866 Args.back()->getEndLoc());
5867
5868 // Emit the location of the prototype.
5869 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5870 Diag(FDecl->getLocation(), diag::note_callee_decl)
5871 << FDecl << FDecl->getParametersSourceRange();
5872
5873 // This deletes the extra arguments.
5874 Call->shrinkNumArgs(NumParams);
5875 return true;
5876 }
5877 }
5878 SmallVector<Expr *, 8> AllArgs;
5879 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5880
5881 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5882 AllArgs, CallType);
5883 if (Invalid)
5884 return true;
5885 unsigned TotalNumArgs = AllArgs.size();
5886 for (unsigned i = 0; i < TotalNumArgs; ++i)
5887 Call->setArg(i, AllArgs[i]);
5888
5889 Call->computeDependence();
5890 return false;
5891}
5892
5894 const FunctionProtoType *Proto,
5895 unsigned FirstParam, ArrayRef<Expr *> Args,
5896 SmallVectorImpl<Expr *> &AllArgs,
5897 VariadicCallType CallType, bool AllowExplicit,
5898 bool IsListInitialization) {
5899 unsigned NumParams = Proto->getNumParams();
5900 bool Invalid = false;
5901 size_t ArgIx = 0;
5902 // Continue to check argument types (even if we have too few/many args).
5903 for (unsigned i = FirstParam; i < NumParams; i++) {
5904 QualType ProtoArgType = Proto->getParamType(i);
5905
5906 Expr *Arg;
5907 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5908 if (ArgIx < Args.size()) {
5909 Arg = Args[ArgIx++];
5910
5911 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5912 diag::err_call_incomplete_argument, Arg))
5913 return true;
5914
5915 // Strip the unbridged-cast placeholder expression off, if applicable.
5916 bool CFAudited = false;
5917 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5918 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5919 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5920 Arg = ObjC().stripARCUnbridgedCast(Arg);
5921 else if (getLangOpts().ObjCAutoRefCount &&
5922 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5923 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5924 CFAudited = true;
5925
5926 if (Proto->getExtParameterInfo(i).isNoEscape() &&
5927 ProtoArgType->isBlockPointerType())
5928 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5929 BE->getBlockDecl()->setDoesNotEscape();
5930
5931 InitializedEntity Entity =
5933 ProtoArgType)
5935 Context, ProtoArgType, Proto->isParamConsumed(i));
5936
5937 // Remember that parameter belongs to a CF audited API.
5938 if (CFAudited)
5939 Entity.setParameterCFAudited();
5940
5942 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5943 if (ArgE.isInvalid())
5944 return true;
5945
5946 Arg = ArgE.getAs<Expr>();
5947 } else {
5948 assert(Param && "can't use default arguments without a known callee");
5949
5950 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5951 if (ArgExpr.isInvalid())
5952 return true;
5953
5954 Arg = ArgExpr.getAs<Expr>();
5955 }
5956
5957 // Check for array bounds violations for each argument to the call. This
5958 // check only triggers warnings when the argument isn't a more complex Expr
5959 // with its own checking, such as a BinaryOperator.
5960 CheckArrayAccess(Arg);
5961
5962 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5963 CheckStaticArrayArgument(CallLoc, Param, Arg);
5964
5965 AllArgs.push_back(Arg);
5966 }
5967
5968 // If this is a variadic call, handle args passed through "...".
5969 if (CallType != VariadicDoesNotApply) {
5970 // Assume that extern "C" functions with variadic arguments that
5971 // return __unknown_anytype aren't *really* variadic.
5972 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5973 FDecl->isExternC()) {
5974 for (Expr *A : Args.slice(ArgIx)) {
5975 QualType paramType; // ignored
5976 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5977 Invalid |= arg.isInvalid();
5978 AllArgs.push_back(arg.get());
5979 }
5980
5981 // Otherwise do argument promotion, (C99 6.5.2.2p7).
5982 } else {
5983 for (Expr *A : Args.slice(ArgIx)) {
5984 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5985 Invalid |= Arg.isInvalid();
5986 AllArgs.push_back(Arg.get());
5987 }
5988 }
5989
5990 // Check for array bounds violations.
5991 for (Expr *A : Args.slice(ArgIx))
5992 CheckArrayAccess(A);
5993 }
5994 return Invalid;
5995}
5996
5998 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5999 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6000 TL = DTL.getOriginalLoc();
6001 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6002 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6003 << ATL.getLocalSourceRange();
6004}
6005
6006void
6008 ParmVarDecl *Param,
6009 const Expr *ArgExpr) {
6010 // Static array parameters are not supported in C++.
6011 if (!Param || getLangOpts().CPlusPlus)
6012 return;
6013
6014 QualType OrigTy = Param->getOriginalType();
6015
6016 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6017 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6018 return;
6019
6020 if (ArgExpr->isNullPointerConstant(Context,
6022 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6023 DiagnoseCalleeStaticArrayParam(*this, Param);
6024 return;
6025 }
6026
6027 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6028 if (!CAT)
6029 return;
6030
6031 const ConstantArrayType *ArgCAT =
6033 if (!ArgCAT)
6034 return;
6035
6036 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6037 ArgCAT->getElementType())) {
6038 if (ArgCAT->getSize().ult(CAT->getSize())) {
6039 Diag(CallLoc, diag::warn_static_array_too_small)
6040 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6041 << (unsigned)CAT->getZExtSize() << 0;
6042 DiagnoseCalleeStaticArrayParam(*this, Param);
6043 }
6044 return;
6045 }
6046
6047 std::optional<CharUnits> ArgSize =
6049 std::optional<CharUnits> ParmSize =
6051 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6052 Diag(CallLoc, diag::warn_static_array_too_small)
6053 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6054 << (unsigned)ParmSize->getQuantity() << 1;
6055 DiagnoseCalleeStaticArrayParam(*this, Param);
6056 }
6057}
6058
6059/// Given a function expression of unknown-any type, try to rebuild it
6060/// to have a function type.
6062
6063/// Is the given type a placeholder that we need to lower out
6064/// immediately during argument processing?
6066 // Placeholders are never sugared.
6067 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6068 if (!placeholder) return false;
6069
6070 switch (placeholder->getKind()) {
6071 // Ignore all the non-placeholder types.
6072#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6073 case BuiltinType::Id:
6074#include "clang/Basic/OpenCLImageTypes.def"
6075#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6076 case BuiltinType::Id:
6077#include "clang/Basic/OpenCLExtensionTypes.def"
6078 // In practice we'll never use this, since all SVE types are sugared
6079 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6080#define SVE_TYPE(Name, Id, SingletonId) \
6081 case BuiltinType::Id:
6082#include "clang/Basic/AArch64SVEACLETypes.def"
6083#define PPC_VECTOR_TYPE(Name, Id, Size) \
6084 case BuiltinType::Id:
6085#include "clang/Basic/PPCTypes.def"
6086#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6087#include "clang/Basic/RISCVVTypes.def"
6088#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6089#include "clang/Basic/WebAssemblyReferenceTypes.def"
6090#define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6091#include "clang/Basic/AMDGPUTypes.def"
6092#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6093#include "clang/Basic/HLSLIntangibleTypes.def"
6094#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6095#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6096#include "clang/AST/BuiltinTypes.def"
6097 return false;
6098
6099 case BuiltinType::UnresolvedTemplate:
6100 // We cannot lower out overload sets; they might validly be resolved
6101 // by the call machinery.
6102 case BuiltinType::Overload:
6103 return false;
6104
6105 // Unbridged casts in ARC can be handled in some call positions and
6106 // should be left in place.
6107 case BuiltinType::ARCUnbridgedCast:
6108 return false;
6109
6110 // Pseudo-objects should be converted as soon as possible.
6111 case BuiltinType::PseudoObject:
6112 return true;
6113
6114 // The debugger mode could theoretically but currently does not try
6115 // to resolve unknown-typed arguments based on known parameter types.
6116 case BuiltinType::UnknownAny:
6117 return true;
6118
6119 // These are always invalid as call arguments and should be reported.
6120 case BuiltinType::BoundMember:
6121 case BuiltinType::BuiltinFn:
6122 case BuiltinType::IncompleteMatrixIdx:
6123 case BuiltinType::ArraySection:
6124 case BuiltinType::OMPArrayShaping:
6125 case BuiltinType::OMPIterator:
6126 return true;
6127
6128 }
6129 llvm_unreachable("bad builtin type kind");
6130}
6131
6133 // Apply this processing to all the arguments at once instead of
6134 // dying at the first failure.
6135 bool hasInvalid = false;
6136 for (size_t i = 0, e = args.size(); i != e; i++) {
6137 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6138 ExprResult result = CheckPlaceholderExpr(args[i]);
6139 if (result.isInvalid()) hasInvalid = true;
6140 else args[i] = result.get();
6141 }
6142 }
6143 return hasInvalid;
6144}
6145
6146/// If a builtin function has a pointer argument with no explicit address
6147/// space, then it should be able to accept a pointer to any address
6148/// space as input. In order to do this, we need to replace the
6149/// standard builtin declaration with one that uses the same address space
6150/// as the call.
6151///
6152/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6153/// it does not contain any pointer arguments without
6154/// an address space qualifer. Otherwise the rewritten
6155/// FunctionDecl is returned.
6156/// TODO: Handle pointer return types.
6158 FunctionDecl *FDecl,
6159 MultiExprArg ArgExprs) {
6160
6161 QualType DeclType = FDecl->getType();
6162 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6163
6164 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6165 ArgExprs.size() < FT->getNumParams())
6166 return nullptr;
6167
6168 bool NeedsNewDecl = false;
6169 unsigned i = 0;
6170 SmallVector<QualType, 8> OverloadParams;
6171
6172 for (QualType ParamType : FT->param_types()) {
6173
6174 // Convert array arguments to pointer to simplify type lookup.
6175 ExprResult ArgRes =
6177 if (ArgRes.isInvalid())
6178 return nullptr;
6179 Expr *Arg = ArgRes.get();
6180 QualType ArgType = Arg->getType();
6181 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6182 !ArgType->isPointerType() ||
6183 !ArgType->getPointeeType().hasAddressSpace() ||
6185 OverloadParams.push_back(ParamType);
6186 continue;
6187 }
6188
6189 QualType PointeeType = ParamType->getPointeeType();
6190 if (PointeeType.hasAddressSpace())
6191 continue;
6192
6193 NeedsNewDecl = true;
6194 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6195
6196 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6197 OverloadParams.push_back(Context.getPointerType(PointeeType));
6198 }
6199
6200 if (!NeedsNewDecl)
6201 return nullptr;
6202
6204 EPI.Variadic = FT->isVariadic();
6205 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6206 OverloadParams, EPI);
6207 DeclContext *Parent = FDecl->getParent();
6208 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6209 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6210 FDecl->getIdentifier(), OverloadTy,
6211 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6212 false,
6213 /*hasPrototype=*/true);
6215 FT = cast<FunctionProtoType>(OverloadTy);
6216 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6217 QualType ParamType = FT->getParamType(i);
6218 ParmVarDecl *Parm =
6219 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6220 SourceLocation(), nullptr, ParamType,
6221 /*TInfo=*/nullptr, SC_None, nullptr);
6222 Parm->setScopeInfo(0, i);
6223 Params.push_back(Parm);
6224 }
6225 OverloadDecl->setParams(Params);
6226 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6227 return OverloadDecl;
6228}
6229
6230static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6231 FunctionDecl *Callee,
6232 MultiExprArg ArgExprs) {
6233 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6234 // similar attributes) really don't like it when functions are called with an
6235 // invalid number of args.
6236 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6237 /*PartialOverloading=*/false) &&
6238 !Callee->isVariadic())
6239 return;
6240 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6241 return;
6242
6243 if (const EnableIfAttr *Attr =
6244 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6245 S.Diag(Fn->getBeginLoc(),
6246 isa<CXXMethodDecl>(Callee)
6247 ? diag::err_ovl_no_viable_member_function_in_call
6248 : diag::err_ovl_no_viable_function_in_call)
6249 << Callee << Callee->getSourceRange();
6250 S.Diag(Callee->getLocation(),
6251 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6252 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6253 return;
6254 }
6255}
6256
6258 const UnresolvedMemberExpr *const UME, Sema &S) {
6259
6260 const auto GetFunctionLevelDCIfCXXClass =
6261 [](Sema &S) -> const CXXRecordDecl * {
6262 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6263 if (!DC || !DC->getParent())
6264 return nullptr;
6265
6266 // If the call to some member function was made from within a member
6267 // function body 'M' return return 'M's parent.
6268 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6269 return MD->getParent()->getCanonicalDecl();
6270 // else the call was made from within a default member initializer of a
6271 // class, so return the class.
6272 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6273 return RD->getCanonicalDecl();
6274 return nullptr;
6275 };
6276 // If our DeclContext is neither a member function nor a class (in the
6277 // case of a lambda in a default member initializer), we can't have an
6278 // enclosing 'this'.
6279
6280 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6281 if (!CurParentClass)
6282 return false;
6283
6284 // The naming class for implicit member functions call is the class in which
6285 // name lookup starts.
6286 const CXXRecordDecl *const NamingClass =
6288 assert(NamingClass && "Must have naming class even for implicit access");
6289
6290 // If the unresolved member functions were found in a 'naming class' that is
6291 // related (either the same or derived from) to the class that contains the
6292 // member function that itself contained the implicit member access.
6293
6294 return CurParentClass == NamingClass ||
6295 CurParentClass->isDerivedFrom(NamingClass);
6296}
6297
6298static void
6300 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6301
6302 if (!UME)
6303 return;
6304
6305 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6306 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6307 // already been captured, or if this is an implicit member function call (if
6308 // it isn't, an attempt to capture 'this' should already have been made).
6309 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6310 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6311 return;
6312
6313 // Check if the naming class in which the unresolved members were found is
6314 // related (same as or is a base of) to the enclosing class.
6315
6317 return;
6318
6319
6320 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6321 // If the enclosing function is not dependent, then this lambda is
6322 // capture ready, so if we can capture this, do so.
6323 if (!EnclosingFunctionCtx->isDependentContext()) {
6324 // If the current lambda and all enclosing lambdas can capture 'this' -
6325 // then go ahead and capture 'this' (since our unresolved overload set
6326 // contains at least one non-static member function).
6327 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6328 S.CheckCXXThisCapture(CallLoc);
6329 } else if (S.CurContext->isDependentContext()) {
6330 // ... since this is an implicit member reference, that might potentially
6331 // involve a 'this' capture, mark 'this' for potential capture in
6332 // enclosing lambdas.
6333 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6334 CurLSI->addPotentialThisCapture(CallLoc);
6335 }
6336}
6337
6338// Once a call is fully resolved, warn for unqualified calls to specific
6339// C++ standard functions, like move and forward.
6341 const CallExpr *Call) {
6342 // We are only checking unary move and forward so exit early here.
6343 if (Call->getNumArgs() != 1)
6344 return;
6345
6346 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6347 if (!E || isa<UnresolvedLookupExpr>(E))
6348 return;
6349 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6350 if (!DRE || !DRE->getLocation().isValid())
6351 return;
6352
6353 if (DRE->getQualifier())
6354 return;
6355
6356 const FunctionDecl *FD = Call->getDirectCallee();
6357 if (!FD)
6358 return;
6359
6360 // Only warn for some functions deemed more frequent or problematic.
6361 unsigned BuiltinID = FD->getBuiltinID();
6362 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6363 return;
6364
6365 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6367 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6368}
6369
6371 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6372 Expr *ExecConfig) {
6374 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6375 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6376 if (Call.isInvalid())
6377 return Call;
6378
6379 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6380 // language modes.
6381 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6382 ULE && ULE->hasExplicitTemplateArgs() &&
6383 ULE->decls_begin() == ULE->decls_end()) {
6384 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6385 ? diag::warn_cxx17_compat_adl_only_template_id
6386 : diag::ext_adl_only_template_id)
6387 << ULE->getName();
6388 }
6389
6390 if (LangOpts.OpenMP)
6391 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6392 ExecConfig);
6393 if (LangOpts.CPlusPlus) {
6394 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6396
6397 // If we previously found that the id-expression of this call refers to a
6398 // consteval function but the call is dependent, we should not treat is an
6399 // an invalid immediate call.
6400 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6401 DRE && Call.get()->isValueDependent()) {
6403 }
6404 }
6405 return Call;
6406}
6407
6409 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6410 Expr *ExecConfig, bool IsExecConfig,
6411 bool AllowRecovery) {
6412 // Since this might be a postfix expression, get rid of ParenListExprs.
6414 if (Result.isInvalid()) return ExprError();
6415 Fn = Result.get();
6416
6417 if (CheckArgsForPlaceholders(ArgExprs))
6418 return ExprError();
6419
6420 if (getLangOpts().CPlusPlus) {
6421 // If this is a pseudo-destructor expression, build the call immediately.
6422 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6423 if (!ArgExprs.empty()) {
6424 // Pseudo-destructor calls should not have any arguments.
6425 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6427 SourceRange(ArgExprs.front()->getBeginLoc(),
6428 ArgExprs.back()->getEndLoc()));
6429 }
6430
6431 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6432 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6433 }
6434 if (Fn->getType() == Context.PseudoObjectTy) {
6435 ExprResult result = CheckPlaceholderExpr(Fn);
6436 if (result.isInvalid()) return ExprError();
6437 Fn = result.get();
6438 }
6439
6440 // Determine whether this is a dependent call inside a C++ template,
6441 // in which case we won't do any semantic analysis now.
6442 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6443 if (ExecConfig) {
6445 cast<CallExpr>(ExecConfig), ArgExprs,
6447 RParenLoc, CurFPFeatureOverrides());
6448 } else {
6449
6451 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6452 Fn->getBeginLoc());
6453
6454 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6455 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6456 }
6457 }
6458
6459 // Determine whether this is a call to an object (C++ [over.call.object]).
6460 if (Fn->getType()->isRecordType())
6461 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6462 RParenLoc);
6463
6464 if (Fn->getType() == Context.UnknownAnyTy) {
6465 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6466 if (result.isInvalid()) return ExprError();
6467 Fn = result.get();
6468 }
6469
6470 if (Fn->getType() == Context.BoundMemberTy) {
6471 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6472 RParenLoc, ExecConfig, IsExecConfig,
6473 AllowRecovery);
6474 }
6475 }
6476
6477 // Check for overloaded calls. This can happen even in C due to extensions.
6478 if (Fn->getType() == Context.OverloadTy) {
6480
6481 // We aren't supposed to apply this logic if there's an '&' involved.
6484 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6485 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6486 OverloadExpr *ovl = find.Expression;
6487 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6489 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6490 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6491 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6492 RParenLoc, ExecConfig, IsExecConfig,
6493 AllowRecovery);
6494 }
6495 }
6496
6497 // If we're directly calling a function, get the appropriate declaration.
6498 if (Fn->getType() == Context.UnknownAnyTy) {
6499 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6500 if (result.isInvalid()) return ExprError();
6501 Fn = result.get();
6502 }
6503
6504 Expr *NakedFn = Fn->IgnoreParens();
6505
6506 bool CallingNDeclIndirectly = false;
6507 NamedDecl *NDecl = nullptr;
6508 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6509 if (UnOp->getOpcode() == UO_AddrOf) {
6510 CallingNDeclIndirectly = true;
6511 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6512 }
6513 }
6514
6515 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6516 NDecl = DRE->getDecl();
6517
6518 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6519 if (FDecl && FDecl->getBuiltinID()) {
6520 // Rewrite the function decl for this builtin by replacing parameters
6521 // with no explicit address space with the address space of the arguments
6522 // in ArgExprs.
6523 if ((FDecl =
6524 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6525 NDecl = FDecl;
6527 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6528 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6529 nullptr, DRE->isNonOdrUse());
6530 }
6531 }
6532 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6533 NDecl = ME->getMemberDecl();
6534
6535 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6536 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6537 FD, /*Complain=*/true, Fn->getBeginLoc()))
6538 return ExprError();
6539
6540 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6541
6542 // If this expression is a call to a builtin function in HIP device
6543 // compilation, allow a pointer-type argument to default address space to be
6544 // passed as a pointer-type parameter to a non-default address space.
6545 // If Arg is declared in the default address space and Param is declared
6546 // in a non-default address space, perform an implicit address space cast to
6547 // the parameter type.
6548 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6549 FD->getBuiltinID()) {
6550 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6551 ++Idx) {
6552 ParmVarDecl *Param = FD->getParamDecl(Idx);
6553 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6554 !ArgExprs[Idx]->getType()->isPointerType())
6555 continue;
6556
6557 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6558 auto ArgTy = ArgExprs[Idx]->getType();
6559 auto ArgPtTy = ArgTy->getPointeeType();
6560 auto ArgAS = ArgPtTy.getAddressSpace();
6561
6562 // Add address space cast if target address spaces are different
6563 bool NeedImplicitASC =
6564 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6565 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6566 // or from specific AS which has target AS matching that of Param.
6568 if (!NeedImplicitASC)
6569 continue;
6570
6571 // First, ensure that the Arg is an RValue.
6572 if (ArgExprs[Idx]->isGLValue()) {
6573 ArgExprs[Idx] = ImplicitCastExpr::Create(
6574 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6575 nullptr, VK_PRValue, FPOptionsOverride());
6576 }
6577
6578 // Construct a new arg type with address space of Param
6579 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6580 ArgPtQuals.setAddressSpace(ParamAS);
6581 auto NewArgPtTy =
6582 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6583 auto NewArgTy =
6585 ArgTy.getQualifiers());
6586
6587 // Finally perform an implicit address space cast
6588 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6589 CK_AddressSpaceConversion)
6590 .get();
6591 }
6592 }
6593 }
6594
6596 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6597 assert(!getLangOpts().CPlusPlus);
6598 assert((Fn->containsErrors() ||
6599 llvm::any_of(ArgExprs,
6600 [](clang::Expr *E) { return E->containsErrors(); })) &&
6601 "should only occur in error-recovery path.");
6602 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6603 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6604 }
6605 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6606 ExecConfig, IsExecConfig);
6607}
6608
6610 MultiExprArg CallArgs) {
6611 StringRef Name = Context.BuiltinInfo.getName(Id);
6612 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6614 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6615
6616 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6617 assert(BuiltInDecl && "failed to find builtin declaration");
6618
6619 ExprResult DeclRef =
6620 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6621 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6622
6624 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6625
6626 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6627 return Call.get();
6628}
6629
6631 SourceLocation BuiltinLoc,
6632 SourceLocation RParenLoc) {
6633 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6634 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6635}
6636
6638 SourceLocation BuiltinLoc,
6639 SourceLocation RParenLoc) {
6642 QualType SrcTy = E->getType();
6643 if (!SrcTy->isDependentType() &&
6644 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6645 return ExprError(
6646 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6647 << DestTy << SrcTy << E->getSourceRange());
6648 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6649}
6650
6652 SourceLocation BuiltinLoc,
6653 SourceLocation RParenLoc) {
6654 TypeSourceInfo *TInfo;
6655 GetTypeFromParser(ParsedDestTy, &TInfo);
6656 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6657}
6658
6660 SourceLocation LParenLoc,
6661 ArrayRef<Expr *> Args,
6662 SourceLocation RParenLoc, Expr *Config,
6663 bool IsExecConfig, ADLCallKind UsesADL) {
6664 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6665 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6666
6667 // Functions with 'interrupt' attribute cannot be called directly.
6668 if (FDecl) {
6669 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
6670 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6671 return ExprError();
6672 }
6673 if (FDecl->hasAttr<ARMInterruptAttr>()) {
6674 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
6675 return ExprError();
6676 }
6677 }
6678
6679 // X86 interrupt handlers may only call routines with attribute
6680 // no_caller_saved_registers since there is no efficient way to
6681 // save and restore the non-GPR state.
6682 if (auto *Caller = getCurFunctionDecl()) {
6683 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6684 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6685 const TargetInfo &TI = Context.getTargetInfo();
6686 bool HasNonGPRRegisters =
6687 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6688 if (HasNonGPRRegisters &&
6689 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6690 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6691 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6692 if (FDecl)
6693 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6694 }
6695 }
6696 }
6697
6698 // Promote the function operand.
6699 // We special-case function promotion here because we only allow promoting
6700 // builtin functions to function pointers in the callee of a call.
6702 QualType ResultTy;
6703 if (BuiltinID &&
6704 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6705 // Extract the return type from the (builtin) function pointer type.
6706 // FIXME Several builtins still have setType in
6707 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6708 // Builtins.td to ensure they are correct before removing setType calls.
6709 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6710 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6711 ResultTy = FDecl->getCallResultType();
6712 } else {
6714 ResultTy = Context.BoolTy;
6715 }
6716 if (Result.isInvalid())
6717 return ExprError();
6718 Fn = Result.get();
6719
6720 // Check for a valid function type, but only if it is not a builtin which
6721 // requires custom type checking. These will be handled by
6722 // CheckBuiltinFunctionCall below just after creation of the call expression.
6723 const FunctionType *FuncT = nullptr;
6724 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6725 retry:
6726 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6727 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6728 // have type pointer to function".
6729 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6730 if (!FuncT)
6731 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6732 << Fn->getType() << Fn->getSourceRange());
6733 } else if (const BlockPointerType *BPT =
6734 Fn->getType()->getAs<BlockPointerType>()) {
6735 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6736 } else {
6737 // Handle calls to expressions of unknown-any type.
6738 if (Fn->getType() == Context.UnknownAnyTy) {
6739 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6740 if (rewrite.isInvalid())
6741 return ExprError();
6742 Fn = rewrite.get();
6743 goto retry;
6744 }
6745
6746 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6747 << Fn->getType() << Fn->getSourceRange());
6748 }
6749 }
6750
6751 // Get the number of parameters in the function prototype, if any.
6752 // We will allocate space for max(Args.size(), NumParams) arguments
6753 // in the call expression.
6754 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6755 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6756
6757 CallExpr *TheCall;
6758 if (Config) {
6759 assert(UsesADL == ADLCallKind::NotADL &&
6760 "CUDAKernelCallExpr should not use ADL");
6761 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6762 Args, ResultTy, VK_PRValue, RParenLoc,
6763 CurFPFeatureOverrides(), NumParams);
6764 } else {
6765 TheCall =
6766 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6767 CurFPFeatureOverrides(), NumParams, UsesADL);
6768 }
6769
6771 // Forget about the nulled arguments since typo correction
6772 // do not handle them well.
6773 TheCall->shrinkNumArgs(Args.size());
6774 // C cannot always handle TypoExpr nodes in builtin calls and direct
6775 // function calls as their argument checking don't necessarily handle
6776 // dependent types properly, so make sure any TypoExprs have been
6777 // dealt with.
6779 if (!Result.isUsable()) return ExprError();
6780 CallExpr *TheOldCall = TheCall;
6781 TheCall = dyn_cast<CallExpr>(Result.get());
6782 bool CorrectedTypos = TheCall != TheOldCall;
6783 if (!TheCall) return Result;
6784 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6785
6786 // A new call expression node was created if some typos were corrected.
6787 // However it may not have been constructed with enough storage. In this
6788 // case, rebuild the node with enough storage. The waste of space is
6789 // immaterial since this only happens when some typos were corrected.
6790 if (CorrectedTypos && Args.size() < NumParams) {
6791 if (Config)
6793 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6794 RParenLoc, CurFPFeatureOverrides(), NumParams);
6795 else
6796 TheCall =
6797 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6798 CurFPFeatureOverrides(), NumParams, UsesADL);
6799 }
6800 // We can now handle the nulled arguments for the default arguments.
6801 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6802 }
6803
6804 // Bail out early if calling a builtin with custom type checking.
6805 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6806 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6807 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
6809 return E;
6810 }
6811
6812 if (getLangOpts().CUDA) {
6813 if (Config) {
6814 // CUDA: Kernel calls must be to global functions
6815 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6816 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6817 << FDecl << Fn->getSourceRange());
6818
6819 // CUDA: Kernel function must have 'void' return type
6820 if (!FuncT->getReturnType()->isVoidType() &&
6821 !FuncT->getReturnType()->getAs<AutoType>() &&
6823 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6824 << Fn->getType() << Fn->getSourceRange());
6825 } else {
6826 // CUDA: Calls to global functions must be configured
6827 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6828 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6829 << FDecl << Fn->getSourceRange());
6830 }
6831 }
6832
6833 // Check for a valid return type
6834 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6835 FDecl))
6836 return ExprError();
6837
6838 // We know the result type of the call, set it.
6839 TheCall->setType(FuncT->getCallResultType(Context));
6841
6842 // WebAssembly tables can't be used as arguments.
6843 if (Context.getTargetInfo().getTriple().isWasm()) {
6844 for (const Expr *Arg : Args) {
6845 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
6846 return ExprError(Diag(Arg->getExprLoc(),
6847 diag::err_wasm_table_as_function_parameter));
6848 }
6849 }
6850 }
6851
6852 if (Proto) {
6853 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6854 IsExecConfig))
6855 return ExprError();
6856 } else {
6857 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6858
6859 if (FDecl) {
6860 // Check if we have too few/too many template arguments, based
6861 // on our knowledge of the function definition.
6862 const FunctionDecl *Def = nullptr;
6863 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6864 Proto = Def->getType()->getAs<FunctionProtoType>();
6865 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6866 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6867 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6868 }
6869
6870 // If the function we're calling isn't a function prototype, but we have
6871 // a function prototype from a prior declaratiom, use that prototype.
6872 if (!FDecl->hasPrototype())
6873 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6874 }
6875
6876 // If we still haven't found a prototype to use but there are arguments to
6877 // the call, diagnose this as calling a function without a prototype.
6878 // However, if we found a function declaration, check to see if
6879 // -Wdeprecated-non-prototype was disabled where the function was declared.
6880 // If so, we will silence the diagnostic here on the assumption that this
6881 // interface is intentional and the user knows what they're doing. We will
6882 // also silence the diagnostic if there is a function declaration but it
6883 // was implicitly defined (the user already gets diagnostics about the
6884 // creation of the implicit function declaration, so the additional warning
6885 // is not helpful).
6886 if (!Proto && !Args.empty() &&
6887 (!FDecl || (!FDecl->isImplicit() &&
6888 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
6889 FDecl->getLocation()))))
6890 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
6891 << (FDecl != nullptr) << FDecl;
6892
6893 // Promote the arguments (C99 6.5.2.2p6).
6894 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6895 Expr *Arg = Args[i];
6896
6897 if (Proto && i < Proto->getNumParams()) {
6899 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6900 ExprResult ArgE =
6902 if (ArgE.isInvalid())
6903 return true;
6904
6905 Arg = ArgE.getAs<Expr>();
6906
6907 } else {
6909
6910 if (ArgE.isInvalid())
6911 return true;
6912
6913 Arg = ArgE.getAs<Expr>();
6914 }
6915
6916 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6917 diag::err_call_incomplete_argument, Arg))
6918 return ExprError();
6919
6920 TheCall->setArg(i, Arg);
6921 }
6922 TheCall->computeDependence();
6923 }
6924
6925 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6926 if (!isa<RequiresExprBodyDecl>(CurContext) &&
6927 Method->isImplicitObjectMemberFunction())
6928 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6929 << Fn->getSourceRange() << 0);
6930
6931 // Check for sentinels
6932 if (NDecl)
6933 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6934
6935 // Warn for unions passing across security boundary (CMSE).
6936 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6937 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6938 if (const auto *RT =
6939 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6940 if (RT->getDecl()->isOrContainsUnion())
6941 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6942 << 0 << i;
6943 }
6944 }
6945 }
6946
6947 // Do special checking on direct calls to functions.
6948 if (FDecl) {
6949 if (CheckFunctionCall(FDecl, TheCall, Proto))
6950 return ExprError();
6951
6952 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6953
6954 if (BuiltinID)
6955 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6956 } else if (NDecl) {
6957 if (CheckPointerCall(NDecl, TheCall, Proto))
6958 return ExprError();
6959 } else {
6960 if (CheckOtherCall(TheCall, Proto))
6961 return ExprError();
6962 }
6963
6964 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6965}
6966
6969 SourceLocation RParenLoc, Expr *InitExpr) {
6970 assert(Ty && "ActOnCompoundLiteral(): missing type");
6971 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6972
6973 TypeSourceInfo *TInfo;
6974 QualType literalType = GetTypeFromParser(Ty, &TInfo);
6975 if (!TInfo)
6976 TInfo = Context.getTrivialTypeSourceInfo(literalType);
6977
6978 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6979}
6980
6983 SourceLocation RParenLoc, Expr *LiteralExpr) {
6984 QualType literalType = TInfo->getType();
6985
6986 if (literalType->isArrayType()) {
6988 LParenLoc, Context.getBaseElementType(literalType),
6989 diag::err_array_incomplete_or_sizeless_type,
6990 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6991 return ExprError();
6992 if (literalType->isVariableArrayType()) {
6993 // C23 6.7.10p4: An entity of variable length array type shall not be
6994 // initialized except by an empty initializer.
6995 //
6996 // The C extension warnings are issued from ParseBraceInitializer() and
6997 // do not need to be issued here. However, we continue to issue an error
6998 // in the case there are initializers or we are compiling C++. We allow
6999 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7000 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7001 // FIXME: should we allow this construct in C++ when it makes sense to do
7002 // so?
7003 //
7004 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7005 // shall specify an object type or an array of unknown size, but not a
7006 // variable length array type. This seems odd, as it allows 'int a[size] =
7007 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7008 // says, this is what's implemented here for C (except for the extension
7009 // that permits constant foldable size arrays)
7010
7011 auto diagID = LangOpts.CPlusPlus
7012 ? diag::err_variable_object_no_init
7013 : diag::err_compound_literal_with_vla_type;
7014 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7015 diagID))
7016 return ExprError();
7017 }
7018 } else if (!literalType->isDependentType() &&
7019 RequireCompleteType(LParenLoc, literalType,
7020 diag::err_typecheck_decl_incomplete_type,
7021 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7022 return ExprError();
7023
7024 InitializedEntity Entity
7028 SourceRange(LParenLoc, RParenLoc),
7029 /*InitList=*/true);
7030 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7031 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7032 &literalType);
7033 if (Result.isInvalid())
7034 return ExprError();
7035 LiteralExpr = Result.get();
7036
7037 bool isFileScope = !CurContext->isFunctionOrMethod();
7038
7039 // In C, compound literals are l-values for some reason.
7040 // For GCC compatibility, in C++, file-scope array compound literals with
7041 // constant initializers are also l-values, and compound literals are
7042 // otherwise prvalues.
7043 //
7044 // (GCC also treats C++ list-initialized file-scope array prvalues with
7045 // constant initializers as l-values, but that's non-conforming, so we don't
7046 // follow it there.)
7047 //
7048 // FIXME: It would be better to handle the lvalue cases as materializing and
7049 // lifetime-extending a temporary object, but our materialized temporaries
7050 // representation only supports lifetime extension from a variable, not "out
7051 // of thin air".
7052 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7053 // is bound to the result of applying array-to-pointer decay to the compound
7054 // literal.
7055 // FIXME: GCC supports compound literals of reference type, which should
7056 // obviously have a value kind derived from the kind of reference involved.
7057 ExprValueKind VK =
7058 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7059 ? VK_PRValue
7060 : VK_LValue;
7061
7062 if (isFileScope)
7063 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7064 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7065 Expr *Init = ILE->getInit(i);
7066 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7067 }
7068
7069 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7070 VK, LiteralExpr, isFileScope);
7071 if (isFileScope) {
7072 if (!LiteralExpr->isTypeDependent() &&
7073 !LiteralExpr->isValueDependent() &&
7074 !literalType->isDependentType()) // C99 6.5.2.5p3
7075 if (CheckForConstantInitializer(LiteralExpr))
7076 return ExprError();
7077 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7078 literalType.getAddressSpace() != LangAS::Default) {
7079 // Embedded-C extensions to C99 6.5.2.5:
7080 // "If the compound literal occurs inside the body of a function, the
7081 // type name shall not be qualified by an address-space qualifier."
7082 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7083 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7084 return ExprError();
7085 }
7086
7087 if (!isFileScope && !getLangOpts().CPlusPlus) {
7088 // Compound literals that have automatic storage duration are destroyed at
7089 // the end of the scope in C; in C++, they're just temporaries.
7090
7091 // Emit diagnostics if it is or contains a C union type that is non-trivial
7092 // to destruct.
7096
7097 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7098 if (literalType.isDestructedType()) {
7100 ExprCleanupObjects.push_back(E);
7102 }
7103 }
7104
7107 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7108 E->getInitializer()->getExprLoc());
7109
7110 return MaybeBindToTemporary(E);
7111}
7112
7115 SourceLocation RBraceLoc) {
7116 // Only produce each kind of designated initialization diagnostic once.
7117 SourceLocation FirstDesignator;
7118 bool DiagnosedArrayDesignator = false;
7119 bool DiagnosedNestedDesignator = false;
7120 bool DiagnosedMixedDesignator = false;
7121
7122 // Check that any designated initializers are syntactically valid in the
7123 // current language mode.
7124 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7125 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7126 if (FirstDesignator.isInvalid())
7127 FirstDesignator = DIE->getBeginLoc();
7128
7129 if (!getLangOpts().CPlusPlus)
7130 break;
7131
7132 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7133 DiagnosedNestedDesignator = true;
7134 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7135 << DIE->getDesignatorsSourceRange();
7136 }
7137
7138 for (auto &Desig : DIE->designators()) {
7139 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7140 DiagnosedArrayDesignator = true;
7141 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7142 << Desig.getSourceRange();
7143 }
7144 }
7145
7146 if (!DiagnosedMixedDesignator &&
7147 !isa<DesignatedInitExpr>(InitArgList[0])) {
7148 DiagnosedMixedDesignator = true;
7149 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7150 << DIE->getSourceRange();
7151 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7152 << InitArgList[0]->getSourceRange();
7153 }
7154 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7155 isa<DesignatedInitExpr>(InitArgList[0])) {
7156 DiagnosedMixedDesignator = true;
7157 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7158 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7159 << DIE->getSourceRange();
7160 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7161 << InitArgList[I]->getSourceRange();
7162 }
7163 }
7164
7165 if (FirstDesignator.isValid()) {
7166 // Only diagnose designated initiaization as a C++20 extension if we didn't
7167 // already diagnose use of (non-C++20) C99 designator syntax.
7168 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7169 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7170 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7171 ? diag::warn_cxx17_compat_designated_init
7172 : diag::ext_cxx_designated_init);
7173 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7174 Diag(FirstDesignator, diag::ext_designated_init);
7175 }
7176 }
7177
7178 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7179}
7180
7183 SourceLocation RBraceLoc) {
7184 // Semantic analysis for initializers is done by ActOnDeclarator() and
7185 // CheckInitializer() - it requires knowledge of the object being initialized.
7186
7187 // Immediately handle non-overload placeholders. Overloads can be
7188 // resolved contextually, but everything else here can't.
7189 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7190 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7191 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7192
7193 // Ignore failures; dropping the entire initializer list because
7194 // of one failure would be terrible for indexing/etc.
7195 if (result.isInvalid()) continue;
7196
7197 InitArgList[I] = result.get();
7198 }
7199 }
7200
7201 InitListExpr *E =
7202 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7203 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7204 return E;
7205}
7206
7208 assert(E.get()->getType()->isBlockPointerType());
7209 assert(E.get()->isPRValue());
7210
7211 // Only do this in an r-value context.
7212 if (!getLangOpts().ObjCAutoRefCount) return;
7213
7215 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7216 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7218}
7219
7221 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7222 // Also, callers should have filtered out the invalid cases with
7223 // pointers. Everything else should be possible.
7224
7225 QualType SrcTy = Src.get()->getType();
7226 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7227 return CK_NoOp;
7228
7229 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7231 llvm_unreachable("member pointer type in C");
7232
7233 case Type::STK_CPointer:
7236 switch (DestTy->getScalarTypeKind()) {
7237 case Type::STK_CPointer: {
7238 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7239 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7240 if (SrcAS != DestAS)
7241 return CK_AddressSpaceConversion;
7242 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7243 return CK_NoOp;
7244 return CK_BitCast;
7245 }
7247 return (SrcKind == Type::STK_BlockPointer
7248 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7250 if (SrcKind == Type::STK_ObjCObjectPointer)
7251 return CK_BitCast;
7252 if (SrcKind == Type::STK_CPointer)
7253 return CK_CPointerToObjCPointerCast;
7255 return CK_BlockPointerToObjCPointerCast;
7256 case Type::STK_Bool:
7257 return CK_PointerToBoolean;
7258 case Type::STK_Integral:
7259 return CK_PointerToIntegral;
7260 case Type::STK_Floating:
7265 llvm_unreachable("illegal cast from pointer");
7266 }
7267 llvm_unreachable("Should have returned before this");
7268
7270 switch (DestTy->getScalarTypeKind()) {
7272 return CK_FixedPointCast;
7273 case Type::STK_Bool:
7274 return CK_FixedPointToBoolean;
7275 case Type::STK_Integral:
7276 return CK_FixedPointToIntegral;
7277 case Type::STK_Floating:
7278 return CK_FixedPointToFloating;
7281 Diag(Src.get()->getExprLoc(),
7282 diag::err_unimplemented_conversion_with_fixed_point_type)
7283 << DestTy;
7284 return CK_IntegralCast;
7285 case Type::STK_CPointer:
7289 llvm_unreachable("illegal cast to pointer type");
7290 }
7291 llvm_unreachable("Should have returned before this");
7292
7293 case Type::STK_Bool: // casting from bool is like casting from an integer
7294 case Type::STK_Integral:
7295 switch (DestTy->getScalarTypeKind()) {
7296 case Type::STK_CPointer:
7301 return CK_NullToPointer;
7302 return CK_IntegralToPointer;
7303 case Type::STK_Bool:
7304 return CK_IntegralToBoolean;
7305 case Type::STK_Integral:
7306 return CK_IntegralCast;
7307 case Type::STK_Floating:
7308 return CK_IntegralToFloating;
7310 Src = ImpCastExprToType(Src.get(),
7311 DestTy->castAs<ComplexType>()->getElementType(),
7312 CK_IntegralCast);
7313 return CK_IntegralRealToComplex;
7315 Src = ImpCastExprToType(Src.get(),
7316 DestTy->castAs<ComplexType>()->getElementType(),
7317 CK_IntegralToFloating);
7318 return CK_FloatingRealToComplex;
7320 llvm_unreachable("member pointer type in C");
7322 return CK_IntegralToFixedPoint;
7323 }
7324 llvm_unreachable("Should have returned before this");
7325
7326 case Type::STK_Floating:
7327 switch (DestTy->getScalarTypeKind()) {
7328 case Type::STK_Floating:
7329 return CK_FloatingCast;
7330 case Type::STK_Bool:
7331 return CK_FloatingToBoolean;
7332 case Type::STK_Integral:
7333 return CK_FloatingToIntegral;
7335 Src = ImpCastExprToType(Src.get(),
7336 DestTy->castAs<ComplexType>()->getElementType(),
7337 CK_FloatingCast);
7338 return CK_FloatingRealToComplex;
7340 Src = ImpCastExprToType(Src.get(),
7341 DestTy->castAs<ComplexType>()->getElementType(),
7342 CK_FloatingToIntegral);
7343 return CK_IntegralRealToComplex;
7344 case Type::STK_CPointer:
7347 llvm_unreachable("valid float->pointer cast?");
7349 llvm_unreachable("member pointer type in C");
7351 return CK_FloatingToFixedPoint;
7352 }
7353 llvm_unreachable("Should have returned before this");
7354
7356 switch (DestTy->getScalarTypeKind()) {
7358 return CK_FloatingComplexCast;
7360 return CK_FloatingComplexToIntegralComplex;
7361 case Type::STK_Floating: {
7362 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7363 if (Context.hasSameType(ET, DestTy))
7364 return CK_FloatingComplexToReal;
7365 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7366 return CK_FloatingCast;
7367 }
7368 case Type::STK_Bool:
7369 return CK_FloatingComplexToBoolean;
7370 case Type::STK_Integral:
7371 Src = ImpCastExprToType(Src.get(),
7372 SrcTy->castAs<ComplexType>()->getElementType(),
7373 CK_FloatingComplexToReal);
7374 return CK_FloatingToIntegral;
7375 case Type::STK_CPointer:
7378 llvm_unreachable("valid complex float->pointer cast?");
7380 llvm_unreachable("member pointer type in C");
7382 Diag(Src.get()->getExprLoc(),
7383 diag::err_unimplemented_conversion_with_fixed_point_type)
7384 << SrcTy;
7385 return CK_IntegralCast;
7386 }
7387 llvm_unreachable("Should have returned before this");
7388
7390 switch (DestTy->getScalarTypeKind()) {
7392 return CK_IntegralComplexToFloatingComplex;
7394 return CK_IntegralComplexCast;
7395 case Type::STK_Integral: {
7396 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7397 if (Context.hasSameType(ET, DestTy))
7398 return CK_IntegralComplexToReal;
7399 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7400 return CK_IntegralCast;
7401 }
7402 case Type::STK_Bool:
7403 return CK_IntegralComplexToBoolean;
7404 case Type::STK_Floating:
7405 Src = ImpCastExprToType(Src.get(),
7406 SrcTy->castAs<ComplexType>()->getElementType(),
7407 CK_IntegralComplexToReal);
7408 return CK_IntegralToFloating;
7409 case Type::STK_CPointer:
7412 llvm_unreachable("valid complex int->pointer cast?");
7414 llvm_unreachable("member pointer type in C");
7416 Diag(Src.get()->getExprLoc(),
7417 diag::err_unimplemented_conversion_with_fixed_point_type)
7418 << SrcTy;
7419 return CK_IntegralCast;
7420 }
7421 llvm_unreachable("Should have returned before this");
7422 }
7423
7424 llvm_unreachable("Unhandled scalar cast");
7425}
7426
7427static bool breakDownVectorType(QualType type, uint64_t &len,
7428 QualType &eltType) {
7429 // Vectors are simple.
7430 if (const VectorType *vecType = type->getAs<VectorType>()) {
7431 len = vecType->getNumElements();
7432 eltType = vecType->getElementType();
7433 assert(eltType->isScalarType());
7434 return true;
7435 }
7436
7437 // We allow lax conversion to and from non-vector types, but only if
7438 // they're real types (i.e. non-complex, non-pointer scalar types).
7439 if (!type->isRealType()) return false;
7440
7441 len = 1;
7442 eltType = type;
7443 return true;
7444}
7445
7447 assert(srcTy->isVectorType() || destTy->isVectorType());
7448
7449 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7450 if (!FirstType->isSVESizelessBuiltinType())
7451 return false;
7452
7453 const auto *VecTy = SecondType->getAs<VectorType>();
7454 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7455 };
7456
7457 return ValidScalableConversion(srcTy, destTy) ||
7458 ValidScalableConversion(destTy, srcTy);
7459}
7460
7462 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7463 return false;
7464
7465 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7466 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7467
7468 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7469 matSrcType->getNumColumns() == matDestType->getNumColumns();
7470}
7471
7473 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7474
7475 uint64_t SrcLen, DestLen;
7476 QualType SrcEltTy, DestEltTy;
7477 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7478 return false;
7479 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7480 return false;
7481
7482 // ASTContext::getTypeSize will return the size rounded up to a
7483 // power of 2, so instead of using that, we need to use the raw
7484 // element size multiplied by the element count.
7485 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7486 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7487
7488 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7489}
7490
7492 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7493 "expected at least one type to be a vector here");
7494
7495 bool IsSrcTyAltivec =
7496 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7498 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7500 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7502
7503 bool IsDestTyAltivec = DestTy->isVectorType() &&
7504 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7506 (DestTy->castAs<VectorType>()->getVectorKind() ==
7508 (DestTy->castAs<VectorType>()->getVectorKind() ==
7510
7511 return (IsSrcTyAltivec || IsDestTyAltivec);
7512}
7513
7515 assert(destTy->isVectorType() || srcTy->isVectorType());
7516
7517 // Disallow lax conversions between scalars and ExtVectors (these
7518 // conversions are allowed for other vector types because common headers
7519 // depend on them). Most scalar OP ExtVector cases are handled by the
7520 // splat path anyway, which does what we want (convert, not bitcast).
7521 // What this rules out for ExtVectors is crazy things like char4*float.
7522 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7523 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7524
7525 return areVectorTypesSameSize(srcTy, destTy);
7526}
7527
7529 assert(destTy->isVectorType() || srcTy->isVectorType());
7530
7531 switch (Context.getLangOpts().getLaxVectorConversions()) {
7533 return false;
7534
7536 if (!srcTy->isIntegralOrEnumerationType()) {
7537 auto *Vec = srcTy->getAs<VectorType>();
7538 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7539 return false;
7540 }
7541 if (!destTy->isIntegralOrEnumerationType()) {
7542 auto *Vec = destTy->getAs<VectorType>();
7543 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7544 return false;
7545 }
7546 // OK, integer (vector) -> integer (vector) bitcast.
7547 break;
7548
7550 break;
7551 }
7552
7553 return areLaxCompatibleVectorTypes(srcTy, destTy);
7554}
7555
7557 CastKind &Kind) {
7558 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7559 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7560 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7561 << DestTy << SrcTy << R;
7562 }
7563 } else if (SrcTy->isMatrixType()) {
7564 return Diag(R.getBegin(),
7565 diag::err_invalid_conversion_between_matrix_and_type)
7566 << SrcTy << DestTy << R;
7567 } else if (DestTy->isMatrixType()) {
7568 return Diag(R.getBegin(),
7569 diag::err_invalid_conversion_between_matrix_and_type)
7570 << DestTy << SrcTy << R;
7571 }
7572
7573 Kind = CK_MatrixCast;
7574 return false;
7575}
7576
7578 CastKind &Kind) {
7579 assert(VectorTy->isVectorType() && "Not a vector type!");
7580
7581 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7582 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7583 return Diag(R.getBegin(),
7584 Ty->isVectorType() ?
7585 diag::err_invalid_conversion_between_vectors :
7586 diag::err_invalid_conversion_between_vector_and_integer)
7587 << VectorTy << Ty << R;
7588 } else
7589 return Diag(R.getBegin(),
7590 diag::err_invalid_conversion_between_vector_and_scalar)
7591 << VectorTy << Ty << R;
7592
7593 Kind = CK_BitCast;
7594 return false;
7595}
7596
7598 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7599
7600 if (DestElemTy == SplattedExpr->getType())
7601 return SplattedExpr;
7602
7603 assert(DestElemTy->isFloatingType() ||
7604 DestElemTy->isIntegralOrEnumerationType());
7605
7606 CastKind CK;
7607 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7608 // OpenCL requires that we convert `true` boolean expressions to -1, but
7609 // only when splatting vectors.
7610 if (DestElemTy->isFloatingType()) {
7611 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7612 // in two steps: boolean to signed integral, then to floating.
7613 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7614 CK_BooleanToSignedIntegral);
7615 SplattedExpr = CastExprRes.get();
7616 CK = CK_IntegralToFloating;
7617 } else {
7618 CK = CK_BooleanToSignedIntegral;
7619 }
7620 } else {
7621 ExprResult CastExprRes = SplattedExpr;
7622 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7623 if (CastExprRes.isInvalid())
7624 return ExprError();
7625 SplattedExpr = CastExprRes.get();
7626 }
7627 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7628}
7629
7631 Expr *CastExpr, CastKind &Kind) {
7632 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7633
7634 QualType SrcTy = CastExpr->getType();
7635
7636 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7637 // an ExtVectorType.
7638 // In OpenCL, casts between vectors of different types are not allowed.
7639 // (See OpenCL 6.2).
7640 if (SrcTy->isVectorType()) {
7641 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7642 (getLangOpts().OpenCL &&
7643 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7644 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7645 << DestTy << SrcTy << R;
7646 return ExprError();
7647 }
7648 Kind = CK_BitCast;
7649 return CastExpr;
7650 }
7651
7652 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7653 // conversion will take place first from scalar to elt type, and then
7654 // splat from elt type to vector.
7655 if (SrcTy->isPointerType())
7656 return Diag(R.getBegin(),
7657 diag::err_invalid_conversion_between_vector_and_scalar)
7658 << DestTy << SrcTy << R;
7659
7660 Kind = CK_VectorSplat;
7661 return prepareVectorSplat(DestTy, CastExpr);
7662}
7663
7666 Declarator &D, ParsedType &Ty,
7667 SourceLocation RParenLoc, Expr *CastExpr) {
7668 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7669 "ActOnCastExpr(): missing type or expr");
7670
7672 if (D.isInvalidType())
7673 return ExprError();
7674
7675 if (getLangOpts().CPlusPlus) {
7676 // Check that there are no default arguments (C++ only).
7678 } else {
7679 // Make sure any TypoExprs have been dealt with.
7681 if (!Res.isUsable())
7682 return ExprError();
7683 CastExpr = Res.get();
7684 }
7685
7687
7688 QualType castType = castTInfo->getType();
7689 Ty = CreateParsedType(castType, castTInfo);
7690
7691 bool isVectorLiteral = false;
7692
7693 // Check for an altivec or OpenCL literal,
7694 // i.e. all the elements are integer constants.
7695 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7696 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7697 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7698 && castType->isVectorType() && (PE || PLE)) {
7699 if (PLE && PLE->getNumExprs() == 0) {
7700 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7701 return ExprError();
7702 }
7703 if (PE || PLE->getNumExprs() == 1) {
7704 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7705 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7706 isVectorLiteral = true;
7707 }
7708 else
7709 isVectorLiteral = true;
7710 }
7711
7712 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7713 // then handle it as such.
7714 if (isVectorLiteral)
7715 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7716
7717 // If the Expr being casted is a ParenListExpr, handle it specially.
7718 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7719 // sequence of BinOp comma operators.
7720 if (isa<ParenListExpr>(CastExpr)) {
7722 if (Result.isInvalid()) return ExprError();
7723 CastExpr = Result.get();
7724 }
7725
7726 if (getLangOpts().CPlusPlus && !castType->isVoidType())
7727 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7728
7730
7732
7734
7735 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7736}
7737
7739 SourceLocation RParenLoc, Expr *E,
7740 TypeSourceInfo *TInfo) {
7741 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7742 "Expected paren or paren list expression");
7743
7744 Expr **exprs;
7745 unsigned numExprs;
7746 Expr *subExpr;
7747 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7748 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7749 LiteralLParenLoc = PE->getLParenLoc();
7750 LiteralRParenLoc = PE->getRParenLoc();
7751 exprs = PE->getExprs();
7752 numExprs = PE->getNumExprs();
7753 } else { // isa<ParenExpr> by assertion at function entrance
7754 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7755 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7756 subExpr = cast<ParenExpr>(E)->getSubExpr();
7757 exprs = &subExpr;
7758 numExprs = 1;
7759 }
7760
7761 QualType Ty = TInfo->getType();
7762 assert(Ty->isVectorType() && "Expected vector type");
7763
7764 SmallVector<Expr *, 8> initExprs;
7765 const VectorType *VTy = Ty->castAs<VectorType>();
7766 unsigned numElems = VTy->getNumElements();
7767
7768 // '(...)' form of vector initialization in AltiVec: the number of
7769 // initializers must be one or must match the size of the vector.
7770 // If a single value is specified in the initializer then it will be
7771 // replicated to all the components of the vector
7773 VTy->getElementType()))
7774 return ExprError();
7776 // The number of initializers must be one or must match the size of the
7777 // vector. If a single value is specified in the initializer then it will
7778 // be replicated to all the components of the vector
7779 if (numExprs == 1) {
7780 QualType ElemTy = VTy->getElementType();
7781 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7782 if (Literal.isInvalid())
7783 return ExprError();
7784 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7785 PrepareScalarCast(Literal, ElemTy));
7786 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7787 }
7788 else if (numExprs < numElems) {
7789 Diag(E->getExprLoc(),
7790 diag::err_incorrect_number_of_vector_initializers);
7791 return ExprError();
7792 }
7793 else
7794 initExprs.append(exprs, exprs + numExprs);
7795 }
7796 else {
7797 // For OpenCL, when the number of initializers is a single value,
7798 // it will be replicated to all components of the vector.
7800 numExprs == 1) {
7801 QualType ElemTy = VTy->getElementType();
7802 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7803 if (Literal.isInvalid())
7804 return ExprError();
7805 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7806 PrepareScalarCast(Literal, ElemTy));
7807 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7808 }
7809
7810 initExprs.append(exprs, exprs + numExprs);
7811 }
7812 // FIXME: This means that pretty-printing the final AST will produce curly
7813 // braces instead of the original commas.
7814 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7815 initExprs, LiteralRParenLoc);
7816 initE->setType(Ty);
7817 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7818}
7819
7822 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7823 if (!E)
7824 return OrigExpr;
7825
7826 ExprResult Result(E->getExpr(0));
7827
7828 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7829 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7830 E->getExpr(i));
7831
7832 if (Result.isInvalid()) return ExprError();
7833
7834 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7835}
7836
7839 MultiExprArg Val) {
7840 return ParenListExpr::Create(Context, L, Val, R);
7841}
7842
7843bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7844 SourceLocation QuestionLoc) {
7845 const Expr *NullExpr = LHSExpr;
7846 const Expr *NonPointerExpr = RHSExpr;
7850
7851 if (NullKind == Expr::NPCK_NotNull) {
7852 NullExpr = RHSExpr;
7853 NonPointerExpr = LHSExpr;
7854 NullKind =
7857 }
7858
7859 if (NullKind == Expr::NPCK_NotNull)
7860 return false;
7861
7862 if (NullKind == Expr::NPCK_ZeroExpression)
7863 return false;
7864
7865 if (NullKind == Expr::NPCK_ZeroLiteral) {
7866 // In this case, check to make sure that we got here from a "NULL"
7867 // string in the source code.
7868 NullExpr = NullExpr->IgnoreParenImpCasts();
7869 SourceLocation loc = NullExpr->getExprLoc();
7870 if (!findMacroSpelling(loc, "NULL"))
7871 return false;
7872 }
7873
7874 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7875 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7876 << NonPointerExpr->getType() << DiagType
7877 << NonPointerExpr->getSourceRange();
7878 return true;
7879}
7880
7881/// Return false if the condition expression is valid, true otherwise.
7882static bool checkCondition(Sema &S, const Expr *Cond,
7883 SourceLocation QuestionLoc) {
7884 QualType CondTy = Cond->getType();
7885
7886 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7887 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7888 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7889 << CondTy << Cond->getSourceRange();
7890 return true;
7891 }
7892
7893 // C99 6.5.15p2
7894 if (CondTy->isScalarType()) return false;
7895
7896 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7897 << CondTy << Cond->getSourceRange();
7898 return true;
7899}
7900
7901/// Return false if the NullExpr can be promoted to PointerTy,
7902/// true otherwise.
7904 QualType PointerTy) {
7905 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7906 !NullExpr.get()->isNullPointerConstant(S.Context,
7908 return true;
7909
7910 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7911 return false;
7912}
7913
7914/// Checks compatibility between two pointers and return the resulting
7915/// type.
7917 ExprResult &RHS,
7919 QualType LHSTy = LHS.get()->getType();
7920 QualType RHSTy = RHS.get()->getType();
7921
7922 if (S.Context.hasSameType(LHSTy, RHSTy)) {
7923 // Two identical pointers types are always compatible.
7924 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
7925 }
7926
7927 QualType lhptee, rhptee;
7928
7929 // Get the pointee types.
7930 bool IsBlockPointer = false;
7931 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7932 lhptee = LHSBTy->getPointeeType();
7933 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7934 IsBlockPointer = true;
7935 } else {
7936 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7937 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7938 }
7939
7940 // C99 6.5.15p6: If both operands are pointers to compatible types or to
7941 // differently qualified versions of compatible types, the result type is
7942 // a pointer to an appropriately qualified version of the composite
7943 // type.
7944
7945 // Only CVR-qualifiers exist in the standard, and the differently-qualified
7946 // clause doesn't make sense for our extensions. E.g. address space 2 should
7947 // be incompatible with address space 3: they may live on different devices or
7948 // anything.
7949 Qualifiers lhQual = lhptee.getQualifiers();
7950 Qualifiers rhQual = rhptee.getQualifiers();
7951
7952 LangAS ResultAddrSpace = LangAS::Default;
7953 LangAS LAddrSpace = lhQual.getAddressSpace();
7954 LangAS RAddrSpace = rhQual.getAddressSpace();
7955
7956 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7957 // spaces is disallowed.
7958 if (lhQual.isAddressSpaceSupersetOf(rhQual))
7959 ResultAddrSpace = LAddrSpace;
7960 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7961 ResultAddrSpace = RAddrSpace;
7962 else {
7963 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7964 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7965 << RHS.get()->getSourceRange();
7966 return QualType();
7967 }
7968
7969 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7970 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7971 lhQual.removeCVRQualifiers();
7972 rhQual.removeCVRQualifiers();
7973
7974 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7975 // (C99 6.7.3) for address spaces. We assume that the check should behave in
7976 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7977 // qual types are compatible iff
7978 // * corresponded types are compatible
7979 // * CVR qualifiers are equal
7980 // * address spaces are equal
7981 // Thus for conditional operator we merge CVR and address space unqualified
7982 // pointees and if there is a composite type we return a pointer to it with
7983 // merged qualifiers.
7984 LHSCastKind =
7985 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7986 RHSCastKind =
7987 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7988 lhQual.removeAddressSpace();
7989 rhQual.removeAddressSpace();
7990
7991 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7992 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7993
7994 QualType CompositeTy = S.Context.mergeTypes(
7995 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
7996 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
7997
7998 if (CompositeTy.isNull()) {
7999 // In this situation, we assume void* type. No especially good
8000 // reason, but this is what gcc does, and we do have to pick
8001 // to get a consistent AST.
8002 QualType incompatTy;
8003 incompatTy = S.Context.getPointerType(
8004 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8005 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8006 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8007
8008 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8009 // for casts between types with incompatible address space qualifiers.
8010 // For the following code the compiler produces casts between global and
8011 // local address spaces of the corresponded innermost pointees:
8012 // local int *global *a;
8013 // global int *global *b;
8014 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8015 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8016 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8017 << RHS.get()->getSourceRange();
8018
8019 return incompatTy;
8020 }
8021
8022 // The pointer types are compatible.
8023 // In case of OpenCL ResultTy should have the address space qualifier
8024 // which is a superset of address spaces of both the 2nd and the 3rd
8025 // operands of the conditional operator.
8026 QualType ResultTy = [&, ResultAddrSpace]() {
8027 if (S.getLangOpts().OpenCL) {
8028 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8029 CompositeQuals.setAddressSpace(ResultAddrSpace);
8030 return S.Context
8031 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8032 .withCVRQualifiers(MergedCVRQual);
8033 }
8034 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8035 }();
8036 if (IsBlockPointer)
8037 ResultTy = S.Context.getBlockPointerType(ResultTy);
8038 else
8039 ResultTy = S.Context.getPointerType(ResultTy);
8040
8041 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8042 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8043 return ResultTy;
8044}
8045
8046/// Return the resulting type when the operands are both block pointers.
8048 ExprResult &LHS,
8049 ExprResult &RHS,
8051 QualType LHSTy = LHS.get()->getType();
8052 QualType RHSTy = RHS.get()->getType();
8053
8054 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8055 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8057 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8058 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8059 return destType;
8060 }
8061 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8062 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8063 << RHS.get()->getSourceRange();
8064 return QualType();
8065 }
8066
8067 // We have 2 block pointer types.
8068 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8069}
8070
8071/// Return the resulting type when the operands are both pointers.
8072static QualType
8074 ExprResult &RHS,
8076 // get the pointer types
8077 QualType LHSTy = LHS.get()->getType();
8078 QualType RHSTy = RHS.get()->getType();
8079
8080 // get the "pointed to" types
8081 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8082 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8083
8084 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8085 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8086 // Figure out necessary qualifiers (C99 6.5.15p6)
8087 QualType destPointee
8088 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8089 QualType destType = S.Context.getPointerType(destPointee);
8090 // Add qualifiers if necessary.
8091 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8092 // Promote to void*.
8093 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8094 return destType;
8095 }
8096 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8097 QualType destPointee
8098 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8099 QualType destType = S.Context.getPointerType(destPointee);
8100 // Add qualifiers if necessary.
8101 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8102 // Promote to void*.
8103 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8104 return destType;
8105 }
8106
8107 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8108}
8109
8110/// Return false if the first expression is not an integer and the second
8111/// expression is not a pointer, true otherwise.
8113 Expr* PointerExpr, SourceLocation Loc,
8114 bool IsIntFirstExpr) {
8115 if (!PointerExpr->getType()->isPointerType() ||
8116 !Int.get()->getType()->isIntegerType())
8117 return false;
8118
8119 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8120 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8121
8122 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8123 << Expr1->getType() << Expr2->getType()
8124 << Expr1->getSourceRange() << Expr2->getSourceRange();
8125 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8126 CK_IntegralToPointer);
8127 return true;
8128}
8129
8130/// Simple conversion between integer and floating point types.
8131///
8132/// Used when handling the OpenCL conditional operator where the
8133/// condition is a vector while the other operands are scalar.
8134///
8135/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8136/// types are either integer or floating type. Between the two
8137/// operands, the type with the higher rank is defined as the "result
8138/// type". The other operand needs to be promoted to the same type. No
8139/// other type promotion is allowed. We cannot use
8140/// UsualArithmeticConversions() for this purpose, since it always
8141/// promotes promotable types.
8143 ExprResult &RHS,
8144 SourceLocation QuestionLoc) {
8146 if (LHS.isInvalid())
8147 return QualType();
8149 if (RHS.isInvalid())
8150 return QualType();
8151
8152 // For conversion purposes, we ignore any qualifiers.
8153 // For example, "const float" and "float" are equivalent.
8154 QualType LHSType =
8156 QualType RHSType =
8158
8159 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8160 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8161 << LHSType << LHS.get()->getSourceRange();
8162 return QualType();
8163 }
8164
8165 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8166 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8167 << RHSType << RHS.get()->getSourceRange();
8168 return QualType();
8169 }
8170
8171 // If both types are identical, no conversion is needed.
8172 if (LHSType == RHSType)
8173 return LHSType;
8174
8175 // Now handle "real" floating types (i.e. float, double, long double).
8176 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8177 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8178 /*IsCompAssign = */ false);
8179
8180 // Finally, we have two differing integer types.
8181 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8182 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8183}
8184
8185/// Convert scalar operands to a vector that matches the
8186/// condition in length.
8187///
8188/// Used when handling the OpenCL conditional operator where the
8189/// condition is a vector while the other operands are scalar.
8190///
8191/// We first compute the "result type" for the scalar operands
8192/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8193/// into a vector of that type where the length matches the condition
8194/// vector type. s6.11.6 requires that the element types of the result
8195/// and the condition must have the same number of bits.
8196static QualType
8198 QualType CondTy, SourceLocation QuestionLoc) {
8199 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8200 if (ResTy.isNull()) return QualType();
8201
8202 const VectorType *CV = CondTy->getAs<VectorType>();
8203 assert(CV);
8204
8205 // Determine the vector result type
8206 unsigned NumElements = CV->getNumElements();
8207 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8208
8209 // Ensure that all types have the same number of bits
8211 != S.Context.getTypeSize(ResTy)) {
8212 // Since VectorTy is created internally, it does not pretty print
8213 // with an OpenCL name. Instead, we just print a description.
8214 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8215 SmallString<64> Str;
8216 llvm::raw_svector_ostream OS(Str);
8217 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8218 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8219 << CondTy << OS.str();
8220 return QualType();
8221 }
8222
8223 // Convert operands to the vector result type
8224 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8225 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8226
8227 return VectorTy;
8228}
8229
8230/// Return false if this is a valid OpenCL condition vector
8232 SourceLocation QuestionLoc) {
8233 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8234 // integral type.
8235 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8236 assert(CondTy);
8237 QualType EleTy = CondTy->getElementType();
8238 if (EleTy->isIntegerType()) return false;
8239
8240 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8241 << Cond->getType() << Cond->getSourceRange();
8242 return true;
8243}
8244
8245/// Return false if the vector condition type and the vector
8246/// result type are compatible.
8247///
8248/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8249/// number of elements, and their element types have the same number
8250/// of bits.
8251static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8252 SourceLocation QuestionLoc) {
8253 const VectorType *CV = CondTy->getAs<VectorType>();
8254 const VectorType *RV = VecResTy->getAs<VectorType>();
8255 assert(CV && RV);
8256
8257 if (CV->getNumElements() != RV->getNumElements()) {
8258 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8259 << CondTy << VecResTy;
8260 return true;
8261 }
8262
8263 QualType CVE = CV->getElementType();
8264 QualType RVE = RV->getElementType();
8265
8266 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8267 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8268 << CondTy << VecResTy;
8269 return true;
8270 }
8271
8272 return false;
8273}
8274
8275/// Return the resulting type for the conditional operator in
8276/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8277/// s6.3.i) when the condition is a vector type.
8278static QualType
8280 ExprResult &LHS, ExprResult &RHS,
8281 SourceLocation QuestionLoc) {
8283 if (Cond.isInvalid())
8284 return QualType();
8285 QualType CondTy = Cond.get()->getType();
8286
8287 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8288 return QualType();
8289
8290 // If either operand is a vector then find the vector type of the
8291 // result as specified in OpenCL v1.1 s6.3.i.
8292 if (LHS.get()->getType()->isVectorType() ||
8293 RHS.get()->getType()->isVectorType()) {
8294 bool IsBoolVecLang =
8295 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8296 QualType VecResTy =
8297 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8298 /*isCompAssign*/ false,
8299 /*AllowBothBool*/ true,
8300 /*AllowBoolConversions*/ false,
8301 /*AllowBooleanOperation*/ IsBoolVecLang,
8302 /*ReportInvalid*/ true);
8303 if (VecResTy.isNull())
8304 return QualType();
8305 // The result type must match the condition type as specified in
8306 // OpenCL v1.1 s6.11.6.
8307 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8308 return QualType();
8309 return VecResTy;
8310 }
8311
8312 // Both operands are scalar.
8313 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8314}
8315
8316/// Return true if the Expr is block type
8317static bool checkBlockType(Sema &S, const Expr *E) {
8318 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8319 QualType Ty = CE->getCallee()->getType();
8320 if (Ty->isBlockPointerType()) {
8321 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8322 return true;
8323 }
8324 }
8325 return false;
8326}
8327
8328/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8329/// In that case, LHS = cond.
8330/// C99 6.5.15
8332 ExprResult &RHS, ExprValueKind &VK,
8333 ExprObjectKind &OK,
8334 SourceLocation QuestionLoc) {
8335
8336 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8337 if (!LHSResult.isUsable()) return QualType();
8338 LHS = LHSResult;
8339
8340 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8341 if (!RHSResult.isUsable()) return QualType();
8342 RHS = RHSResult;
8343
8344 // C++ is sufficiently different to merit its own checker.
8345 if (getLangOpts().CPlusPlus)
8346 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8347
8348 VK = VK_PRValue;
8349 OK = OK_Ordinary;
8350
8352 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8353 RHS.get()->isTypeDependent())) {
8354 assert(!getLangOpts().CPlusPlus);
8355 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8356 RHS.get()->containsErrors()) &&
8357 "should only occur in error-recovery path.");
8358 return Context.DependentTy;
8359 }
8360
8361 // The OpenCL operator with a vector condition is sufficiently
8362 // different to merit its own checker.
8363 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8364 Cond.get()->getType()->isExtVectorType())
8365 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8366
8367 // First, check the condition.
8368 Cond = UsualUnaryConversions(Cond.get());
8369 if (Cond.isInvalid())
8370 return QualType();
8371 if (checkCondition(*this, Cond.get(), QuestionLoc))
8372 return QualType();
8373
8374 // Handle vectors.
8375 if (LHS.get()->getType()->isVectorType() ||
8376 RHS.get()->getType()->isVectorType())
8377 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8378 /*AllowBothBool*/ true,
8379 /*AllowBoolConversions*/ false,
8380 /*AllowBooleanOperation*/ false,
8381 /*ReportInvalid*/ true);
8382
8383 QualType ResTy =
8384 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8385 if (LHS.isInvalid() || RHS.isInvalid())
8386 return QualType();
8387
8388 // WebAssembly tables are not allowed as conditional LHS or RHS.
8389 QualType LHSTy = LHS.get()->getType();
8390 QualType RHSTy = RHS.get()->getType();
8391 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8392 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8393 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8394 return QualType();
8395 }
8396
8397 // Diagnose attempts to convert between __ibm128, __float128 and long double
8398 // where such conversions currently can't be handled.
8399 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8400 Diag(QuestionLoc,
8401 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8402 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8403 return QualType();
8404 }
8405
8406 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8407 // selection operator (?:).
8408 if (getLangOpts().OpenCL &&
8409 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8410 return QualType();
8411 }
8412
8413 // If both operands have arithmetic type, do the usual arithmetic conversions
8414 // to find a common type: C99 6.5.15p3,5.
8415 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8416 // Disallow invalid arithmetic conversions, such as those between bit-
8417 // precise integers types of different sizes, or between a bit-precise
8418 // integer and another type.
8419 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8420 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8421 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8422 << RHS.get()->getSourceRange();
8423 return QualType();
8424 }
8425
8426 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8427 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8428
8429 return ResTy;
8430 }
8431
8432 // If both operands are the same structure or union type, the result is that
8433 // type.
8434 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8435 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8436 if (LHSRT->getDecl() == RHSRT->getDecl())
8437 // "If both the operands have structure or union type, the result has
8438 // that type." This implies that CV qualifiers are dropped.
8440 RHSTy.getUnqualifiedType());
8441 // FIXME: Type of conditional expression must be complete in C mode.
8442 }
8443
8444 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8445 // The following || allows only one side to be void (a GCC-ism).
8446 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8447 QualType ResTy;
8448 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8449 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8450 } else if (RHSTy->isVoidType()) {
8451 ResTy = RHSTy;
8452 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8453 << RHS.get()->getSourceRange();
8454 } else {
8455 ResTy = LHSTy;
8456 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8457 << LHS.get()->getSourceRange();
8458 }
8459 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8460 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8461 return ResTy;
8462 }
8463
8464 // C23 6.5.15p7:
8465 // ... if both the second and third operands have nullptr_t type, the
8466 // result also has that type.
8467 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8468 return ResTy;
8469
8470 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8471 // the type of the other operand."
8472 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8473 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8474
8475 // All objective-c pointer type analysis is done here.
8476 QualType compositeType =
8477 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8478 if (LHS.isInvalid() || RHS.isInvalid())
8479 return QualType();
8480 if (!compositeType.isNull())
8481 return compositeType;
8482
8483
8484 // Handle block pointer types.
8485 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8486 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8487 QuestionLoc);
8488
8489 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8490 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8491 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8492 QuestionLoc);
8493
8494 // GCC compatibility: soften pointer/integer mismatch. Note that
8495 // null pointers have been filtered out by this point.
8496 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8497 /*IsIntFirstExpr=*/true))
8498 return RHSTy;
8499 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8500 /*IsIntFirstExpr=*/false))
8501 return LHSTy;
8502
8503 // Emit a better diagnostic if one of the expressions is a null pointer
8504 // constant and the other is not a pointer type. In this case, the user most
8505 // likely forgot to take the address of the other expression.
8506 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8507 return QualType();
8508
8509 // Finally, if the LHS and RHS types are canonically the same type, we can
8510 // use the common sugared type.
8511 if (Context.hasSameType(LHSTy, RHSTy))
8512 return Context.getCommonSugaredType(LHSTy, RHSTy);
8513
8514 // Otherwise, the operands are not compatible.
8515 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8516 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8517 << RHS.get()->getSourceRange();
8518 return QualType();
8519}
8520
8521/// SuggestParentheses - Emit a note with a fixit hint that wraps
8522/// ParenRange in parentheses.
8524 const PartialDiagnostic &Note,
8525 SourceRange ParenRange) {
8526 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8527 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8528 EndLoc.isValid()) {
8529 Self.Diag(Loc, Note)
8530 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8531 << FixItHint::CreateInsertion(EndLoc, ")");
8532 } else {
8533 // We can't display the parentheses, so just show the bare note.
8534 Self.Diag(Loc, Note) << ParenRange;
8535 }
8536}
8537
8539 return BinaryOperator::isAdditiveOp(Opc) ||
8541 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8542 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8543 // not any of the logical operators. Bitwise-xor is commonly used as a
8544 // logical-xor because there is no logical-xor operator. The logical
8545 // operators, including uses of xor, have a high false positive rate for
8546 // precedence warnings.
8547}
8548
8549/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8550/// expression, either using a built-in or overloaded operator,
8551/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8552/// expression.
8554 const Expr **RHSExprs) {
8555 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8556 E = E->IgnoreImpCasts();
8558 E = E->IgnoreImpCasts();
8559 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8560 E = MTE->getSubExpr();
8561 E = E->IgnoreImpCasts();
8562 }
8563
8564 // Built-in binary operator.
8565 if (const auto *OP = dyn_cast<BinaryOperator>(E);
8566 OP && IsArithmeticOp(OP->getOpcode())) {
8567 *Opcode = OP->getOpcode();
8568 *RHSExprs = OP->getRHS();
8569 return true;
8570 }
8571
8572 // Overloaded operator.
8573 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8574 if (Call->getNumArgs() != 2)
8575 return false;
8576
8577 // Make sure this is really a binary operator that is safe to pass into
8578 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8579 OverloadedOperatorKind OO = Call->getOperator();
8580 if (OO < OO_Plus || OO > OO_Arrow ||
8581 OO == OO_PlusPlus || OO == OO_MinusMinus)
8582 return false;
8583
8585 if (IsArithmeticOp(OpKind)) {
8586 *Opcode = OpKind;
8587 *RHSExprs = Call->getArg(1);
8588 return true;
8589 }
8590 }
8591
8592 return false;
8593}
8594
8595/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8596/// or is a logical expression such as (x==y) which has int type, but is
8597/// commonly interpreted as boolean.
8598static bool ExprLooksBoolean(const Expr *E) {
8599 E = E->IgnoreParenImpCasts();
8600
8601 if (E->getType()->isBooleanType())
8602 return true;
8603 if (const auto *OP = dyn_cast<BinaryOperator>(E))
8604 return OP->isComparisonOp() || OP->isLogicalOp();
8605 if (const auto *OP = dyn_cast<UnaryOperator>(E))
8606 return OP->getOpcode() == UO_LNot;
8607 if (E->getType()->isPointerType())
8608 return true;
8609 // FIXME: What about overloaded operator calls returning "unspecified boolean
8610 // type"s (commonly pointer-to-members)?
8611
8612 return false;
8613}
8614
8615/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8616/// and binary operator are mixed in a way that suggests the programmer assumed
8617/// the conditional operator has higher precedence, for example:
8618/// "int x = a + someBinaryCondition ? 1 : 2".
8620 Expr *Condition, const Expr *LHSExpr,
8621 const Expr *RHSExpr) {
8622 BinaryOperatorKind CondOpcode;
8623 const Expr *CondRHS;
8624
8625 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8626 return;
8627 if (!ExprLooksBoolean(CondRHS))
8628 return;
8629
8630 // The condition is an arithmetic binary expression, with a right-
8631 // hand side that looks boolean, so warn.
8632
8633 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8634 ? diag::warn_precedence_bitwise_conditional
8635 : diag::warn_precedence_conditional;
8636
8637 Self.Diag(OpLoc, DiagID)
8638 << Condition->getSourceRange()
8639 << BinaryOperator::getOpcodeStr(CondOpcode);
8640
8642 Self, OpLoc,
8643 Self.PDiag(diag::note_precedence_silence)
8644 << BinaryOperator::getOpcodeStr(CondOpcode),
8645 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8646
8647 SuggestParentheses(Self, OpLoc,
8648 Self.PDiag(diag::note_precedence_conditional_first),
8649 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8650}
8651
8652/// Compute the nullability of a conditional expression.
8654 QualType LHSTy, QualType RHSTy,
8655 ASTContext &Ctx) {
8656 if (!ResTy->isAnyPointerType())
8657 return ResTy;
8658
8659 auto GetNullability = [](QualType Ty) {
8660 std::optional<NullabilityKind> Kind = Ty->getNullability();
8661 if (Kind) {
8662 // For our purposes, treat _Nullable_result as _Nullable.
8665 return *Kind;
8666 }
8668 };
8669
8670 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8671 NullabilityKind MergedKind;
8672
8673 // Compute nullability of a binary conditional expression.
8674 if (IsBin) {
8675 if (LHSKind == NullabilityKind::NonNull)
8676 MergedKind = NullabilityKind::NonNull;
8677 else
8678 MergedKind = RHSKind;
8679 // Compute nullability of a normal conditional expression.
8680 } else {
8681 if (LHSKind == NullabilityKind::Nullable ||
8682 RHSKind == NullabilityKind::Nullable)
8683 MergedKind = NullabilityKind::Nullable;
8684 else if (LHSKind == NullabilityKind::NonNull)
8685 MergedKind = RHSKind;
8686 else if (RHSKind == NullabilityKind::NonNull)
8687 MergedKind = LHSKind;
8688 else
8689 MergedKind = NullabilityKind::Unspecified;
8690 }
8691
8692 // Return if ResTy already has the correct nullability.
8693 if (GetNullability(ResTy) == MergedKind)
8694 return ResTy;
8695
8696 // Strip all nullability from ResTy.
8697 while (ResTy->getNullability())
8698 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8699
8700 // Create a new AttributedType with the new nullability kind.
8701 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8702 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8703}
8704
8706 SourceLocation ColonLoc,
8707 Expr *CondExpr, Expr *LHSExpr,
8708 Expr *RHSExpr) {
8710 // C cannot handle TypoExpr nodes in the condition because it
8711 // doesn't handle dependent types properly, so make sure any TypoExprs have
8712 // been dealt with before checking the operands.
8713 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8714 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8715 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8716
8717 if (!CondResult.isUsable())
8718 return ExprError();
8719
8720 if (LHSExpr) {
8721 if (!LHSResult.isUsable())
8722 return ExprError();
8723 }
8724
8725 if (!RHSResult.isUsable())
8726 return ExprError();
8727
8728 CondExpr = CondResult.get();
8729 LHSExpr = LHSResult.get();
8730 RHSExpr = RHSResult.get();
8731 }
8732
8733 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8734 // was the condition.
8735 OpaqueValueExpr *opaqueValue = nullptr;
8736 Expr *commonExpr = nullptr;
8737 if (!LHSExpr) {
8738 commonExpr = CondExpr;
8739 // Lower out placeholder types first. This is important so that we don't
8740 // try to capture a placeholder. This happens in few cases in C++; such
8741 // as Objective-C++'s dictionary subscripting syntax.
8742 if (commonExpr->hasPlaceholderType()) {
8743 ExprResult result = CheckPlaceholderExpr(commonExpr);
8744 if (!result.isUsable()) return ExprError();
8745 commonExpr = result.get();
8746 }
8747 // We usually want to apply unary conversions *before* saving, except
8748 // in the special case of a C++ l-value conditional.
8749 if (!(getLangOpts().CPlusPlus
8750 && !commonExpr->isTypeDependent()
8751 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8752 && commonExpr->isGLValue()
8753 && commonExpr->isOrdinaryOrBitFieldObject()
8754 && RHSExpr->isOrdinaryOrBitFieldObject()
8755 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8756 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8757 if (commonRes.isInvalid())
8758 return ExprError();
8759 commonExpr = commonRes.get();
8760 }
8761
8762 // If the common expression is a class or array prvalue, materialize it
8763 // so that we can safely refer to it multiple times.
8764 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8765 commonExpr->getType()->isArrayType())) {
8766 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8767 if (MatExpr.isInvalid())
8768 return ExprError();
8769 commonExpr = MatExpr.get();
8770 }
8771
8772 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8773 commonExpr->getType(),
8774 commonExpr->getValueKind(),
8775 commonExpr->getObjectKind(),
8776 commonExpr);
8777 LHSExpr = CondExpr = opaqueValue;
8778 }
8779
8780 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8783 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8784 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8785 VK, OK, QuestionLoc);
8786 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8787 RHS.isInvalid())
8788 return ExprError();
8789
8790 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8791 RHS.get());
8792
8793 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8794
8795 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8796 Context);
8797
8798 if (!commonExpr)
8799 return new (Context)
8800 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8801 RHS.get(), result, VK, OK);
8802
8804 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8805 ColonLoc, result, VK, OK);
8806}
8807
8809 unsigned FromAttributes = 0, ToAttributes = 0;
8810 if (const auto *FromFn =
8811 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
8812 FromAttributes =
8813 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8814 if (const auto *ToFn =
8815 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
8816 ToAttributes =
8817 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8818
8819 return FromAttributes != ToAttributes;
8820}
8821
8822// Check if we have a conversion between incompatible cmse function pointer
8823// types, that is, a conversion between a function pointer with the
8824// cmse_nonsecure_call attribute and one without.
8826 QualType ToType) {
8827 if (const auto *ToFn =
8828 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8829 if (const auto *FromFn =
8830 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8831 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8832 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8833
8834 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8835 }
8836 }
8837 return false;
8838}
8839
8840// checkPointerTypesForAssignment - This is a very tricky routine (despite
8841// being closely modeled after the C99 spec:-). The odd characteristic of this
8842// routine is it effectively iqnores the qualifiers on the top level pointee.
8843// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8844// FIXME: add a couple examples in this comment.
8848 assert(LHSType.isCanonical() && "LHS not canonicalized!");
8849 assert(RHSType.isCanonical() && "RHS not canonicalized!");
8850
8851 // get the "pointed to" type (ignoring qualifiers at the top level)
8852 const Type *lhptee, *rhptee;
8853 Qualifiers lhq, rhq;
8854 std::tie(lhptee, lhq) =
8855 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8856 std::tie(rhptee, rhq) =
8857 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8858
8860
8861 // C99 6.5.16.1p1: This following citation is common to constraints
8862 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8863 // qualifiers of the type *pointed to* by the right;
8864
8865 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8866 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8868 // Ignore lifetime for further calculation.
8869 lhq.removeObjCLifetime();
8870 rhq.removeObjCLifetime();
8871 }
8872
8873 if (!lhq.compatiblyIncludes(rhq)) {
8874 // Treat address-space mismatches as fatal.
8875 if (!lhq.isAddressSpaceSupersetOf(rhq))
8877
8878 // It's okay to add or remove GC or lifetime qualifiers when converting to
8879 // and from void*.
8880 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8883 && (lhptee->isVoidType() || rhptee->isVoidType()))
8884 ; // keep old
8885
8886 // Treat lifetime mismatches as fatal.
8887 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8889
8890 // For GCC/MS compatibility, other qualifier mismatches are treated
8891 // as still compatible in C.
8893 }
8894
8895 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8896 // incomplete type and the other is a pointer to a qualified or unqualified
8897 // version of void...
8898 if (lhptee->isVoidType()) {
8899 if (rhptee->isIncompleteOrObjectType())
8900 return ConvTy;
8901
8902 // As an extension, we allow cast to/from void* to function pointer.
8903 assert(rhptee->isFunctionType());
8905 }
8906
8907 if (rhptee->isVoidType()) {
8908 if (lhptee->isIncompleteOrObjectType())
8909 return ConvTy;
8910
8911 // As an extension, we allow cast to/from void* to function pointer.
8912 assert(lhptee->isFunctionType());
8914 }
8915
8916 if (!S.Diags.isIgnored(
8917 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
8918 Loc) &&
8919 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
8920 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
8922
8923 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8924 // unqualified versions of compatible types, ...
8925 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8926 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8927 // Check if the pointee types are compatible ignoring the sign.
8928 // We explicitly check for char so that we catch "char" vs
8929 // "unsigned char" on systems where "char" is unsigned.
8930 if (lhptee->isCharType())
8931 ltrans = S.Context.UnsignedCharTy;
8932 else if (lhptee->hasSignedIntegerRepresentation())
8933 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8934
8935 if (rhptee->isCharType())
8936 rtrans = S.Context.UnsignedCharTy;
8937 else if (rhptee->hasSignedIntegerRepresentation())
8938 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8939
8940 if (ltrans == rtrans) {
8941 // Types are compatible ignoring the sign. Qualifier incompatibility
8942 // takes priority over sign incompatibility because the sign
8943 // warning can be disabled.
8944 if (ConvTy != Sema::Compatible)
8945 return ConvTy;
8946
8948 }
8949
8950 // If we are a multi-level pointer, it's possible that our issue is simply
8951 // one of qualification - e.g. char ** -> const char ** is not allowed. If
8952 // the eventual target type is the same and the pointers have the same
8953 // level of indirection, this must be the issue.
8954 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8955 do {
8956 std::tie(lhptee, lhq) =
8957 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8958 std::tie(rhptee, rhq) =
8959 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8960
8961 // Inconsistent address spaces at this point is invalid, even if the
8962 // address spaces would be compatible.
8963 // FIXME: This doesn't catch address space mismatches for pointers of
8964 // different nesting levels, like:
8965 // __local int *** a;
8966 // int ** b = a;
8967 // It's not clear how to actually determine when such pointers are
8968 // invalidly incompatible.
8969 if (lhq.getAddressSpace() != rhq.getAddressSpace())
8971
8972 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8973
8974 if (lhptee == rhptee)
8976 }
8977
8978 // General pointer incompatibility takes priority over qualifiers.
8979 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8982 }
8983 if (!S.getLangOpts().CPlusPlus &&
8984 S.IsFunctionConversion(ltrans, rtrans, ltrans))
8986 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8988 if (S.IsInvalidSMECallConversion(rtrans, ltrans))
8990 return ConvTy;
8991}
8992
8993/// checkBlockPointerTypesForAssignment - This routine determines whether two
8994/// block pointer types are compatible or whether a block and normal pointer
8995/// are compatible. It is more restrict than comparing two function pointer
8996// types.
8999 QualType RHSType) {
9000 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9001 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9002
9003 QualType lhptee, rhptee;
9004
9005 // get the "pointed to" type (ignoring qualifiers at the top level)
9006 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9007 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9008
9009 // In C++, the types have to match exactly.
9010 if (S.getLangOpts().CPlusPlus)
9012
9014
9015 // For blocks we enforce that qualifiers are identical.
9016 Qualifiers LQuals = lhptee.getLocalQualifiers();
9017 Qualifiers RQuals = rhptee.getLocalQualifiers();
9018 if (S.getLangOpts().OpenCL) {
9019 LQuals.removeAddressSpace();
9020 RQuals.removeAddressSpace();
9021 }
9022 if (LQuals != RQuals)
9024
9025 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9026 // assignment.
9027 // The current behavior is similar to C++ lambdas. A block might be
9028 // assigned to a variable iff its return type and parameters are compatible
9029 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9030 // an assignment. Presumably it should behave in way that a function pointer
9031 // assignment does in C, so for each parameter and return type:
9032 // * CVR and address space of LHS should be a superset of CVR and address
9033 // space of RHS.
9034 // * unqualified types should be compatible.
9035 if (S.getLangOpts().OpenCL) {
9037 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9038 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9040 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9042
9043 return ConvTy;
9044}
9045
9046/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9047/// for assignment compatibility.
9050 QualType RHSType) {
9051 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9052 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9053
9054 if (LHSType->isObjCBuiltinType()) {
9055 // Class is not compatible with ObjC object pointers.
9056 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9057 !RHSType->isObjCQualifiedClassType())
9059 return Sema::Compatible;
9060 }
9061 if (RHSType->isObjCBuiltinType()) {
9062 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9063 !LHSType->isObjCQualifiedClassType())
9065 return Sema::Compatible;
9066 }
9067 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9068 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9069
9070 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9071 // make an exception for id<P>
9072 !LHSType->isObjCQualifiedIdType())
9074
9075 if (S.Context.typesAreCompatible(LHSType, RHSType))
9076 return Sema::Compatible;
9077 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9080}
9081
9084 QualType LHSType, QualType RHSType) {
9085 // Fake up an opaque expression. We don't actually care about what
9086 // cast operations are required, so if CheckAssignmentConstraints
9087 // adds casts to this they'll be wasted, but fortunately that doesn't
9088 // usually happen on valid code.
9089 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9090 ExprResult RHSPtr = &RHSExpr;
9091 CastKind K;
9092
9093 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9094}
9095
9096/// This helper function returns true if QT is a vector type that has element
9097/// type ElementType.
9098static bool isVector(QualType QT, QualType ElementType) {
9099 if (const VectorType *VT = QT->getAs<VectorType>())
9100 return VT->getElementType().getCanonicalType() == ElementType;
9101 return false;
9102}
9103
9104/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9105/// has code to accommodate several GCC extensions when type checking
9106/// pointers. Here are some objectionable examples that GCC considers warnings:
9107///
9108/// int a, *pint;
9109/// short *pshort;
9110/// struct foo *pfoo;
9111///
9112/// pint = pshort; // warning: assignment from incompatible pointer type
9113/// a = pint; // warning: assignment makes integer from pointer without a cast
9114/// pint = a; // warning: assignment makes pointer from integer without a cast
9115/// pint = pfoo; // warning: assignment from incompatible pointer type
9116///
9117/// As a result, the code for dealing with pointers is more complex than the
9118/// C99 spec dictates.
9119///
9120/// Sets 'Kind' for any result kind except Incompatible.
9123 CastKind &Kind, bool ConvertRHS) {
9124 QualType RHSType = RHS.get()->getType();
9125 QualType OrigLHSType = LHSType;
9126
9127 // Get canonical types. We're not formatting these types, just comparing
9128 // them.
9129 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9130 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9131
9132 // Common case: no conversion required.
9133 if (LHSType == RHSType) {
9134 Kind = CK_NoOp;
9135 return Compatible;
9136 }
9137
9138 // If the LHS has an __auto_type, there are no additional type constraints
9139 // to be worried about.
9140 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9141 if (AT->isGNUAutoType()) {
9142 Kind = CK_NoOp;
9143 return Compatible;
9144 }
9145 }
9146
9147 // If we have an atomic type, try a non-atomic assignment, then just add an
9148 // atomic qualification step.
9149 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9151 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9152 if (result != Compatible)
9153 return result;
9154 if (Kind != CK_NoOp && ConvertRHS)
9155 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9156 Kind = CK_NonAtomicToAtomic;
9157 return Compatible;
9158 }
9159
9160 // If the left-hand side is a reference type, then we are in a
9161 // (rare!) case where we've allowed the use of references in C,
9162 // e.g., as a parameter type in a built-in function. In this case,
9163 // just make sure that the type referenced is compatible with the
9164 // right-hand side type. The caller is responsible for adjusting
9165 // LHSType so that the resulting expression does not have reference
9166 // type.
9167 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9168 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9169 Kind = CK_LValueBitCast;
9170 return Compatible;
9171 }
9172 return Incompatible;
9173 }
9174
9175 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9176 // to the same ExtVector type.
9177 if (LHSType->isExtVectorType()) {
9178 if (RHSType->isExtVectorType())
9179 return Incompatible;
9180 if (RHSType->isArithmeticType()) {
9181 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9182 if (ConvertRHS)
9183 RHS = prepareVectorSplat(LHSType, RHS.get());
9184 Kind = CK_VectorSplat;
9185 return Compatible;
9186 }
9187 }
9188
9189 // Conversions to or from vector type.
9190 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9191 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9192 // Allow assignments of an AltiVec vector type to an equivalent GCC
9193 // vector type and vice versa
9194 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9195 Kind = CK_BitCast;
9196 return Compatible;
9197 }
9198
9199 // If we are allowing lax vector conversions, and LHS and RHS are both
9200 // vectors, the total size only needs to be the same. This is a bitcast;
9201 // no bits are changed but the result type is different.
9202 if (isLaxVectorConversion(RHSType, LHSType)) {
9203 // The default for lax vector conversions with Altivec vectors will
9204 // change, so if we are converting between vector types where
9205 // at least one is an Altivec vector, emit a warning.
9206 if (Context.getTargetInfo().getTriple().isPPC() &&
9207 anyAltivecTypes(RHSType, LHSType) &&
9208 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9209 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9210 << RHSType << LHSType;
9211 Kind = CK_BitCast;
9212 return IncompatibleVectors;
9213 }
9214 }
9215
9216 // When the RHS comes from another lax conversion (e.g. binops between
9217 // scalars and vectors) the result is canonicalized as a vector. When the
9218 // LHS is also a vector, the lax is allowed by the condition above. Handle
9219 // the case where LHS is a scalar.
9220 if (LHSType->isScalarType()) {
9221 const VectorType *VecType = RHSType->getAs<VectorType>();
9222 if (VecType && VecType->getNumElements() == 1 &&
9223 isLaxVectorConversion(RHSType, LHSType)) {
9224 if (Context.getTargetInfo().getTriple().isPPC() &&
9226 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9228 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9229 << RHSType << LHSType;
9230 ExprResult *VecExpr = &RHS;
9231 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9232 Kind = CK_BitCast;
9233 return Compatible;
9234 }
9235 }
9236
9237 // Allow assignments between fixed-length and sizeless SVE vectors.
9238 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9239 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9240 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9241 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9242 Kind = CK_BitCast;
9243 return Compatible;
9244 }
9245
9246 // Allow assignments between fixed-length and sizeless RVV vectors.
9247 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9248 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9249 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9250 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9251 Kind = CK_BitCast;
9252 return Compatible;
9253 }
9254 }
9255
9256 return Incompatible;
9257 }
9258
9259 // Diagnose attempts to convert between __ibm128, __float128 and long double
9260 // where such conversions currently can't be handled.
9261 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9262 return Incompatible;
9263
9264 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9265 // discards the imaginary part.
9266 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9267 !LHSType->getAs<ComplexType>())
9268 return Incompatible;
9269
9270 // Arithmetic conversions.
9271 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9272 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9273 if (ConvertRHS)
9274 Kind = PrepareScalarCast(RHS, LHSType);
9275 return Compatible;
9276 }
9277
9278 // Conversions to normal pointers.
9279 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9280 // U* -> T*
9281 if (isa<PointerType>(RHSType)) {
9282 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9283 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9284 if (AddrSpaceL != AddrSpaceR)
9285 Kind = CK_AddressSpaceConversion;
9286 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9287 Kind = CK_NoOp;
9288 else
9289 Kind = CK_BitCast;
9290 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9291 RHS.get()->getBeginLoc());
9292 }
9293
9294 // int -> T*
9295 if (RHSType->isIntegerType()) {
9296 Kind = CK_IntegralToPointer; // FIXME: null?
9297 return IntToPointer;
9298 }
9299
9300 // C pointers are not compatible with ObjC object pointers,
9301 // with two exceptions:
9302 if (isa<ObjCObjectPointerType>(RHSType)) {
9303 // - conversions to void*
9304 if (LHSPointer->getPointeeType()->isVoidType()) {
9305 Kind = CK_BitCast;
9306 return Compatible;
9307 }
9308
9309 // - conversions from 'Class' to the redefinition type
9310 if (RHSType->isObjCClassType() &&
9311 Context.hasSameType(LHSType,
9313 Kind = CK_BitCast;
9314 return Compatible;
9315 }
9316
9317 Kind = CK_BitCast;
9318 return IncompatiblePointer;
9319 }
9320
9321 // U^ -> void*
9322 if (RHSType->getAs<BlockPointerType>()) {
9323 if (LHSPointer->getPointeeType()->isVoidType()) {
9324 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9325 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9326 ->getPointeeType()
9327 .getAddressSpace();
9328 Kind =
9329 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9330 return Compatible;
9331 }
9332 }
9333
9334 return Incompatible;
9335 }
9336
9337 // Conversions to block pointers.
9338 if (isa<BlockPointerType>(LHSType)) {
9339 // U^ -> T^
9340 if (RHSType->isBlockPointerType()) {
9341 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9342 ->getPointeeType()
9343 .getAddressSpace();
9344 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9345 ->getPointeeType()
9346 .getAddressSpace();
9347 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9348 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9349 }
9350
9351 // int or null -> T^
9352 if (RHSType->isIntegerType()) {
9353 Kind = CK_IntegralToPointer; // FIXME: null
9354 return IntToBlockPointer;
9355 }
9356
9357 // id -> T^
9358 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9359 Kind = CK_AnyPointerToBlockPointerCast;
9360 return Compatible;
9361 }
9362
9363 // void* -> T^
9364 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9365 if (RHSPT->getPointeeType()->isVoidType()) {
9366 Kind = CK_AnyPointerToBlockPointerCast;
9367 return Compatible;
9368 }
9369
9370 return Incompatible;
9371 }
9372
9373 // Conversions to Objective-C pointers.
9374 if (isa<ObjCObjectPointerType>(LHSType)) {
9375 // A* -> B*
9376 if (RHSType->isObjCObjectPointerType()) {
9377 Kind = CK_BitCast;
9379 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9380 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9381 result == Compatible &&
9382 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9383 result = IncompatibleObjCWeakRef;
9384 return result;
9385 }
9386
9387 // int or null -> A*
9388 if (RHSType->isIntegerType()) {
9389 Kind = CK_IntegralToPointer; // FIXME: null
9390 return IntToPointer;
9391 }
9392
9393 // In general, C pointers are not compatible with ObjC object pointers,
9394 // with two exceptions:
9395 if (isa<PointerType>(RHSType)) {
9396 Kind = CK_CPointerToObjCPointerCast;
9397
9398 // - conversions from 'void*'
9399 if (RHSType->isVoidPointerType()) {
9400 return Compatible;
9401 }
9402
9403 // - conversions to 'Class' from its redefinition type
9404 if (LHSType->isObjCClassType() &&
9405 Context.hasSameType(RHSType,
9407 return Compatible;
9408 }
9409
9410 return IncompatiblePointer;
9411 }
9412
9413 // Only under strict condition T^ is compatible with an Objective-C pointer.
9414 if (RHSType->isBlockPointerType() &&
9416 if (ConvertRHS)
9418 Kind = CK_BlockPointerToObjCPointerCast;
9419 return Compatible;
9420 }
9421
9422 return Incompatible;
9423 }
9424
9425 // Conversion to nullptr_t (C23 only)
9426 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9429 // null -> nullptr_t
9430 Kind = CK_NullToPointer;
9431 return Compatible;
9432 }
9433
9434 // Conversions from pointers that are not covered by the above.
9435 if (isa<PointerType>(RHSType)) {
9436 // T* -> _Bool
9437 if (LHSType == Context.BoolTy) {
9438 Kind = CK_PointerToBoolean;
9439 return Compatible;
9440 }
9441
9442 // T* -> int
9443 if (LHSType->isIntegerType()) {
9444 Kind = CK_PointerToIntegral;
9445 return PointerToInt;
9446 }
9447
9448 return Incompatible;
9449 }
9450
9451 // Conversions from Objective-C pointers that are not covered by the above.
9452 if (isa<ObjCObjectPointerType>(RHSType)) {
9453 // T* -> _Bool
9454 if (LHSType == Context.BoolTy) {
9455 Kind = CK_PointerToBoolean;
9456 return Compatible;
9457 }
9458
9459 // T* -> int
9460 if (LHSType->isIntegerType()) {
9461 Kind = CK_PointerToIntegral;
9462 return PointerToInt;
9463 }
9464
9465 return Incompatible;
9466 }
9467
9468 // struct A -> struct B
9469 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9470 if (Context.typesAreCompatible(LHSType, RHSType)) {
9471 Kind = CK_NoOp;
9472 return Compatible;
9473 }
9474 }
9475
9476 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9477 Kind = CK_IntToOCLSampler;
9478 return Compatible;
9479 }
9480
9481 return Incompatible;
9482}
9483
9484/// Constructs a transparent union from an expression that is
9485/// used to initialize the transparent union.
9487 ExprResult &EResult, QualType UnionType,
9488 FieldDecl *Field) {
9489 // Build an initializer list that designates the appropriate member
9490 // of the transparent union.
9491 Expr *E = EResult.get();
9493 E, SourceLocation());
9494 Initializer->setType(UnionType);
9495 Initializer->setInitializedFieldInUnion(Field);
9496
9497 // Build a compound literal constructing a value of the transparent
9498 // union type from this initializer list.
9499 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9500 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9501 VK_PRValue, Initializer, false);
9502}
9503
9506 ExprResult &RHS) {
9507 QualType RHSType = RHS.get()->getType();
9508
9509 // If the ArgType is a Union type, we want to handle a potential
9510 // transparent_union GCC extension.
9511 const RecordType *UT = ArgType->getAsUnionType();
9512 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9513 return Incompatible;
9514
9515 // The field to initialize within the transparent union.
9516 RecordDecl *UD = UT->getDecl();
9517 FieldDecl *InitField = nullptr;
9518 // It's compatible if the expression matches any of the fields.
9519 for (auto *it : UD->fields()) {
9520 if (it->getType()->isPointerType()) {
9521 // If the transparent union contains a pointer type, we allow:
9522 // 1) void pointer
9523 // 2) null pointer constant
9524 if (RHSType->isPointerType())
9525 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9526 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9527 InitField = it;
9528 break;
9529 }
9530
9533 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9534 CK_NullToPointer);
9535 InitField = it;
9536 break;
9537 }
9538 }
9539
9540 CastKind Kind;
9541 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9542 == Compatible) {
9543 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9544 InitField = it;
9545 break;
9546 }
9547 }
9548
9549 if (!InitField)
9550 return Incompatible;
9551
9552 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9553 return Compatible;
9554}
9555
9558 bool Diagnose,
9559 bool DiagnoseCFAudited,
9560 bool ConvertRHS) {
9561 // We need to be able to tell the caller whether we diagnosed a problem, if
9562 // they ask us to issue diagnostics.
9563 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9564
9565 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9566 // we can't avoid *all* modifications at the moment, so we need some somewhere
9567 // to put the updated value.
9568 ExprResult LocalRHS = CallerRHS;
9569 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9570
9571 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9572 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9573 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9574 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9575 Diag(RHS.get()->getExprLoc(),
9576 diag::warn_noderef_to_dereferenceable_pointer)
9577 << RHS.get()->getSourceRange();
9578 }
9579 }
9580 }
9581
9582 if (getLangOpts().CPlusPlus) {
9583 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9584 // C++ 5.17p3: If the left operand is not of class type, the
9585 // expression is implicitly converted (C++ 4) to the
9586 // cv-unqualified type of the left operand.
9587 QualType RHSType = RHS.get()->getType();
9588 if (Diagnose) {
9589 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9590 AA_Assigning);
9591 } else {
9594 /*SuppressUserConversions=*/false,
9595 AllowedExplicit::None,
9596 /*InOverloadResolution=*/false,
9597 /*CStyle=*/false,
9598 /*AllowObjCWritebackConversion=*/false);
9599 if (ICS.isFailure())
9600 return Incompatible;
9601 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9602 ICS, AA_Assigning);
9603 }
9604 if (RHS.isInvalid())
9605 return Incompatible;
9607 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9608 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9609 result = IncompatibleObjCWeakRef;
9610 return result;
9611 }
9612
9613 // FIXME: Currently, we fall through and treat C++ classes like C
9614 // structures.
9615 // FIXME: We also fall through for atomics; not sure what should
9616 // happen there, though.
9617 } else if (RHS.get()->getType() == Context.OverloadTy) {
9618 // As a set of extensions to C, we support overloading on functions. These
9619 // functions need to be resolved here.
9620 DeclAccessPair DAP;
9622 RHS.get(), LHSType, /*Complain=*/false, DAP))
9623 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9624 else
9625 return Incompatible;
9626 }
9627
9628 // This check seems unnatural, however it is necessary to ensure the proper
9629 // conversion of functions/arrays. If the conversion were done for all
9630 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9631 // expressions that suppress this implicit conversion (&, sizeof). This needs
9632 // to happen before we check for null pointer conversions because C does not
9633 // undergo the same implicit conversions as C++ does above (by the calls to
9634 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
9635 // lvalue to rvalue cast before checking for null pointer constraints. This
9636 // addresses code like: nullptr_t val; int *ptr; ptr = val;
9637 //
9638 // Suppress this for references: C++ 8.5.3p5.
9639 if (!LHSType->isReferenceType()) {
9640 // FIXME: We potentially allocate here even if ConvertRHS is false.
9642 if (RHS.isInvalid())
9643 return Incompatible;
9644 }
9645
9646 // The constraints are expressed in terms of the atomic, qualified, or
9647 // unqualified type of the LHS.
9648 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
9649
9650 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9651 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
9652 if ((LHSTypeAfterConversion->isPointerType() ||
9653 LHSTypeAfterConversion->isObjCObjectPointerType() ||
9654 LHSTypeAfterConversion->isBlockPointerType()) &&
9655 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
9658 if (Diagnose || ConvertRHS) {
9659 CastKind Kind;
9661 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9662 /*IgnoreBaseAccess=*/false, Diagnose);
9663 if (ConvertRHS)
9664 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9665 }
9666 return Compatible;
9667 }
9668 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
9669 // unqualified bool, and the right operand is a pointer or its type is
9670 // nullptr_t.
9671 if (getLangOpts().C23 && LHSType->isBooleanType() &&
9672 RHS.get()->getType()->isNullPtrType()) {
9673 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
9674 // only handles nullptr -> _Bool due to needing an extra conversion
9675 // step.
9676 // We model this by converting from nullptr -> void * and then let the
9677 // conversion from void * -> _Bool happen naturally.
9678 if (Diagnose || ConvertRHS) {
9679 CastKind Kind;
9682 /*IgnoreBaseAccess=*/false, Diagnose);
9683 if (ConvertRHS)
9684 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
9685 &Path);
9686 }
9687 }
9688
9689 // OpenCL queue_t type assignment.
9690 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9692 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9693 return Compatible;
9694 }
9695
9696 CastKind Kind;
9698 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9699
9700 // C99 6.5.16.1p2: The value of the right operand is converted to the
9701 // type of the assignment expression.
9702 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9703 // so that we can use references in built-in functions even in C.
9704 // The getNonReferenceType() call makes sure that the resulting expression
9705 // does not have reference type.
9706 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9708 Expr *E = RHS.get();
9709
9710 // Check for various Objective-C errors. If we are not reporting
9711 // diagnostics and just checking for errors, e.g., during overload
9712 // resolution, return Incompatible to indicate the failure.
9713 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9714 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
9716 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
9717 if (!Diagnose)
9718 return Incompatible;
9719 }
9720 if (getLangOpts().ObjC &&
9721 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9722 E->getType(), E, Diagnose) ||
9723 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9724 if (!Diagnose)
9725 return Incompatible;
9726 // Replace the expression with a corrected version and continue so we
9727 // can find further errors.
9728 RHS = E;
9729 return Compatible;
9730 }
9731
9732 if (ConvertRHS)
9733 RHS = ImpCastExprToType(E, Ty, Kind);
9734 }
9735
9736 return result;
9737}
9738
9739namespace {
9740/// The original operand to an operator, prior to the application of the usual
9741/// arithmetic conversions and converting the arguments of a builtin operator
9742/// candidate.
9743struct OriginalOperand {
9744 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9745 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9746 Op = MTE->getSubExpr();
9747 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9748 Op = BTE->getSubExpr();
9749 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9750 Orig = ICE->getSubExprAsWritten();
9751 Conversion = ICE->getConversionFunction();
9752 }
9753 }
9754
9755 QualType getType() const { return Orig->getType(); }
9756
9757 Expr *Orig;
9758 NamedDecl *Conversion;
9759};
9760}
9761
9763 ExprResult &RHS) {
9764 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9765
9766 Diag(Loc, diag::err_typecheck_invalid_operands)
9767 << OrigLHS.getType() << OrigRHS.getType()
9768 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9769
9770 // If a user-defined conversion was applied to either of the operands prior
9771 // to applying the built-in operator rules, tell the user about it.
9772 if (OrigLHS.Conversion) {
9773 Diag(OrigLHS.Conversion->getLocation(),
9774 diag::note_typecheck_invalid_operands_converted)
9775 << 0 << LHS.get()->getType();
9776 }
9777 if (OrigRHS.Conversion) {
9778 Diag(OrigRHS.Conversion->getLocation(),
9779 diag::note_typecheck_invalid_operands_converted)
9780 << 1 << RHS.get()->getType();
9781 }
9782
9783 return QualType();
9784}
9785
9787 ExprResult &RHS) {
9788 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9789 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9790
9791 bool LHSNatVec = LHSType->isVectorType();
9792 bool RHSNatVec = RHSType->isVectorType();
9793
9794 if (!(LHSNatVec && RHSNatVec)) {
9795 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9796 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9797 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9798 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9799 << Vector->getSourceRange();
9800 return QualType();
9801 }
9802
9803 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9804 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9805 << RHS.get()->getSourceRange();
9806
9807 return QualType();
9808}
9809
9810/// Try to convert a value of non-vector type to a vector type by converting
9811/// the type to the element type of the vector and then performing a splat.
9812/// If the language is OpenCL, we only use conversions that promote scalar
9813/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9814/// for float->int.
9815///
9816/// OpenCL V2.0 6.2.6.p2:
9817/// An error shall occur if any scalar operand type has greater rank
9818/// than the type of the vector element.
9819///
9820/// \param scalar - if non-null, actually perform the conversions
9821/// \return true if the operation fails (but without diagnosing the failure)
9823 QualType scalarTy,
9824 QualType vectorEltTy,
9825 QualType vectorTy,
9826 unsigned &DiagID) {
9827 // The conversion to apply to the scalar before splatting it,
9828 // if necessary.
9829 CastKind scalarCast = CK_NoOp;
9830
9831 if (vectorEltTy->isIntegralType(S.Context)) {
9832 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9833 (scalarTy->isIntegerType() &&
9834 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9835 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9836 return true;
9837 }
9838 if (!scalarTy->isIntegralType(S.Context))
9839 return true;
9840 scalarCast = CK_IntegralCast;
9841 } else if (vectorEltTy->isRealFloatingType()) {
9842 if (scalarTy->isRealFloatingType()) {
9843 if (S.getLangOpts().OpenCL &&
9844 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9845 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9846 return true;
9847 }
9848 scalarCast = CK_FloatingCast;
9849 }
9850 else if (scalarTy->isIntegralType(S.Context))
9851 scalarCast = CK_IntegralToFloating;
9852 else
9853 return true;
9854 } else {
9855 return true;
9856 }
9857
9858 // Adjust scalar if desired.
9859 if (scalar) {
9860 if (scalarCast != CK_NoOp)
9861 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9862 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9863 }
9864 return false;
9865}
9866
9867/// Convert vector E to a vector with the same number of elements but different
9868/// element type.
9869static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9870 const auto *VecTy = E->getType()->getAs<VectorType>();
9871 assert(VecTy && "Expression E must be a vector");
9872 QualType NewVecTy =
9873 VecTy->isExtVectorType()
9874 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
9875 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
9876 VecTy->getVectorKind());
9877
9878 // Look through the implicit cast. Return the subexpression if its type is
9879 // NewVecTy.
9880 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9881 if (ICE->getSubExpr()->getType() == NewVecTy)
9882 return ICE->getSubExpr();
9883
9884 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9885 return S.ImpCastExprToType(E, NewVecTy, Cast);
9886}
9887
9888/// Test if a (constant) integer Int can be casted to another integer type
9889/// IntTy without losing precision.
9891 QualType OtherIntTy) {
9892 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9893
9894 // Reject cases where the value of the Int is unknown as that would
9895 // possibly cause truncation, but accept cases where the scalar can be
9896 // demoted without loss of precision.
9897 Expr::EvalResult EVResult;
9898 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9899 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9900 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9901 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9902
9903 if (CstInt) {
9904 // If the scalar is constant and is of a higher order and has more active
9905 // bits that the vector element type, reject it.
9906 llvm::APSInt Result = EVResult.Val.getInt();
9907 unsigned NumBits = IntSigned
9908 ? (Result.isNegative() ? Result.getSignificantBits()
9909 : Result.getActiveBits())
9910 : Result.getActiveBits();
9911 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9912 return true;
9913
9914 // If the signedness of the scalar type and the vector element type
9915 // differs and the number of bits is greater than that of the vector
9916 // element reject it.
9917 return (IntSigned != OtherIntSigned &&
9918 NumBits > S.Context.getIntWidth(OtherIntTy));
9919 }
9920
9921 // Reject cases where the value of the scalar is not constant and it's
9922 // order is greater than that of the vector element type.
9923 return (Order < 0);
9924}
9925
9926/// Test if a (constant) integer Int can be casted to floating point type
9927/// FloatTy without losing precision.
9929 QualType FloatTy) {
9930 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9931
9932 // Determine if the integer constant can be expressed as a floating point
9933 // number of the appropriate type.
9934 Expr::EvalResult EVResult;
9935 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9936
9937 uint64_t Bits = 0;
9938 if (CstInt) {
9939 // Reject constants that would be truncated if they were converted to
9940 // the floating point type. Test by simple to/from conversion.
9941 // FIXME: Ideally the conversion to an APFloat and from an APFloat
9942 // could be avoided if there was a convertFromAPInt method
9943 // which could signal back if implicit truncation occurred.
9944 llvm::APSInt Result = EVResult.Val.getInt();
9945 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9946 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9947 llvm::APFloat::rmTowardZero);
9948 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9950 bool Ignored = false;
9951 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9952 &Ignored);
9953 if (Result != ConvertBack)
9954 return true;
9955 } else {
9956 // Reject types that cannot be fully encoded into the mantissa of
9957 // the float.
9958 Bits = S.Context.getTypeSize(IntTy);
9959 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9960 S.Context.getFloatTypeSemantics(FloatTy));
9961 if (Bits > FloatPrec)
9962 return true;
9963 }
9964
9965 return false;
9966}
9967
9968/// Attempt to convert and splat Scalar into a vector whose types matches
9969/// Vector following GCC conversion rules. The rule is that implicit
9970/// conversion can occur when Scalar can be casted to match Vector's element
9971/// type without causing truncation of Scalar.
9973 ExprResult *Vector) {
9974 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9975 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9976 QualType VectorEltTy;
9977
9978 if (const auto *VT = VectorTy->getAs<VectorType>()) {
9979 assert(!isa<ExtVectorType>(VT) &&
9980 "ExtVectorTypes should not be handled here!");
9981 VectorEltTy = VT->getElementType();
9982 } else if (VectorTy->isSveVLSBuiltinType()) {
9983 VectorEltTy =
9984 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
9985 } else {
9986 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
9987 }
9988
9989 // Reject cases where the vector element type or the scalar element type are
9990 // not integral or floating point types.
9991 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9992 return true;
9993
9994 // The conversion to apply to the scalar before splatting it,
9995 // if necessary.
9996 CastKind ScalarCast = CK_NoOp;
9997
9998 // Accept cases where the vector elements are integers and the scalar is
9999 // an integer.
10000 // FIXME: Notionally if the scalar was a floating point value with a precise
10001 // integral representation, we could cast it to an appropriate integer
10002 // type and then perform the rest of the checks here. GCC will perform
10003 // this conversion in some cases as determined by the input language.
10004 // We should accept it on a language independent basis.
10005 if (VectorEltTy->isIntegralType(S.Context) &&
10006 ScalarTy->isIntegralType(S.Context) &&
10007 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10008
10009 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10010 return true;
10011
10012 ScalarCast = CK_IntegralCast;
10013 } else if (VectorEltTy->isIntegralType(S.Context) &&
10014 ScalarTy->isRealFloatingType()) {
10015 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10016 ScalarCast = CK_FloatingToIntegral;
10017 else
10018 return true;
10019 } else if (VectorEltTy->isRealFloatingType()) {
10020 if (ScalarTy->isRealFloatingType()) {
10021
10022 // Reject cases where the scalar type is not a constant and has a higher
10023 // Order than the vector element type.
10024 llvm::APFloat Result(0.0);
10025
10026 // Determine whether this is a constant scalar. In the event that the
10027 // value is dependent (and thus cannot be evaluated by the constant
10028 // evaluator), skip the evaluation. This will then diagnose once the
10029 // expression is instantiated.
10030 bool CstScalar = Scalar->get()->isValueDependent() ||
10031 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10032 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10033 if (!CstScalar && Order < 0)
10034 return true;
10035
10036 // If the scalar cannot be safely casted to the vector element type,
10037 // reject it.
10038 if (CstScalar) {
10039 bool Truncated = false;
10040 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10041 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10042 if (Truncated)
10043 return true;
10044 }
10045
10046 ScalarCast = CK_FloatingCast;
10047 } else if (ScalarTy->isIntegralType(S.Context)) {
10048 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10049 return true;
10050
10051 ScalarCast = CK_IntegralToFloating;
10052 } else
10053 return true;
10054 } else if (ScalarTy->isEnumeralType())
10055 return true;
10056
10057 // Adjust scalar if desired.
10058 if (ScalarCast != CK_NoOp)
10059 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10060 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10061 return false;
10062}
10063
10065 SourceLocation Loc, bool IsCompAssign,
10066 bool AllowBothBool,
10067 bool AllowBoolConversions,
10068 bool AllowBoolOperation,
10069 bool ReportInvalid) {
10070 if (!IsCompAssign) {
10072 if (LHS.isInvalid())
10073 return QualType();
10074 }
10076 if (RHS.isInvalid())
10077 return QualType();
10078
10079 // For conversion purposes, we ignore any qualifiers.
10080 // For example, "const float" and "float" are equivalent.
10081 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10082 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10083
10084 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10085 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10086 assert(LHSVecType || RHSVecType);
10087
10088 // AltiVec-style "vector bool op vector bool" combinations are allowed
10089 // for some operators but not others.
10090 if (!AllowBothBool && LHSVecType &&
10091 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10092 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10093 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10094
10095 // This operation may not be performed on boolean vectors.
10096 if (!AllowBoolOperation &&
10097 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10098 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10099
10100 // If the vector types are identical, return.
10101 if (Context.hasSameType(LHSType, RHSType))
10102 return Context.getCommonSugaredType(LHSType, RHSType);
10103
10104 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10105 if (LHSVecType && RHSVecType &&
10106 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10107 if (isa<ExtVectorType>(LHSVecType)) {
10108 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10109 return LHSType;
10110 }
10111
10112 if (!IsCompAssign)
10113 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10114 return RHSType;
10115 }
10116
10117 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10118 // can be mixed, with the result being the non-bool type. The non-bool
10119 // operand must have integer element type.
10120 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10121 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10122 (Context.getTypeSize(LHSVecType->getElementType()) ==
10123 Context.getTypeSize(RHSVecType->getElementType()))) {
10124 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10125 LHSVecType->getElementType()->isIntegerType() &&
10126 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10127 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10128 return LHSType;
10129 }
10130 if (!IsCompAssign &&
10131 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10132 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10133 RHSVecType->getElementType()->isIntegerType()) {
10134 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10135 return RHSType;
10136 }
10137 }
10138
10139 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10140 // invalid since the ambiguity can affect the ABI.
10141 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10142 unsigned &SVEorRVV) {
10143 const VectorType *VecType = SecondType->getAs<VectorType>();
10144 SVEorRVV = 0;
10145 if (FirstType->isSizelessBuiltinType() && VecType) {
10148 return true;
10154 SVEorRVV = 1;
10155 return true;
10156 }
10157 }
10158
10159 return false;
10160 };
10161
10162 unsigned SVEorRVV;
10163 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10164 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10165 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10166 << SVEorRVV << LHSType << RHSType;
10167 return QualType();
10168 }
10169
10170 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10171 // invalid since the ambiguity can affect the ABI.
10172 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10173 unsigned &SVEorRVV) {
10174 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10175 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10176
10177 SVEorRVV = 0;
10178 if (FirstVecType && SecondVecType) {
10179 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10180 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10181 SecondVecType->getVectorKind() ==
10183 return true;
10184 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10185 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10186 SecondVecType->getVectorKind() ==
10188 SecondVecType->getVectorKind() ==
10190 SecondVecType->getVectorKind() ==
10192 SVEorRVV = 1;
10193 return true;
10194 }
10195 }
10196 return false;
10197 }
10198
10199 if (SecondVecType &&
10200 SecondVecType->getVectorKind() == VectorKind::Generic) {
10201 if (FirstType->isSVESizelessBuiltinType())
10202 return true;
10203 if (FirstType->isRVVSizelessBuiltinType()) {
10204 SVEorRVV = 1;
10205 return true;
10206 }
10207 }
10208
10209 return false;
10210 };
10211
10212 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10213 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10214 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10215 << SVEorRVV << LHSType << RHSType;
10216 return QualType();
10217 }
10218
10219 // If there's a vector type and a scalar, try to convert the scalar to
10220 // the vector element type and splat.
10221 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10222 if (!RHSVecType) {
10223 if (isa<ExtVectorType>(LHSVecType)) {
10224 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10225 LHSVecType->getElementType(), LHSType,
10226 DiagID))
10227 return LHSType;
10228 } else {
10229 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10230 return LHSType;
10231 }
10232 }
10233 if (!LHSVecType) {
10234 if (isa<ExtVectorType>(RHSVecType)) {
10235 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10236 LHSType, RHSVecType->getElementType(),
10237 RHSType, DiagID))
10238 return RHSType;
10239 } else {
10240 if (LHS.get()->isLValue() ||
10241 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10242 return RHSType;
10243 }
10244 }
10245
10246 // FIXME: The code below also handles conversion between vectors and
10247 // non-scalars, we should break this down into fine grained specific checks
10248 // and emit proper diagnostics.
10249 QualType VecType = LHSVecType ? LHSType : RHSType;
10250 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10251 QualType OtherType = LHSVecType ? RHSType : LHSType;
10252 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10253 if (isLaxVectorConversion(OtherType, VecType)) {
10254 if (Context.getTargetInfo().getTriple().isPPC() &&
10255 anyAltivecTypes(RHSType, LHSType) &&
10256 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10257 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10258 // If we're allowing lax vector conversions, only the total (data) size
10259 // needs to be the same. For non compound assignment, if one of the types is
10260 // scalar, the result is always the vector type.
10261 if (!IsCompAssign) {
10262 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10263 return VecType;
10264 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10265 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10266 // type. Note that this is already done by non-compound assignments in
10267 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10268 // <1 x T> -> T. The result is also a vector type.
10269 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10270 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10271 ExprResult *RHSExpr = &RHS;
10272 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10273 return VecType;
10274 }
10275 }
10276
10277 // Okay, the expression is invalid.
10278
10279 // If there's a non-vector, non-real operand, diagnose that.
10280 if ((!RHSVecType && !RHSType->isRealType()) ||
10281 (!LHSVecType && !LHSType->isRealType())) {
10282 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10283 << LHSType << RHSType
10284 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10285 return QualType();
10286 }
10287
10288 // OpenCL V1.1 6.2.6.p1:
10289 // If the operands are of more than one vector type, then an error shall
10290 // occur. Implicit conversions between vector types are not permitted, per
10291 // section 6.2.1.
10292 if (getLangOpts().OpenCL &&
10293 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10294 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10295 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10296 << RHSType;
10297 return QualType();
10298 }
10299
10300
10301 // If there is a vector type that is not a ExtVector and a scalar, we reach
10302 // this point if scalar could not be converted to the vector's element type
10303 // without truncation.
10304 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10305 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10306 QualType Scalar = LHSVecType ? RHSType : LHSType;
10307 QualType Vector = LHSVecType ? LHSType : RHSType;
10308 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10309 Diag(Loc,
10310 diag::err_typecheck_vector_not_convertable_implict_truncation)
10311 << ScalarOrVector << Scalar << Vector;
10312
10313 return QualType();
10314 }
10315
10316 // Otherwise, use the generic diagnostic.
10317 Diag(Loc, DiagID)
10318 << LHSType << RHSType
10319 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10320 return QualType();
10321}
10322
10325 bool IsCompAssign,
10326 ArithConvKind OperationKind) {
10327 if (!IsCompAssign) {
10329 if (LHS.isInvalid())
10330 return QualType();
10331 }
10333 if (RHS.isInvalid())
10334 return QualType();
10335
10336 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10337 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10338
10339 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10340 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10341
10342 unsigned DiagID = diag::err_typecheck_invalid_operands;
10343 if ((OperationKind == ACK_Arithmetic) &&
10344 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10345 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10346 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10347 << RHS.get()->getSourceRange();
10348 return QualType();
10349 }
10350
10351 if (Context.hasSameType(LHSType, RHSType))
10352 return LHSType;
10353
10354 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10355 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10356 return LHSType;
10357 }
10358 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10359 if (LHS.get()->isLValue() ||
10360 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10361 return RHSType;
10362 }
10363
10364 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10365 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10366 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10367 << LHSType << RHSType << LHS.get()->getSourceRange()
10368 << RHS.get()->getSourceRange();
10369 return QualType();
10370 }
10371
10372 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10373 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10374 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10375 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10376 << LHSType << RHSType << LHS.get()->getSourceRange()
10377 << RHS.get()->getSourceRange();
10378 return QualType();
10379 }
10380
10381 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10382 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10383 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10384 bool ScalarOrVector =
10385 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10386
10387 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10388 << ScalarOrVector << Scalar << Vector;
10389
10390 return QualType();
10391 }
10392
10393 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10394 << RHS.get()->getSourceRange();
10395 return QualType();
10396}
10397
10398// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10399// expression. These are mainly cases where the null pointer is used as an
10400// integer instead of a pointer.
10402 SourceLocation Loc, bool IsCompare) {
10403 // The canonical way to check for a GNU null is with isNullPointerConstant,
10404 // but we use a bit of a hack here for speed; this is a relatively
10405 // hot path, and isNullPointerConstant is slow.
10406 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10407 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10408
10409 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10410
10411 // Avoid analyzing cases where the result will either be invalid (and
10412 // diagnosed as such) or entirely valid and not something to warn about.
10413 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10414 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10415 return;
10416
10417 // Comparison operations would not make sense with a null pointer no matter
10418 // what the other expression is.
10419 if (!IsCompare) {
10420 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10421 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10422 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10423 return;
10424 }
10425
10426 // The rest of the operations only make sense with a null pointer
10427 // if the other expression is a pointer.
10428 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10429 NonNullType->canDecayToPointerType())
10430 return;
10431
10432 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10433 << LHSNull /* LHS is NULL */ << NonNullType
10434 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10435}
10436
10439 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10440 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10441 if (!LUE || !RUE)
10442 return;
10443 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10444 RUE->getKind() != UETT_SizeOf)
10445 return;
10446
10447 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10448 QualType LHSTy = LHSArg->getType();
10449 QualType RHSTy;
10450
10451 if (RUE->isArgumentType())
10452 RHSTy = RUE->getArgumentType().getNonReferenceType();
10453 else
10454 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10455
10456 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10457 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10458 return;
10459
10460 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10461 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10462 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10463 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10464 << LHSArgDecl;
10465 }
10466 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10467 QualType ArrayElemTy = ArrayTy->getElementType();
10468 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10469 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10470 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10471 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10472 return;
10473 S.Diag(Loc, diag::warn_division_sizeof_array)
10474 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10475 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10476 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10477 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10478 << LHSArgDecl;
10479 }
10480
10481 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10482 }
10483}
10484
10486 ExprResult &RHS,
10487 SourceLocation Loc, bool IsDiv) {
10488 // Check for division/remainder by zero.
10489 Expr::EvalResult RHSValue;
10490 if (!RHS.get()->isValueDependent() &&
10491 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10492 RHSValue.Val.getInt() == 0)
10493 S.DiagRuntimeBehavior(Loc, RHS.get(),
10494 S.PDiag(diag::warn_remainder_division_by_zero)
10495 << IsDiv << RHS.get()->getSourceRange());
10496}
10497
10500 bool IsCompAssign, bool IsDiv) {
10501 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10502
10503 QualType LHSTy = LHS.get()->getType();
10504 QualType RHSTy = RHS.get()->getType();
10505 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10506 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10507 /*AllowBothBool*/ getLangOpts().AltiVec,
10508 /*AllowBoolConversions*/ false,
10509 /*AllowBooleanOperation*/ false,
10510 /*ReportInvalid*/ true);
10511 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10512 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10514 if (!IsDiv &&
10515 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10516 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10517 // For division, only matrix-by-scalar is supported. Other combinations with
10518 // matrix types are invalid.
10519 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10520 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10521
10523 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10524 if (LHS.isInvalid() || RHS.isInvalid())
10525 return QualType();
10526
10527
10528 if (compType.isNull() || !compType->isArithmeticType())
10529 return InvalidOperands(Loc, LHS, RHS);
10530 if (IsDiv) {
10531 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10532 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10533 }
10534 return compType;
10535}
10536
10538 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10539 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10540
10541 if (LHS.get()->getType()->isVectorType() ||
10542 RHS.get()->getType()->isVectorType()) {
10543 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10545 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10546 /*AllowBothBool*/ getLangOpts().AltiVec,
10547 /*AllowBoolConversions*/ false,
10548 /*AllowBooleanOperation*/ false,
10549 /*ReportInvalid*/ true);
10550 return InvalidOperands(Loc, LHS, RHS);
10551 }
10552
10553 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10554 RHS.get()->getType()->isSveVLSBuiltinType()) {
10555 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10557 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10559
10560 return InvalidOperands(Loc, LHS, RHS);
10561 }
10562
10564 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10565 if (LHS.isInvalid() || RHS.isInvalid())
10566 return QualType();
10567
10568 if (compType.isNull() || !compType->isIntegerType())
10569 return InvalidOperands(Loc, LHS, RHS);
10570 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10571 return compType;
10572}
10573
10574/// Diagnose invalid arithmetic on two void pointers.
10576 Expr *LHSExpr, Expr *RHSExpr) {
10577 S.Diag(Loc, S.getLangOpts().CPlusPlus
10578 ? diag::err_typecheck_pointer_arith_void_type
10579 : diag::ext_gnu_void_ptr)
10580 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10581 << RHSExpr->getSourceRange();
10582}
10583
10584/// Diagnose invalid arithmetic on a void pointer.
10586 Expr *Pointer) {
10587 S.Diag(Loc, S.getLangOpts().CPlusPlus
10588 ? diag::err_typecheck_pointer_arith_void_type
10589 : diag::ext_gnu_void_ptr)
10590 << 0 /* one pointer */ << Pointer->getSourceRange();
10591}
10592
10593/// Diagnose invalid arithmetic on a null pointer.
10594///
10595/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10596/// idiom, which we recognize as a GNU extension.
10597///
10599 Expr *Pointer, bool IsGNUIdiom) {
10600 if (IsGNUIdiom)
10601 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10602 << Pointer->getSourceRange();
10603 else
10604 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10605 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10606}
10607
10608/// Diagnose invalid subraction on a null pointer.
10609///
10611 Expr *Pointer, bool BothNull) {
10612 // Null - null is valid in C++ [expr.add]p7
10613 if (BothNull && S.getLangOpts().CPlusPlus)
10614 return;
10615
10616 // Is this s a macro from a system header?
10618 return;
10619
10621 S.PDiag(diag::warn_pointer_sub_null_ptr)
10622 << S.getLangOpts().CPlusPlus
10623 << Pointer->getSourceRange());
10624}
10625
10626/// Diagnose invalid arithmetic on two function pointers.
10628 Expr *LHS, Expr *RHS) {
10629 assert(LHS->getType()->isAnyPointerType());
10630 assert(RHS->getType()->isAnyPointerType());
10631 S.Diag(Loc, S.getLangOpts().CPlusPlus
10632 ? diag::err_typecheck_pointer_arith_function_type
10633 : diag::ext_gnu_ptr_func_arith)
10634 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10635 // We only show the second type if it differs from the first.
10637 RHS->getType())
10638 << RHS->getType()->getPointeeType()
10639 << LHS->getSourceRange() << RHS->getSourceRange();
10640}
10641
10642/// Diagnose invalid arithmetic on a function pointer.
10644 Expr *Pointer) {
10645 assert(Pointer->getType()->isAnyPointerType());
10646 S.Diag(Loc, S.getLangOpts().CPlusPlus
10647 ? diag::err_typecheck_pointer_arith_function_type
10648 : diag::ext_gnu_ptr_func_arith)
10649 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10650 << 0 /* one pointer, so only one type */
10651 << Pointer->getSourceRange();
10652}
10653
10654/// Emit error if Operand is incomplete pointer type
10655///
10656/// \returns True if pointer has incomplete type
10658 Expr *Operand) {
10659 QualType ResType = Operand->getType();
10660 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10661 ResType = ResAtomicType->getValueType();
10662
10663 assert(ResType->isAnyPointerType());
10664 QualType PointeeTy = ResType->getPointeeType();
10665 return S.RequireCompleteSizedType(
10666 Loc, PointeeTy,
10667 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10668 Operand->getSourceRange());
10669}
10670
10671/// Check the validity of an arithmetic pointer operand.
10672///
10673/// If the operand has pointer type, this code will check for pointer types
10674/// which are invalid in arithmetic operations. These will be diagnosed
10675/// appropriately, including whether or not the use is supported as an
10676/// extension.
10677///
10678/// \returns True when the operand is valid to use (even if as an extension).
10680 Expr *Operand) {
10681 QualType ResType = Operand->getType();
10682 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10683 ResType = ResAtomicType->getValueType();
10684
10685 if (!ResType->isAnyPointerType()) return true;
10686
10687 QualType PointeeTy = ResType->getPointeeType();
10688 if (PointeeTy->isVoidType()) {
10690 return !S.getLangOpts().CPlusPlus;
10691 }
10692 if (PointeeTy->isFunctionType()) {
10694 return !S.getLangOpts().CPlusPlus;
10695 }
10696
10697 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10698
10699 return true;
10700}
10701
10702/// Check the validity of a binary arithmetic operation w.r.t. pointer
10703/// operands.
10704///
10705/// This routine will diagnose any invalid arithmetic on pointer operands much
10706/// like \see checkArithmeticOpPointerOperand. However, it has special logic
10707/// for emitting a single diagnostic even for operations where both LHS and RHS
10708/// are (potentially problematic) pointers.
10709///
10710/// \returns True when the operand is valid to use (even if as an extension).
10712 Expr *LHSExpr, Expr *RHSExpr) {
10713 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10714 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10715 if (!isLHSPointer && !isRHSPointer) return true;
10716
10717 QualType LHSPointeeTy, RHSPointeeTy;
10718 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10719 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10720
10721 // if both are pointers check if operation is valid wrt address spaces
10722 if (isLHSPointer && isRHSPointer) {
10723 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10724 S.Diag(Loc,
10725 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10726 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10727 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10728 return false;
10729 }
10730 }
10731
10732 // Check for arithmetic on pointers to incomplete types.
10733 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10734 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10735 if (isLHSVoidPtr || isRHSVoidPtr) {
10736 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10737 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10738 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10739
10740 return !S.getLangOpts().CPlusPlus;
10741 }
10742
10743 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10744 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10745 if (isLHSFuncPtr || isRHSFuncPtr) {
10746 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10747 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10748 RHSExpr);
10749 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10750
10751 return !S.getLangOpts().CPlusPlus;
10752 }
10753
10754 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10755 return false;
10756 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10757 return false;
10758
10759 return true;
10760}
10761
10762/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10763/// literal.
10765 Expr *LHSExpr, Expr *RHSExpr) {
10766 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10767 Expr* IndexExpr = RHSExpr;
10768 if (!StrExpr) {
10769 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10770 IndexExpr = LHSExpr;
10771 }
10772
10773 bool IsStringPlusInt = StrExpr &&
10775 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10776 return;
10777
10778 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10779 Self.Diag(OpLoc, diag::warn_string_plus_int)
10780 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10781
10782 // Only print a fixit for "str" + int, not for int + "str".
10783 if (IndexExpr == RHSExpr) {
10784 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10785 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10786 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10788 << FixItHint::CreateInsertion(EndLoc, "]");
10789 } else
10790 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10791}
10792
10793/// Emit a warning when adding a char literal to a string.
10795 Expr *LHSExpr, Expr *RHSExpr) {
10796 const Expr *StringRefExpr = LHSExpr;
10797 const CharacterLiteral *CharExpr =
10798 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10799
10800 if (!CharExpr) {
10801 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10802 StringRefExpr = RHSExpr;
10803 }
10804
10805 if (!CharExpr || !StringRefExpr)
10806 return;
10807
10808 const QualType StringType = StringRefExpr->getType();
10809
10810 // Return if not a PointerType.
10811 if (!StringType->isAnyPointerType())
10812 return;
10813
10814 // Return if not a CharacterType.
10815 if (!StringType->getPointeeType()->isAnyCharacterType())
10816 return;
10817
10818 ASTContext &Ctx = Self.getASTContext();
10819 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10820
10821 const QualType CharType = CharExpr->getType();
10822 if (!CharType->isAnyCharacterType() &&
10823 CharType->isIntegerType() &&
10824 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10825 Self.Diag(OpLoc, diag::warn_string_plus_char)
10826 << DiagRange << Ctx.CharTy;
10827 } else {
10828 Self.Diag(OpLoc, diag::warn_string_plus_char)
10829 << DiagRange << CharExpr->getType();
10830 }
10831
10832 // Only print a fixit for str + char, not for char + str.
10833 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10834 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10835 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10836 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10838 << FixItHint::CreateInsertion(EndLoc, "]");
10839 } else {
10840 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10841 }
10842}
10843
10844/// Emit error when two pointers are incompatible.
10846 Expr *LHSExpr, Expr *RHSExpr) {
10847 assert(LHSExpr->getType()->isAnyPointerType());
10848 assert(RHSExpr->getType()->isAnyPointerType());
10849 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10850 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10851 << RHSExpr->getSourceRange();
10852}
10853
10854// C99 6.5.6
10857 QualType* CompLHSTy) {
10858 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10859
10860 if (LHS.get()->getType()->isVectorType() ||
10861 RHS.get()->getType()->isVectorType()) {
10862 QualType compType =
10863 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
10864 /*AllowBothBool*/ getLangOpts().AltiVec,
10865 /*AllowBoolConversions*/ getLangOpts().ZVector,
10866 /*AllowBooleanOperation*/ false,
10867 /*ReportInvalid*/ true);
10868 if (CompLHSTy) *CompLHSTy = compType;
10869 return compType;
10870 }
10871
10872 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10873 RHS.get()->getType()->isSveVLSBuiltinType()) {
10874 QualType compType =
10875 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
10876 if (CompLHSTy)
10877 *CompLHSTy = compType;
10878 return compType;
10879 }
10880
10881 if (LHS.get()->getType()->isConstantMatrixType() ||
10882 RHS.get()->getType()->isConstantMatrixType()) {
10883 QualType compType =
10884 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10885 if (CompLHSTy)
10886 *CompLHSTy = compType;
10887 return compType;
10888 }
10889
10891 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10892 if (LHS.isInvalid() || RHS.isInvalid())
10893 return QualType();
10894
10895 // Diagnose "string literal" '+' int and string '+' "char literal".
10896 if (Opc == BO_Add) {
10897 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10898 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10899 }
10900
10901 // handle the common case first (both operands are arithmetic).
10902 if (!compType.isNull() && compType->isArithmeticType()) {
10903 if (CompLHSTy) *CompLHSTy = compType;
10904 return compType;
10905 }
10906
10907 // Type-checking. Ultimately the pointer's going to be in PExp;
10908 // note that we bias towards the LHS being the pointer.
10909 Expr *PExp = LHS.get(), *IExp = RHS.get();
10910
10911 bool isObjCPointer;
10912 if (PExp->getType()->isPointerType()) {
10913 isObjCPointer = false;
10914 } else if (PExp->getType()->isObjCObjectPointerType()) {
10915 isObjCPointer = true;
10916 } else {
10917 std::swap(PExp, IExp);
10918 if (PExp->getType()->isPointerType()) {
10919 isObjCPointer = false;
10920 } else if (PExp->getType()->isObjCObjectPointerType()) {
10921 isObjCPointer = true;
10922 } else {
10923 return InvalidOperands(Loc, LHS, RHS);
10924 }
10925 }
10926 assert(PExp->getType()->isAnyPointerType());
10927
10928 if (!IExp->getType()->isIntegerType())
10929 return InvalidOperands(Loc, LHS, RHS);
10930
10931 // Adding to a null pointer results in undefined behavior.
10934 // In C++ adding zero to a null pointer is defined.
10935 Expr::EvalResult KnownVal;
10936 if (!getLangOpts().CPlusPlus ||
10937 (!IExp->isValueDependent() &&
10938 (!IExp->EvaluateAsInt(KnownVal, Context) ||
10939 KnownVal.Val.getInt() != 0))) {
10940 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10942 Context, BO_Add, PExp, IExp);
10943 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10944 }
10945 }
10946
10947 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10948 return QualType();
10949
10950 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10951 return QualType();
10952
10953 // Arithmetic on label addresses is normally allowed, except when we add
10954 // a ptrauth signature to the addresses.
10955 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
10956 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
10957 << /*addition*/ 1;
10958 return QualType();
10959 }
10960
10961 // Check array bounds for pointer arithemtic
10962 CheckArrayAccess(PExp, IExp);
10963
10964 if (CompLHSTy) {
10966 if (LHSTy.isNull()) {
10967 LHSTy = LHS.get()->getType();
10969 LHSTy = Context.getPromotedIntegerType(LHSTy);
10970 }
10971 *CompLHSTy = LHSTy;
10972 }
10973
10974 return PExp->getType();
10975}
10976
10977// C99 6.5.6
10980 QualType* CompLHSTy) {
10981 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10982
10983 if (LHS.get()->getType()->isVectorType() ||
10984 RHS.get()->getType()->isVectorType()) {
10985 QualType compType =
10986 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
10987 /*AllowBothBool*/ getLangOpts().AltiVec,
10988 /*AllowBoolConversions*/ getLangOpts().ZVector,
10989 /*AllowBooleanOperation*/ false,
10990 /*ReportInvalid*/ true);
10991 if (CompLHSTy) *CompLHSTy = compType;
10992 return compType;
10993 }
10994
10995 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10996 RHS.get()->getType()->isSveVLSBuiltinType()) {
10997 QualType compType =
10998 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
10999 if (CompLHSTy)
11000 *CompLHSTy = compType;
11001 return compType;
11002 }
11003
11004 if (LHS.get()->getType()->isConstantMatrixType() ||
11005 RHS.get()->getType()->isConstantMatrixType()) {
11006 QualType compType =
11007 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11008 if (CompLHSTy)
11009 *CompLHSTy = compType;
11010 return compType;
11011 }
11012
11014 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11015 if (LHS.isInvalid() || RHS.isInvalid())
11016 return QualType();
11017
11018 // Enforce type constraints: C99 6.5.6p3.
11019
11020 // Handle the common case first (both operands are arithmetic).
11021 if (!compType.isNull() && compType->isArithmeticType()) {
11022 if (CompLHSTy) *CompLHSTy = compType;
11023 return compType;
11024 }
11025
11026 // Either ptr - int or ptr - ptr.
11027 if (LHS.get()->getType()->isAnyPointerType()) {
11028 QualType lpointee = LHS.get()->getType()->getPointeeType();
11029
11030 // Diagnose bad cases where we step over interface counts.
11031 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11032 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11033 return QualType();
11034
11035 // Arithmetic on label addresses is normally allowed, except when we add
11036 // a ptrauth signature to the addresses.
11037 if (isa<AddrLabelExpr>(LHS.get()) &&
11038 getLangOpts().PointerAuthIndirectGotos) {
11039 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11040 << /*subtraction*/ 0;
11041 return QualType();
11042 }
11043
11044 // The result type of a pointer-int computation is the pointer type.
11045 if (RHS.get()->getType()->isIntegerType()) {
11046 // Subtracting from a null pointer should produce a warning.
11047 // The last argument to the diagnose call says this doesn't match the
11048 // GNU int-to-pointer idiom.
11051 // In C++ adding zero to a null pointer is defined.
11052 Expr::EvalResult KnownVal;
11053 if (!getLangOpts().CPlusPlus ||
11054 (!RHS.get()->isValueDependent() &&
11055 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11056 KnownVal.Val.getInt() != 0))) {
11057 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11058 }
11059 }
11060
11061 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11062 return QualType();
11063
11064 // Check array bounds for pointer arithemtic
11065 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11066 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11067
11068 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11069 return LHS.get()->getType();
11070 }
11071
11072 // Handle pointer-pointer subtractions.
11073 if (const PointerType *RHSPTy
11074 = RHS.get()->getType()->getAs<PointerType>()) {
11075 QualType rpointee = RHSPTy->getPointeeType();
11076
11077 if (getLangOpts().CPlusPlus) {
11078 // Pointee types must be the same: C++ [expr.add]
11079 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11080 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11081 }
11082 } else {
11083 // Pointee types must be compatible C99 6.5.6p3
11087 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11088 return QualType();
11089 }
11090 }
11091
11093 LHS.get(), RHS.get()))
11094 return QualType();
11095
11096 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11098 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11100
11101 // Subtracting nullptr or from nullptr is suspect
11102 if (LHSIsNullPtr)
11103 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11104 if (RHSIsNullPtr)
11105 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11106
11107 // The pointee type may have zero size. As an extension, a structure or
11108 // union may have zero size or an array may have zero length. In this
11109 // case subtraction does not make sense.
11110 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11111 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11112 if (ElementSize.isZero()) {
11113 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11114 << rpointee.getUnqualifiedType()
11115 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11116 }
11117 }
11118
11119 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11120 return Context.getPointerDiffType();
11121 }
11122 }
11123
11124 return InvalidOperands(Loc, LHS, RHS);
11125}
11126
11128 if (const EnumType *ET = T->getAs<EnumType>())
11129 return ET->getDecl()->isScoped();
11130 return false;
11131}
11132
11135 QualType LHSType) {
11136 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11137 // so skip remaining warnings as we don't want to modify values within Sema.
11138 if (S.getLangOpts().OpenCL)
11139 return;
11140
11141 // Check right/shifter operand
11142 Expr::EvalResult RHSResult;
11143 if (RHS.get()->isValueDependent() ||
11144 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11145 return;
11146 llvm::APSInt Right = RHSResult.Val.getInt();
11147
11148 if (Right.isNegative()) {
11149 S.DiagRuntimeBehavior(Loc, RHS.get(),
11150 S.PDiag(diag::warn_shift_negative)
11151 << RHS.get()->getSourceRange());
11152 return;
11153 }
11154
11155 QualType LHSExprType = LHS.get()->getType();
11156 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11157 if (LHSExprType->isBitIntType())
11158 LeftSize = S.Context.getIntWidth(LHSExprType);
11159 else if (LHSExprType->isFixedPointType()) {
11160 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11161 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11162 }
11163 if (Right.uge(LeftSize)) {
11164 S.DiagRuntimeBehavior(Loc, RHS.get(),
11165 S.PDiag(diag::warn_shift_gt_typewidth)
11166 << RHS.get()->getSourceRange());
11167 return;
11168 }
11169
11170 // FIXME: We probably need to handle fixed point types specially here.
11171 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11172 return;
11173
11174 // When left shifting an ICE which is signed, we can check for overflow which
11175 // according to C++ standards prior to C++2a has undefined behavior
11176 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11177 // more than the maximum value representable in the result type, so never
11178 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11179 // expression is still probably a bug.)
11180 Expr::EvalResult LHSResult;
11181 if (LHS.get()->isValueDependent() ||
11183 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11184 return;
11185 llvm::APSInt Left = LHSResult.Val.getInt();
11186
11187 // Don't warn if signed overflow is defined, then all the rest of the
11188 // diagnostics will not be triggered because the behavior is defined.
11189 // Also don't warn in C++20 mode (and newer), as signed left shifts
11190 // always wrap and never overflow.
11191 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11192 return;
11193
11194 // If LHS does not have a non-negative value then, the
11195 // behavior is undefined before C++2a. Warn about it.
11196 if (Left.isNegative()) {
11197 S.DiagRuntimeBehavior(Loc, LHS.get(),
11198 S.PDiag(diag::warn_shift_lhs_negative)
11199 << LHS.get()->getSourceRange());
11200 return;
11201 }
11202
11203 llvm::APInt ResultBits =
11204 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11205 if (ResultBits.ule(LeftSize))
11206 return;
11207 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11208 Result = Result.shl(Right);
11209
11210 // Print the bit representation of the signed integer as an unsigned
11211 // hexadecimal number.
11212 SmallString<40> HexResult;
11213 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11214
11215 // If we are only missing a sign bit, this is less likely to result in actual
11216 // bugs -- if the result is cast back to an unsigned type, it will have the
11217 // expected value. Thus we place this behind a different warning that can be
11218 // turned off separately if needed.
11219 if (ResultBits - 1 == LeftSize) {
11220 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11221 << HexResult << LHSType
11222 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11223 return;
11224 }
11225
11226 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11227 << HexResult.str() << Result.getSignificantBits() << LHSType
11228 << Left.getBitWidth() << LHS.get()->getSourceRange()
11229 << RHS.get()->getSourceRange();
11230}
11231
11232/// Return the resulting type when a vector is shifted
11233/// by a scalar or vector shift amount.
11235 SourceLocation Loc, bool IsCompAssign) {
11236 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11237 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11238 !LHS.get()->getType()->isVectorType()) {
11239 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11240 << RHS.get()->getType() << LHS.get()->getType()
11241 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11242 return QualType();
11243 }
11244
11245 if (!IsCompAssign) {
11246 LHS = S.UsualUnaryConversions(LHS.get());
11247 if (LHS.isInvalid()) return QualType();
11248 }
11249
11250 RHS = S.UsualUnaryConversions(RHS.get());
11251 if (RHS.isInvalid()) return QualType();
11252
11253 QualType LHSType = LHS.get()->getType();
11254 // Note that LHS might be a scalar because the routine calls not only in
11255 // OpenCL case.
11256 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11257 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11258
11259 // Note that RHS might not be a vector.
11260 QualType RHSType = RHS.get()->getType();
11261 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11262 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11263
11264 // Do not allow shifts for boolean vectors.
11265 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11266 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11267 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11268 << LHS.get()->getType() << RHS.get()->getType()
11269 << LHS.get()->getSourceRange();
11270 return QualType();
11271 }
11272
11273 // The operands need to be integers.
11274 if (!LHSEleType->isIntegerType()) {
11275 S.Diag(Loc, diag::err_typecheck_expect_int)
11276 << LHS.get()->getType() << LHS.get()->getSourceRange();
11277 return QualType();
11278 }
11279
11280 if (!RHSEleType->isIntegerType()) {
11281 S.Diag(Loc, diag::err_typecheck_expect_int)
11282 << RHS.get()->getType() << RHS.get()->getSourceRange();
11283 return QualType();
11284 }
11285
11286 if (!LHSVecTy) {
11287 assert(RHSVecTy);
11288 if (IsCompAssign)
11289 return RHSType;
11290 if (LHSEleType != RHSEleType) {
11291 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11292 LHSEleType = RHSEleType;
11293 }
11294 QualType VecTy =
11295 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11296 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11297 LHSType = VecTy;
11298 } else if (RHSVecTy) {
11299 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11300 // are applied component-wise. So if RHS is a vector, then ensure
11301 // that the number of elements is the same as LHS...
11302 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11303 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11304 << LHS.get()->getType() << RHS.get()->getType()
11305 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11306 return QualType();
11307 }
11308 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11309 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11310 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11311 if (LHSBT != RHSBT &&
11312 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11313 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11314 << LHS.get()->getType() << RHS.get()->getType()
11315 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11316 }
11317 }
11318 } else {
11319 // ...else expand RHS to match the number of elements in LHS.
11320 QualType VecTy =
11321 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11322 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11323 }
11324
11325 return LHSType;
11326}
11327
11330 bool IsCompAssign) {
11331 if (!IsCompAssign) {
11332 LHS = S.UsualUnaryConversions(LHS.get());
11333 if (LHS.isInvalid())
11334 return QualType();
11335 }
11336
11337 RHS = S.UsualUnaryConversions(RHS.get());
11338 if (RHS.isInvalid())
11339 return QualType();
11340
11341 QualType LHSType = LHS.get()->getType();
11342 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11343 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11344 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11345 : LHSType;
11346
11347 // Note that RHS might not be a vector
11348 QualType RHSType = RHS.get()->getType();
11349 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11350 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11351 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11352 : RHSType;
11353
11354 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11355 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11356 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11357 << LHSType << RHSType << LHS.get()->getSourceRange();
11358 return QualType();
11359 }
11360
11361 if (!LHSEleType->isIntegerType()) {
11362 S.Diag(Loc, diag::err_typecheck_expect_int)
11363 << LHS.get()->getType() << LHS.get()->getSourceRange();
11364 return QualType();
11365 }
11366
11367 if (!RHSEleType->isIntegerType()) {
11368 S.Diag(Loc, diag::err_typecheck_expect_int)
11369 << RHS.get()->getType() << RHS.get()->getSourceRange();
11370 return QualType();
11371 }
11372
11373 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11374 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11375 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11376 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11377 << LHSType << RHSType << LHS.get()->getSourceRange()
11378 << RHS.get()->getSourceRange();
11379 return QualType();
11380 }
11381
11382 if (!LHSType->isSveVLSBuiltinType()) {
11383 assert(RHSType->isSveVLSBuiltinType());
11384 if (IsCompAssign)
11385 return RHSType;
11386 if (LHSEleType != RHSEleType) {
11387 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11388 LHSEleType = RHSEleType;
11389 }
11390 const llvm::ElementCount VecSize =
11391 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11392 QualType VecTy =
11393 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11394 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11395 LHSType = VecTy;
11396 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11397 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11398 S.Context.getTypeSize(LHSBuiltinTy)) {
11399 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11400 << LHSType << RHSType << LHS.get()->getSourceRange()
11401 << RHS.get()->getSourceRange();
11402 return QualType();
11403 }
11404 } else {
11405 const llvm::ElementCount VecSize =
11406 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11407 if (LHSEleType != RHSEleType) {
11408 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11409 RHSEleType = LHSEleType;
11410 }
11411 QualType VecTy =
11412 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11413 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11414 }
11415
11416 return LHSType;
11417}
11418
11419// C99 6.5.7
11422 bool IsCompAssign) {
11423 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11424
11425 // Vector shifts promote their scalar inputs to vector type.
11426 if (LHS.get()->getType()->isVectorType() ||
11427 RHS.get()->getType()->isVectorType()) {
11428 if (LangOpts.ZVector) {
11429 // The shift operators for the z vector extensions work basically
11430 // like general shifts, except that neither the LHS nor the RHS is
11431 // allowed to be a "vector bool".
11432 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11433 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11434 return InvalidOperands(Loc, LHS, RHS);
11435 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11436 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11437 return InvalidOperands(Loc, LHS, RHS);
11438 }
11439 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11440 }
11441
11442 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11443 RHS.get()->getType()->isSveVLSBuiltinType())
11444 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11445
11446 // Shifts don't perform usual arithmetic conversions, they just do integer
11447 // promotions on each operand. C99 6.5.7p3
11448
11449 // For the LHS, do usual unary conversions, but then reset them away
11450 // if this is a compound assignment.
11451 ExprResult OldLHS = LHS;
11452 LHS = UsualUnaryConversions(LHS.get());
11453 if (LHS.isInvalid())
11454 return QualType();
11455 QualType LHSType = LHS.get()->getType();
11456 if (IsCompAssign) LHS = OldLHS;
11457
11458 // The RHS is simpler.
11459 RHS = UsualUnaryConversions(RHS.get());
11460 if (RHS.isInvalid())
11461 return QualType();
11462 QualType RHSType = RHS.get()->getType();
11463
11464 // C99 6.5.7p2: Each of the operands shall have integer type.
11465 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11466 if ((!LHSType->isFixedPointOrIntegerType() &&
11467 !LHSType->hasIntegerRepresentation()) ||
11468 !RHSType->hasIntegerRepresentation())
11469 return InvalidOperands(Loc, LHS, RHS);
11470
11471 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11472 // hasIntegerRepresentation() above instead of this.
11473 if (isScopedEnumerationType(LHSType) ||
11474 isScopedEnumerationType(RHSType)) {
11475 return InvalidOperands(Loc, LHS, RHS);
11476 }
11477 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11478
11479 // "The type of the result is that of the promoted left operand."
11480 return LHSType;
11481}
11482
11483/// Diagnose bad pointer comparisons.
11485 ExprResult &LHS, ExprResult &RHS,
11486 bool IsError) {
11487 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11488 : diag::ext_typecheck_comparison_of_distinct_pointers)
11489 << LHS.get()->getType() << RHS.get()->getType()
11490 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11491}
11492
11493/// Returns false if the pointers are converted to a composite type,
11494/// true otherwise.
11496 ExprResult &LHS, ExprResult &RHS) {
11497 // C++ [expr.rel]p2:
11498 // [...] Pointer conversions (4.10) and qualification
11499 // conversions (4.4) are performed on pointer operands (or on
11500 // a pointer operand and a null pointer constant) to bring
11501 // them to their composite pointer type. [...]
11502 //
11503 // C++ [expr.eq]p1 uses the same notion for (in)equality
11504 // comparisons of pointers.
11505
11506 QualType LHSType = LHS.get()->getType();
11507 QualType RHSType = RHS.get()->getType();
11508 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11509 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11510
11511 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11512 if (T.isNull()) {
11513 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11514 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11515 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11516 else
11517 S.InvalidOperands(Loc, LHS, RHS);
11518 return true;
11519 }
11520
11521 return false;
11522}
11523
11525 ExprResult &LHS,
11526 ExprResult &RHS,
11527 bool IsError) {
11528 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11529 : diag::ext_typecheck_comparison_of_fptr_to_void)
11530 << LHS.get()->getType() << RHS.get()->getType()
11531 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11532}
11533
11535 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11536 case Stmt::ObjCArrayLiteralClass:
11537 case Stmt::ObjCDictionaryLiteralClass:
11538 case Stmt::ObjCStringLiteralClass:
11539 case Stmt::ObjCBoxedExprClass:
11540 return true;
11541 default:
11542 // Note that ObjCBoolLiteral is NOT an object literal!
11543 return false;
11544 }
11545}
11546
11547static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11550
11551 // If this is not actually an Objective-C object, bail out.
11552 if (!Type)
11553 return false;
11554
11555 // Get the LHS object's interface type.
11556 QualType InterfaceType = Type->getPointeeType();
11557
11558 // If the RHS isn't an Objective-C object, bail out.
11559 if (!RHS->getType()->isObjCObjectPointerType())
11560 return false;
11561
11562 // Try to find the -isEqual: method.
11563 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
11564 ObjCMethodDecl *Method =
11565 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
11566 /*IsInstance=*/true);
11567 if (!Method) {
11568 if (Type->isObjCIdType()) {
11569 // For 'id', just check the global pool.
11570 Method =
11572 /*receiverId=*/true);
11573 } else {
11574 // Check protocols.
11575 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
11576 /*IsInstance=*/true);
11577 }
11578 }
11579
11580 if (!Method)
11581 return false;
11582
11583 QualType T = Method->parameters()[0]->getType();
11584 if (!T->isObjCObjectPointerType())
11585 return false;
11586
11587 QualType R = Method->getReturnType();
11588 if (!R->isScalarType())
11589 return false;
11590
11591 return true;
11592}
11593
11595 ExprResult &LHS, ExprResult &RHS,
11597 Expr *Literal;
11598 Expr *Other;
11599 if (isObjCObjectLiteral(LHS)) {
11600 Literal = LHS.get();
11601 Other = RHS.get();
11602 } else {
11603 Literal = RHS.get();
11604 Other = LHS.get();
11605 }
11606
11607 // Don't warn on comparisons against nil.
11608 Other = Other->IgnoreParenCasts();
11609 if (Other->isNullPointerConstant(S.getASTContext(),
11611 return;
11612
11613 // This should be kept in sync with warn_objc_literal_comparison.
11614 // LK_String should always be after the other literals, since it has its own
11615 // warning flag.
11616 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
11617 assert(LiteralKind != SemaObjC::LK_Block);
11618 if (LiteralKind == SemaObjC::LK_None) {
11619 llvm_unreachable("Unknown Objective-C object literal kind");
11620 }
11621
11622 if (LiteralKind == SemaObjC::LK_String)
11623 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11624 << Literal->getSourceRange();
11625 else
11626 S.Diag(Loc, diag::warn_objc_literal_comparison)
11627 << LiteralKind << Literal->getSourceRange();
11628
11630 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11631 SourceLocation Start = LHS.get()->getBeginLoc();
11633 CharSourceRange OpRange =
11635
11636 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11637 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11638 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11639 << FixItHint::CreateInsertion(End, "]");
11640 }
11641}
11642
11643/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11646 BinaryOperatorKind Opc) {
11647 // Check that left hand side is !something.
11648 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11649 if (!UO || UO->getOpcode() != UO_LNot) return;
11650
11651 // Only check if the right hand side is non-bool arithmetic type.
11652 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11653
11654 // Make sure that the something in !something is not bool.
11655 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11656 if (SubExpr->isKnownToHaveBooleanValue()) return;
11657
11658 // Emit warning.
11659 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11660 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11661 << Loc << IsBitwiseOp;
11662
11663 // First note suggest !(x < y)
11664 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11665 SourceLocation FirstClose = RHS.get()->getEndLoc();
11666 FirstClose = S.getLocForEndOfToken(FirstClose);
11667 if (FirstClose.isInvalid())
11668 FirstOpen = SourceLocation();
11669 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11670 << IsBitwiseOp
11671 << FixItHint::CreateInsertion(FirstOpen, "(")
11672 << FixItHint::CreateInsertion(FirstClose, ")");
11673
11674 // Second note suggests (!x) < y
11675 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11676 SourceLocation SecondClose = LHS.get()->getEndLoc();
11677 SecondClose = S.getLocForEndOfToken(SecondClose);
11678 if (SecondClose.isInvalid())
11679 SecondOpen = SourceLocation();
11680 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11681 << FixItHint::CreateInsertion(SecondOpen, "(")
11682 << FixItHint::CreateInsertion(SecondClose, ")");
11683}
11684
11685// Returns true if E refers to a non-weak array.
11686static bool checkForArray(const Expr *E) {
11687 const ValueDecl *D = nullptr;
11688 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11689 D = DR->getDecl();
11690 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11691 if (Mem->isImplicitAccess())
11692 D = Mem->getMemberDecl();
11693 }
11694 if (!D)
11695 return false;
11696 return D->getType()->isArrayType() && !D->isWeak();
11697}
11698
11699/// Diagnose some forms of syntactically-obvious tautological comparison.
11701 Expr *LHS, Expr *RHS,
11702 BinaryOperatorKind Opc) {
11703 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11704 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11705
11706 QualType LHSType = LHS->getType();
11707 QualType RHSType = RHS->getType();
11708 if (LHSType->hasFloatingRepresentation() ||
11709 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11711 return;
11712
11713 // WebAssembly Tables cannot be compared, therefore shouldn't emit
11714 // Tautological diagnostics.
11715 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
11716 return;
11717
11718 // Comparisons between two array types are ill-formed for operator<=>, so
11719 // we shouldn't emit any additional warnings about it.
11720 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11721 return;
11722
11723 // For non-floating point types, check for self-comparisons of the form
11724 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11725 // often indicate logic errors in the program.
11726 //
11727 // NOTE: Don't warn about comparison expressions resulting from macro
11728 // expansion. Also don't warn about comparisons which are only self
11729 // comparisons within a template instantiation. The warnings should catch
11730 // obvious cases in the definition of the template anyways. The idea is to
11731 // warn when the typed comparison operator will always evaluate to the same
11732 // result.
11733
11734 // Used for indexing into %select in warn_comparison_always
11735 enum {
11736 AlwaysConstant,
11737 AlwaysTrue,
11738 AlwaysFalse,
11739 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11740 };
11741
11742 // C++2a [depr.array.comp]:
11743 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11744 // operands of array type are deprecated.
11745 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11746 RHSStripped->getType()->isArrayType()) {
11747 S.Diag(Loc, diag::warn_depr_array_comparison)
11748 << LHS->getSourceRange() << RHS->getSourceRange()
11749 << LHSStripped->getType() << RHSStripped->getType();
11750 // Carry on to produce the tautological comparison warning, if this
11751 // expression is potentially-evaluated, we can resolve the array to a
11752 // non-weak declaration, and so on.
11753 }
11754
11755 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11756 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11757 unsigned Result;
11758 switch (Opc) {
11759 case BO_EQ:
11760 case BO_LE:
11761 case BO_GE:
11762 Result = AlwaysTrue;
11763 break;
11764 case BO_NE:
11765 case BO_LT:
11766 case BO_GT:
11767 Result = AlwaysFalse;
11768 break;
11769 case BO_Cmp:
11770 Result = AlwaysEqual;
11771 break;
11772 default:
11773 Result = AlwaysConstant;
11774 break;
11775 }
11776 S.DiagRuntimeBehavior(Loc, nullptr,
11777 S.PDiag(diag::warn_comparison_always)
11778 << 0 /*self-comparison*/
11779 << Result);
11780 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11781 // What is it always going to evaluate to?
11782 unsigned Result;
11783 switch (Opc) {
11784 case BO_EQ: // e.g. array1 == array2
11785 Result = AlwaysFalse;
11786 break;
11787 case BO_NE: // e.g. array1 != array2
11788 Result = AlwaysTrue;
11789 break;
11790 default: // e.g. array1 <= array2
11791 // The best we can say is 'a constant'
11792 Result = AlwaysConstant;
11793 break;
11794 }
11795 S.DiagRuntimeBehavior(Loc, nullptr,
11796 S.PDiag(diag::warn_comparison_always)
11797 << 1 /*array comparison*/
11798 << Result);
11799 }
11800 }
11801
11802 if (isa<CastExpr>(LHSStripped))
11803 LHSStripped = LHSStripped->IgnoreParenCasts();
11804 if (isa<CastExpr>(RHSStripped))
11805 RHSStripped = RHSStripped->IgnoreParenCasts();
11806
11807 // Warn about comparisons against a string constant (unless the other
11808 // operand is null); the user probably wants string comparison function.
11809 Expr *LiteralString = nullptr;
11810 Expr *LiteralStringStripped = nullptr;
11811 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11812 !RHSStripped->isNullPointerConstant(S.Context,
11814 LiteralString = LHS;
11815 LiteralStringStripped = LHSStripped;
11816 } else if ((isa<StringLiteral>(RHSStripped) ||
11817 isa<ObjCEncodeExpr>(RHSStripped)) &&
11818 !LHSStripped->isNullPointerConstant(S.Context,
11820 LiteralString = RHS;
11821 LiteralStringStripped = RHSStripped;
11822 }
11823
11824 if (LiteralString) {
11825 S.DiagRuntimeBehavior(Loc, nullptr,
11826 S.PDiag(diag::warn_stringcompare)
11827 << isa<ObjCEncodeExpr>(LiteralStringStripped)
11828 << LiteralString->getSourceRange());
11829 }
11830}
11831
11833 switch (CK) {
11834 default: {
11835#ifndef NDEBUG
11836 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11837 << "\n";
11838#endif
11839 llvm_unreachable("unhandled cast kind");
11840 }
11841 case CK_UserDefinedConversion:
11842 return ICK_Identity;
11843 case CK_LValueToRValue:
11844 return ICK_Lvalue_To_Rvalue;
11845 case CK_ArrayToPointerDecay:
11846 return ICK_Array_To_Pointer;
11847 case CK_FunctionToPointerDecay:
11849 case CK_IntegralCast:
11851 case CK_FloatingCast:
11853 case CK_IntegralToFloating:
11854 case CK_FloatingToIntegral:
11855 return ICK_Floating_Integral;
11856 case CK_IntegralComplexCast:
11857 case CK_FloatingComplexCast:
11858 case CK_FloatingComplexToIntegralComplex:
11859 case CK_IntegralComplexToFloatingComplex:
11861 case CK_FloatingComplexToReal:
11862 case CK_FloatingRealToComplex:
11863 case CK_IntegralComplexToReal:
11864 case CK_IntegralRealToComplex:
11865 return ICK_Complex_Real;
11866 case CK_HLSLArrayRValue:
11867 return ICK_HLSL_Array_RValue;
11868 }
11869}
11870
11872 QualType FromType,
11874 // Check for a narrowing implicit conversion.
11877 SCS.setToType(0, FromType);
11878 SCS.setToType(1, ToType);
11879 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11880 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11881
11882 APValue PreNarrowingValue;
11883 QualType PreNarrowingType;
11884 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11885 PreNarrowingType,
11886 /*IgnoreFloatToIntegralConversion*/ true)) {
11888 // Implicit conversion to a narrower type, but the expression is
11889 // value-dependent so we can't tell whether it's actually narrowing.
11890 case NK_Not_Narrowing:
11891 return false;
11892
11894 // Implicit conversion to a narrower type, and the value is not a constant
11895 // expression.
11896 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11897 << /*Constant*/ 1
11898 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11899 return true;
11900
11902 // Implicit conversion to a narrower type, and the value is not a constant
11903 // expression.
11904 case NK_Type_Narrowing:
11905 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11906 << /*Constant*/ 0 << FromType << ToType;
11907 // TODO: It's not a constant expression, but what if the user intended it
11908 // to be? Can we produce notes to help them figure out why it isn't?
11909 return true;
11910 }
11911 llvm_unreachable("unhandled case in switch");
11912}
11913
11915 ExprResult &LHS,
11916 ExprResult &RHS,
11918 QualType LHSType = LHS.get()->getType();
11919 QualType RHSType = RHS.get()->getType();
11920 // Dig out the original argument type and expression before implicit casts
11921 // were applied. These are the types/expressions we need to check the
11922 // [expr.spaceship] requirements against.
11923 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11924 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11925 QualType LHSStrippedType = LHSStripped.get()->getType();
11926 QualType RHSStrippedType = RHSStripped.get()->getType();
11927
11928 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11929 // other is not, the program is ill-formed.
11930 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11931 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11932 return QualType();
11933 }
11934
11935 // FIXME: Consider combining this with checkEnumArithmeticConversions.
11936 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11937 RHSStrippedType->isEnumeralType();
11938 if (NumEnumArgs == 1) {
11939 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11940 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11941 if (OtherTy->hasFloatingRepresentation()) {
11942 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11943 return QualType();
11944 }
11945 }
11946 if (NumEnumArgs == 2) {
11947 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11948 // type E, the operator yields the result of converting the operands
11949 // to the underlying type of E and applying <=> to the converted operands.
11950 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11951 S.InvalidOperands(Loc, LHS, RHS);
11952 return QualType();
11953 }
11954 QualType IntType =
11955 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11956 assert(IntType->isArithmeticType());
11957
11958 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11959 // promote the boolean type, and all other promotable integer types, to
11960 // avoid this.
11961 if (S.Context.isPromotableIntegerType(IntType))
11962 IntType = S.Context.getPromotedIntegerType(IntType);
11963
11964 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11965 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11966 LHSType = RHSType = IntType;
11967 }
11968
11969 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11970 // usual arithmetic conversions are applied to the operands.
11971 QualType Type =
11973 if (LHS.isInvalid() || RHS.isInvalid())
11974 return QualType();
11975 if (Type.isNull())
11976 return S.InvalidOperands(Loc, LHS, RHS);
11977
11978 std::optional<ComparisonCategoryType> CCT =
11980 if (!CCT)
11981 return S.InvalidOperands(Loc, LHS, RHS);
11982
11983 bool HasNarrowing = checkThreeWayNarrowingConversion(
11984 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11985 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11986 RHS.get()->getBeginLoc());
11987 if (HasNarrowing)
11988 return QualType();
11989
11990 assert(!Type.isNull() && "composite type for <=> has not been set");
11991
11994}
11995
11997 ExprResult &RHS,
11999 BinaryOperatorKind Opc) {
12000 if (Opc == BO_Cmp)
12001 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12002
12003 // C99 6.5.8p3 / C99 6.5.9p4
12004 QualType Type =
12006 if (LHS.isInvalid() || RHS.isInvalid())
12007 return QualType();
12008 if (Type.isNull())
12009 return S.InvalidOperands(Loc, LHS, RHS);
12010 assert(Type->isArithmeticType() || Type->isEnumeralType());
12011
12013 return S.InvalidOperands(Loc, LHS, RHS);
12014
12015 // Check for comparisons of floating point operands using != and ==.
12017 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12018
12019 // The result of comparisons is 'bool' in C++, 'int' in C.
12021}
12022
12024 if (!NullE.get()->getType()->isAnyPointerType())
12025 return;
12026 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12027 if (!E.get()->getType()->isAnyPointerType() &&
12031 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12032 if (CL->getValue() == 0)
12033 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12034 << NullValue
12036 NullValue ? "NULL" : "(void *)0");
12037 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12038 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12040 if (T == Context.CharTy)
12041 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12042 << NullValue
12044 NullValue ? "NULL" : "(void *)0");
12045 }
12046 }
12047}
12048
12049// C99 6.5.8, C++ [expr.rel]
12052 BinaryOperatorKind Opc) {
12053 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12054 bool IsThreeWay = Opc == BO_Cmp;
12055 bool IsOrdered = IsRelational || IsThreeWay;
12056 auto IsAnyPointerType = [](ExprResult E) {
12057 QualType Ty = E.get()->getType();
12058 return Ty->isPointerType() || Ty->isMemberPointerType();
12059 };
12060
12061 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12062 // type, array-to-pointer, ..., conversions are performed on both operands to
12063 // bring them to their composite type.
12064 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12065 // any type-related checks.
12066 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12068 if (LHS.isInvalid())
12069 return QualType();
12071 if (RHS.isInvalid())
12072 return QualType();
12073 } else {
12074 LHS = DefaultLvalueConversion(LHS.get());
12075 if (LHS.isInvalid())
12076 return QualType();
12077 RHS = DefaultLvalueConversion(RHS.get());
12078 if (RHS.isInvalid())
12079 return QualType();
12080 }
12081
12082 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12086 }
12087
12088 // Handle vector comparisons separately.
12089 if (LHS.get()->getType()->isVectorType() ||
12090 RHS.get()->getType()->isVectorType())
12091 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12092
12093 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12094 RHS.get()->getType()->isSveVLSBuiltinType())
12095 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12096
12097 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12098 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12099
12100 QualType LHSType = LHS.get()->getType();
12101 QualType RHSType = RHS.get()->getType();
12102 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12103 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12104 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12105
12106 if ((LHSType->isPointerType() &&
12108 (RHSType->isPointerType() &&
12110 return InvalidOperands(Loc, LHS, RHS);
12111
12112 const Expr::NullPointerConstantKind LHSNullKind =
12114 const Expr::NullPointerConstantKind RHSNullKind =
12116 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12117 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12118
12119 auto computeResultTy = [&]() {
12120 if (Opc != BO_Cmp)
12122 assert(getLangOpts().CPlusPlus);
12123 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12124
12125 QualType CompositeTy = LHS.get()->getType();
12126 assert(!CompositeTy->isReferenceType());
12127
12128 std::optional<ComparisonCategoryType> CCT =
12130 if (!CCT)
12131 return InvalidOperands(Loc, LHS, RHS);
12132
12133 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12134 // P0946R0: Comparisons between a null pointer constant and an object
12135 // pointer result in std::strong_equality, which is ill-formed under
12136 // P1959R0.
12137 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12138 << (LHSIsNull ? LHS.get()->getSourceRange()
12139 : RHS.get()->getSourceRange());
12140 return QualType();
12141 }
12142
12145 };
12146
12147 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12148 bool IsEquality = Opc == BO_EQ;
12149 if (RHSIsNull)
12150 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12151 RHS.get()->getSourceRange());
12152 else
12153 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12154 LHS.get()->getSourceRange());
12155 }
12156
12157 if (IsOrdered && LHSType->isFunctionPointerType() &&
12158 RHSType->isFunctionPointerType()) {
12159 // Valid unless a relational comparison of function pointers
12160 bool IsError = Opc == BO_Cmp;
12161 auto DiagID =
12162 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12163 : getLangOpts().CPlusPlus
12164 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12165 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12166 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12167 << RHS.get()->getSourceRange();
12168 if (IsError)
12169 return QualType();
12170 }
12171
12172 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12173 (RHSType->isIntegerType() && !RHSIsNull)) {
12174 // Skip normal pointer conversion checks in this case; we have better
12175 // diagnostics for this below.
12176 } else if (getLangOpts().CPlusPlus) {
12177 // Equality comparison of a function pointer to a void pointer is invalid,
12178 // but we allow it as an extension.
12179 // FIXME: If we really want to allow this, should it be part of composite
12180 // pointer type computation so it works in conditionals too?
12181 if (!IsOrdered &&
12182 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12183 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12184 // This is a gcc extension compatibility comparison.
12185 // In a SFINAE context, we treat this as a hard error to maintain
12186 // conformance with the C++ standard.
12188 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12189
12190 if (isSFINAEContext())
12191 return QualType();
12192
12193 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12194 return computeResultTy();
12195 }
12196
12197 // C++ [expr.eq]p2:
12198 // If at least one operand is a pointer [...] bring them to their
12199 // composite pointer type.
12200 // C++ [expr.spaceship]p6
12201 // If at least one of the operands is of pointer type, [...] bring them
12202 // to their composite pointer type.
12203 // C++ [expr.rel]p2:
12204 // If both operands are pointers, [...] bring them to their composite
12205 // pointer type.
12206 // For <=>, the only valid non-pointer types are arrays and functions, and
12207 // we already decayed those, so this is really the same as the relational
12208 // comparison rule.
12209 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12210 (IsOrdered ? 2 : 1) &&
12211 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12212 RHSType->isObjCObjectPointerType()))) {
12213 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12214 return QualType();
12215 return computeResultTy();
12216 }
12217 } else if (LHSType->isPointerType() &&
12218 RHSType->isPointerType()) { // C99 6.5.8p2
12219 // All of the following pointer-related warnings are GCC extensions, except
12220 // when handling null pointer constants.
12221 QualType LCanPointeeTy =
12223 QualType RCanPointeeTy =
12225
12226 // C99 6.5.9p2 and C99 6.5.8p2
12227 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12228 RCanPointeeTy.getUnqualifiedType())) {
12229 if (IsRelational) {
12230 // Pointers both need to point to complete or incomplete types
12231 if ((LCanPointeeTy->isIncompleteType() !=
12232 RCanPointeeTy->isIncompleteType()) &&
12233 !getLangOpts().C11) {
12234 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12235 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12236 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12237 << RCanPointeeTy->isIncompleteType();
12238 }
12239 }
12240 } else if (!IsRelational &&
12241 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12242 // Valid unless comparison between non-null pointer and function pointer
12243 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12244 && !LHSIsNull && !RHSIsNull)
12246 /*isError*/false);
12247 } else {
12248 // Invalid
12249 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12250 }
12251 if (LCanPointeeTy != RCanPointeeTy) {
12252 // Treat NULL constant as a special case in OpenCL.
12253 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12254 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12255 Diag(Loc,
12256 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12257 << LHSType << RHSType << 0 /* comparison */
12258 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12259 }
12260 }
12261 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12262 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12263 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12264 : CK_BitCast;
12265 if (LHSIsNull && !RHSIsNull)
12266 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12267 else
12268 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12269 }
12270 return computeResultTy();
12271 }
12272
12273
12274 // C++ [expr.eq]p4:
12275 // Two operands of type std::nullptr_t or one operand of type
12276 // std::nullptr_t and the other a null pointer constant compare
12277 // equal.
12278 // C23 6.5.9p5:
12279 // If both operands have type nullptr_t or one operand has type nullptr_t
12280 // and the other is a null pointer constant, they compare equal if the
12281 // former is a null pointer.
12282 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12283 if (LHSType->isNullPtrType()) {
12284 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12285 return computeResultTy();
12286 }
12287 if (RHSType->isNullPtrType()) {
12288 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12289 return computeResultTy();
12290 }
12291 }
12292
12293 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12294 // C23 6.5.9p6:
12295 // Otherwise, at least one operand is a pointer. If one is a pointer and
12296 // the other is a null pointer constant or has type nullptr_t, they
12297 // compare equal
12298 if (LHSIsNull && RHSType->isPointerType()) {
12299 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12300 return computeResultTy();
12301 }
12302 if (RHSIsNull && LHSType->isPointerType()) {
12303 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12304 return computeResultTy();
12305 }
12306 }
12307
12308 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12309 // These aren't covered by the composite pointer type rules.
12310 if (!IsOrdered && RHSType->isNullPtrType() &&
12311 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12312 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12313 return computeResultTy();
12314 }
12315 if (!IsOrdered && LHSType->isNullPtrType() &&
12316 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12317 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12318 return computeResultTy();
12319 }
12320
12321 if (getLangOpts().CPlusPlus) {
12322 if (IsRelational &&
12323 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12324 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12325 // HACK: Relational comparison of nullptr_t against a pointer type is
12326 // invalid per DR583, but we allow it within std::less<> and friends,
12327 // since otherwise common uses of it break.
12328 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12329 // friends to have std::nullptr_t overload candidates.
12330 DeclContext *DC = CurContext;
12331 if (isa<FunctionDecl>(DC))
12332 DC = DC->getParent();
12333 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12334 if (CTSD->isInStdNamespace() &&
12335 llvm::StringSwitch<bool>(CTSD->getName())
12336 .Cases("less", "less_equal", "greater", "greater_equal", true)
12337 .Default(false)) {
12338 if (RHSType->isNullPtrType())
12339 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12340 else
12341 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12342 return computeResultTy();
12343 }
12344 }
12345 }
12346
12347 // C++ [expr.eq]p2:
12348 // If at least one operand is a pointer to member, [...] bring them to
12349 // their composite pointer type.
12350 if (!IsOrdered &&
12351 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12352 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12353 return QualType();
12354 else
12355 return computeResultTy();
12356 }
12357 }
12358
12359 // Handle block pointer types.
12360 if (!IsOrdered && LHSType->isBlockPointerType() &&
12361 RHSType->isBlockPointerType()) {
12362 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12363 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12364
12365 if (!LHSIsNull && !RHSIsNull &&
12366 !Context.typesAreCompatible(lpointee, rpointee)) {
12367 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12368 << LHSType << RHSType << LHS.get()->getSourceRange()
12369 << RHS.get()->getSourceRange();
12370 }
12371 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12372 return computeResultTy();
12373 }
12374
12375 // Allow block pointers to be compared with null pointer constants.
12376 if (!IsOrdered
12377 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12378 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12379 if (!LHSIsNull && !RHSIsNull) {
12380 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12382 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12383 ->getPointeeType()->isVoidType())))
12384 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12385 << LHSType << RHSType << LHS.get()->getSourceRange()
12386 << RHS.get()->getSourceRange();
12387 }
12388 if (LHSIsNull && !RHSIsNull)
12389 LHS = ImpCastExprToType(LHS.get(), RHSType,
12390 RHSType->isPointerType() ? CK_BitCast
12391 : CK_AnyPointerToBlockPointerCast);
12392 else
12393 RHS = ImpCastExprToType(RHS.get(), LHSType,
12394 LHSType->isPointerType() ? CK_BitCast
12395 : CK_AnyPointerToBlockPointerCast);
12396 return computeResultTy();
12397 }
12398
12399 if (LHSType->isObjCObjectPointerType() ||
12400 RHSType->isObjCObjectPointerType()) {
12401 const PointerType *LPT = LHSType->getAs<PointerType>();
12402 const PointerType *RPT = RHSType->getAs<PointerType>();
12403 if (LPT || RPT) {
12404 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12405 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12406
12407 if (!LPtrToVoid && !RPtrToVoid &&
12408 !Context.typesAreCompatible(LHSType, RHSType)) {
12409 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12410 /*isError*/false);
12411 }
12412 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12413 // the RHS, but we have test coverage for this behavior.
12414 // FIXME: Consider using convertPointersToCompositeType in C++.
12415 if (LHSIsNull && !RHSIsNull) {
12416 Expr *E = LHS.get();
12417 if (getLangOpts().ObjCAutoRefCount)
12418 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
12420 LHS = ImpCastExprToType(E, RHSType,
12421 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12422 }
12423 else {
12424 Expr *E = RHS.get();
12425 if (getLangOpts().ObjCAutoRefCount)
12426 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
12428 /*Diagnose=*/true,
12429 /*DiagnoseCFAudited=*/false, Opc);
12430 RHS = ImpCastExprToType(E, LHSType,
12431 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12432 }
12433 return computeResultTy();
12434 }
12435 if (LHSType->isObjCObjectPointerType() &&
12436 RHSType->isObjCObjectPointerType()) {
12437 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12438 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12439 /*isError*/false);
12441 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12442
12443 if (LHSIsNull && !RHSIsNull)
12444 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12445 else
12446 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12447 return computeResultTy();
12448 }
12449
12450 if (!IsOrdered && LHSType->isBlockPointerType() &&
12452 LHS = ImpCastExprToType(LHS.get(), RHSType,
12453 CK_BlockPointerToObjCPointerCast);
12454 return computeResultTy();
12455 } else if (!IsOrdered &&
12457 RHSType->isBlockPointerType()) {
12458 RHS = ImpCastExprToType(RHS.get(), LHSType,
12459 CK_BlockPointerToObjCPointerCast);
12460 return computeResultTy();
12461 }
12462 }
12463 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12464 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12465 unsigned DiagID = 0;
12466 bool isError = false;
12467 if (LangOpts.DebuggerSupport) {
12468 // Under a debugger, allow the comparison of pointers to integers,
12469 // since users tend to want to compare addresses.
12470 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12471 (RHSIsNull && RHSType->isIntegerType())) {
12472 if (IsOrdered) {
12473 isError = getLangOpts().CPlusPlus;
12474 DiagID =
12475 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12476 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12477 }
12478 } else if (getLangOpts().CPlusPlus) {
12479 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12480 isError = true;
12481 } else if (IsOrdered)
12482 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12483 else
12484 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12485
12486 if (DiagID) {
12487 Diag(Loc, DiagID)
12488 << LHSType << RHSType << LHS.get()->getSourceRange()
12489 << RHS.get()->getSourceRange();
12490 if (isError)
12491 return QualType();
12492 }
12493
12494 if (LHSType->isIntegerType())
12495 LHS = ImpCastExprToType(LHS.get(), RHSType,
12496 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12497 else
12498 RHS = ImpCastExprToType(RHS.get(), LHSType,
12499 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12500 return computeResultTy();
12501 }
12502
12503 // Handle block pointers.
12504 if (!IsOrdered && RHSIsNull
12505 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12506 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12507 return computeResultTy();
12508 }
12509 if (!IsOrdered && LHSIsNull
12510 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12511 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12512 return computeResultTy();
12513 }
12514
12515 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12516 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12517 return computeResultTy();
12518 }
12519
12520 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12521 return computeResultTy();
12522 }
12523
12524 if (LHSIsNull && RHSType->isQueueT()) {
12525 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12526 return computeResultTy();
12527 }
12528
12529 if (LHSType->isQueueT() && RHSIsNull) {
12530 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12531 return computeResultTy();
12532 }
12533 }
12534
12535 return InvalidOperands(Loc, LHS, RHS);
12536}
12537
12539 const VectorType *VTy = V->castAs<VectorType>();
12540 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12541
12542 if (isa<ExtVectorType>(VTy)) {
12543 if (VTy->isExtVectorBoolType())
12545 if (TypeSize == Context.getTypeSize(Context.CharTy))
12547 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12549 if (TypeSize == Context.getTypeSize(Context.IntTy))
12551 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12553 if (TypeSize == Context.getTypeSize(Context.LongTy))
12555 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12556 "Unhandled vector element size in vector compare");
12558 }
12559
12560 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12563 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12566 if (TypeSize == Context.getTypeSize(Context.LongTy))
12569 if (TypeSize == Context.getTypeSize(Context.IntTy))
12572 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12575 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12576 "Unhandled vector element size in vector compare");
12579}
12580
12582 const BuiltinType *VTy = V->castAs<BuiltinType>();
12583 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
12584
12585 const QualType ETy = V->getSveEltType(Context);
12586 const auto TypeSize = Context.getTypeSize(ETy);
12587
12588 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12589 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12590 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12591}
12592
12595 BinaryOperatorKind Opc) {
12596 if (Opc == BO_Cmp) {
12597 Diag(Loc, diag::err_three_way_vector_comparison);
12598 return QualType();
12599 }
12600
12601 // Check to make sure we're operating on vectors of the same type and width,
12602 // Allowing one side to be a scalar of element type.
12603 QualType vType =
12604 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12605 /*AllowBothBool*/ true,
12606 /*AllowBoolConversions*/ getLangOpts().ZVector,
12607 /*AllowBooleanOperation*/ true,
12608 /*ReportInvalid*/ true);
12609 if (vType.isNull())
12610 return vType;
12611
12612 QualType LHSType = LHS.get()->getType();
12613
12614 // Determine the return type of a vector compare. By default clang will return
12615 // a scalar for all vector compares except vector bool and vector pixel.
12616 // With the gcc compiler we will always return a vector type and with the xl
12617 // compiler we will always return a scalar type. This switch allows choosing
12618 // which behavior is prefered.
12619 if (getLangOpts().AltiVec) {
12620 switch (getLangOpts().getAltivecSrcCompat()) {
12622 // If AltiVec, the comparison results in a numeric type, i.e.
12623 // bool for C++, int for C
12624 if (vType->castAs<VectorType>()->getVectorKind() ==
12627 else
12628 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12629 break;
12631 // For GCC we always return the vector type.
12632 break;
12635 break;
12636 }
12637 }
12638
12639 // For non-floating point types, check for self-comparisons of the form
12640 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12641 // often indicate logic errors in the program.
12642 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12643
12644 // Check for comparisons of floating point operands using != and ==.
12645 if (LHSType->hasFloatingRepresentation()) {
12646 assert(RHS.get()->getType()->hasFloatingRepresentation());
12647 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12648 }
12649
12650 // Return a signed type for the vector.
12651 return GetSignedVectorType(vType);
12652}
12653
12655 ExprResult &RHS,
12657 BinaryOperatorKind Opc) {
12658 if (Opc == BO_Cmp) {
12659 Diag(Loc, diag::err_three_way_vector_comparison);
12660 return QualType();
12661 }
12662
12663 // Check to make sure we're operating on vectors of the same type and width,
12664 // Allowing one side to be a scalar of element type.
12666 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12667
12668 if (vType.isNull())
12669 return vType;
12670
12671 QualType LHSType = LHS.get()->getType();
12672
12673 // For non-floating point types, check for self-comparisons of the form
12674 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12675 // often indicate logic errors in the program.
12676 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12677
12678 // Check for comparisons of floating point operands using != and ==.
12679 if (LHSType->hasFloatingRepresentation()) {
12680 assert(RHS.get()->getType()->hasFloatingRepresentation());
12681 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12682 }
12683
12684 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12685 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12686
12687 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12688 RHSBuiltinTy->isSVEBool())
12689 return LHSType;
12690
12691 // Return a signed type for the vector.
12692 return GetSignedSizelessVectorType(vType);
12693}
12694
12695static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12696 const ExprResult &XorRHS,
12697 const SourceLocation Loc) {
12698 // Do not diagnose macros.
12699 if (Loc.isMacroID())
12700 return;
12701
12702 // Do not diagnose if both LHS and RHS are macros.
12703 if (XorLHS.get()->getExprLoc().isMacroID() &&
12704 XorRHS.get()->getExprLoc().isMacroID())
12705 return;
12706
12707 bool Negative = false;
12708 bool ExplicitPlus = false;
12709 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12710 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12711
12712 if (!LHSInt)
12713 return;
12714 if (!RHSInt) {
12715 // Check negative literals.
12716 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12717 UnaryOperatorKind Opc = UO->getOpcode();
12718 if (Opc != UO_Minus && Opc != UO_Plus)
12719 return;
12720 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12721 if (!RHSInt)
12722 return;
12723 Negative = (Opc == UO_Minus);
12724 ExplicitPlus = !Negative;
12725 } else {
12726 return;
12727 }
12728 }
12729
12730 const llvm::APInt &LeftSideValue = LHSInt->getValue();
12731 llvm::APInt RightSideValue = RHSInt->getValue();
12732 if (LeftSideValue != 2 && LeftSideValue != 10)
12733 return;
12734
12735 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12736 return;
12737
12739 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12740 llvm::StringRef ExprStr =
12742
12743 CharSourceRange XorRange =
12745 llvm::StringRef XorStr =
12747 // Do not diagnose if xor keyword/macro is used.
12748 if (XorStr == "xor")
12749 return;
12750
12751 std::string LHSStr = std::string(Lexer::getSourceText(
12752 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12753 S.getSourceManager(), S.getLangOpts()));
12754 std::string RHSStr = std::string(Lexer::getSourceText(
12755 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12756 S.getSourceManager(), S.getLangOpts()));
12757
12758 if (Negative) {
12759 RightSideValue = -RightSideValue;
12760 RHSStr = "-" + RHSStr;
12761 } else if (ExplicitPlus) {
12762 RHSStr = "+" + RHSStr;
12763 }
12764
12765 StringRef LHSStrRef = LHSStr;
12766 StringRef RHSStrRef = RHSStr;
12767 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12768 // literals.
12769 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
12770 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
12771 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
12772 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
12773 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
12774 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
12775 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12776 return;
12777
12778 bool SuggestXor =
12779 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12780 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12781 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12782 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12783 std::string SuggestedExpr = "1 << " + RHSStr;
12784 bool Overflow = false;
12785 llvm::APInt One = (LeftSideValue - 1);
12786 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12787 if (Overflow) {
12788 if (RightSideIntValue < 64)
12789 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12790 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12791 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12792 else if (RightSideIntValue == 64)
12793 S.Diag(Loc, diag::warn_xor_used_as_pow)
12794 << ExprStr << toString(XorValue, 10, true);
12795 else
12796 return;
12797 } else {
12798 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12799 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12800 << toString(PowValue, 10, true)
12802 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12803 }
12804
12805 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12806 << ("0x2 ^ " + RHSStr) << SuggestXor;
12807 } else if (LeftSideValue == 10) {
12808 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12809 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12810 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12811 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12812 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12813 << ("0xA ^ " + RHSStr) << SuggestXor;
12814 }
12815}
12816
12819 // Ensure that either both operands are of the same vector type, or
12820 // one operand is of a vector type and the other is of its element type.
12821 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12822 /*AllowBothBool*/ true,
12823 /*AllowBoolConversions*/ false,
12824 /*AllowBooleanOperation*/ false,
12825 /*ReportInvalid*/ false);
12826 if (vType.isNull())
12827 return InvalidOperands(Loc, LHS, RHS);
12828 if (getLangOpts().OpenCL &&
12829 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12831 return InvalidOperands(Loc, LHS, RHS);
12832 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12833 // usage of the logical operators && and || with vectors in C. This
12834 // check could be notionally dropped.
12835 if (!getLangOpts().CPlusPlus &&
12836 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12837 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12838
12839 return GetSignedVectorType(LHS.get()->getType());
12840}
12841
12844 bool IsCompAssign) {
12845 if (!IsCompAssign) {
12847 if (LHS.isInvalid())
12848 return QualType();
12849 }
12851 if (RHS.isInvalid())
12852 return QualType();
12853
12854 // For conversion purposes, we ignore any qualifiers.
12855 // For example, "const float" and "float" are equivalent.
12856 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12857 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12858
12859 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12860 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12861 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12862
12863 if (Context.hasSameType(LHSType, RHSType))
12864 return Context.getCommonSugaredType(LHSType, RHSType);
12865
12866 // Type conversion may change LHS/RHS. Keep copies to the original results, in
12867 // case we have to return InvalidOperands.
12868 ExprResult OriginalLHS = LHS;
12869 ExprResult OriginalRHS = RHS;
12870 if (LHSMatType && !RHSMatType) {
12871 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12872 if (!RHS.isInvalid())
12873 return LHSType;
12874
12875 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12876 }
12877
12878 if (!LHSMatType && RHSMatType) {
12879 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12880 if (!LHS.isInvalid())
12881 return RHSType;
12882 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12883 }
12884
12885 return InvalidOperands(Loc, LHS, RHS);
12886}
12887
12890 bool IsCompAssign) {
12891 if (!IsCompAssign) {
12893 if (LHS.isInvalid())
12894 return QualType();
12895 }
12897 if (RHS.isInvalid())
12898 return QualType();
12899
12900 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12901 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12902 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12903
12904 if (LHSMatType && RHSMatType) {
12905 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12906 return InvalidOperands(Loc, LHS, RHS);
12907
12908 if (Context.hasSameType(LHSMatType, RHSMatType))
12910 LHS.get()->getType().getUnqualifiedType(),
12911 RHS.get()->getType().getUnqualifiedType());
12912
12913 QualType LHSELTy = LHSMatType->getElementType(),
12914 RHSELTy = RHSMatType->getElementType();
12915 if (!Context.hasSameType(LHSELTy, RHSELTy))
12916 return InvalidOperands(Loc, LHS, RHS);
12917
12919 Context.getCommonSugaredType(LHSELTy, RHSELTy),
12920 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
12921 }
12922 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12923}
12924
12926 switch (Opc) {
12927 default:
12928 return false;
12929 case BO_And:
12930 case BO_AndAssign:
12931 case BO_Or:
12932 case BO_OrAssign:
12933 case BO_Xor:
12934 case BO_XorAssign:
12935 return true;
12936 }
12937}
12938
12941 BinaryOperatorKind Opc) {
12942 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12943
12944 bool IsCompAssign =
12945 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12946
12947 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
12948
12949 if (LHS.get()->getType()->isVectorType() ||
12950 RHS.get()->getType()->isVectorType()) {
12951 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12953 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12954 /*AllowBothBool*/ true,
12955 /*AllowBoolConversions*/ getLangOpts().ZVector,
12956 /*AllowBooleanOperation*/ LegalBoolVecOperator,
12957 /*ReportInvalid*/ true);
12958 return InvalidOperands(Loc, LHS, RHS);
12959 }
12960
12961 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12962 RHS.get()->getType()->isSveVLSBuiltinType()) {
12963 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12965 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
12967 return InvalidOperands(Loc, LHS, RHS);
12968 }
12969
12970 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12971 RHS.get()->getType()->isSveVLSBuiltinType()) {
12972 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12974 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
12976 return InvalidOperands(Loc, LHS, RHS);
12977 }
12978
12979 if (Opc == BO_And)
12980 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12981
12982 if (LHS.get()->getType()->hasFloatingRepresentation() ||
12984 return InvalidOperands(Loc, LHS, RHS);
12985
12986 ExprResult LHSResult = LHS, RHSResult = RHS;
12988 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12989 if (LHSResult.isInvalid() || RHSResult.isInvalid())
12990 return QualType();
12991 LHS = LHSResult.get();
12992 RHS = RHSResult.get();
12993
12994 if (Opc == BO_Xor)
12995 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12996
12997 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12998 return compType;
12999 return InvalidOperands(Loc, LHS, RHS);
13000}
13001
13002// C99 6.5.[13,14]
13005 BinaryOperatorKind Opc) {
13006 // Check vector operands differently.
13007 if (LHS.get()->getType()->isVectorType() ||
13008 RHS.get()->getType()->isVectorType())
13009 return CheckVectorLogicalOperands(LHS, RHS, Loc);
13010
13011 bool EnumConstantInBoolContext = false;
13012 for (const ExprResult &HS : {LHS, RHS}) {
13013 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13014 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13015 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13016 EnumConstantInBoolContext = true;
13017 }
13018 }
13019
13020 if (EnumConstantInBoolContext)
13021 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13022
13023 // WebAssembly tables can't be used with logical operators.
13024 QualType LHSTy = LHS.get()->getType();
13025 QualType RHSTy = RHS.get()->getType();
13026 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13027 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13028 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13029 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13030 return InvalidOperands(Loc, LHS, RHS);
13031 }
13032
13033 // Diagnose cases where the user write a logical and/or but probably meant a
13034 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13035 // is a constant.
13036 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13037 !LHS.get()->getType()->isBooleanType() &&
13038 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13039 // Don't warn in macros or template instantiations.
13041 // If the RHS can be constant folded, and if it constant folds to something
13042 // that isn't 0 or 1 (which indicate a potential logical operation that
13043 // happened to fold to true/false) then warn.
13044 // Parens on the RHS are ignored.
13045 Expr::EvalResult EVResult;
13046 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13047 llvm::APSInt Result = EVResult.Val.getInt();
13048 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13049 !RHS.get()->getExprLoc().isMacroID()) ||
13050 (Result != 0 && Result != 1)) {
13051 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13052 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13053 // Suggest replacing the logical operator with the bitwise version
13054 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13055 << (Opc == BO_LAnd ? "&" : "|")
13058 Opc == BO_LAnd ? "&" : "|");
13059 if (Opc == BO_LAnd)
13060 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13061 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13064 RHS.get()->getEndLoc()));
13065 }
13066 }
13067 }
13068
13069 if (!Context.getLangOpts().CPlusPlus) {
13070 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13071 // not operate on the built-in scalar and vector float types.
13072 if (Context.getLangOpts().OpenCL &&
13073 Context.getLangOpts().OpenCLVersion < 120) {
13074 if (LHS.get()->getType()->isFloatingType() ||
13075 RHS.get()->getType()->isFloatingType())
13076 return InvalidOperands(Loc, LHS, RHS);
13077 }
13078
13079 LHS = UsualUnaryConversions(LHS.get());
13080 if (LHS.isInvalid())
13081 return QualType();
13082
13083 RHS = UsualUnaryConversions(RHS.get());
13084 if (RHS.isInvalid())
13085 return QualType();
13086
13087 if (!LHS.get()->getType()->isScalarType() ||
13088 !RHS.get()->getType()->isScalarType())
13089 return InvalidOperands(Loc, LHS, RHS);
13090
13091 return Context.IntTy;
13092 }
13093
13094 // The following is safe because we only use this method for
13095 // non-overloadable operands.
13096
13097 // C++ [expr.log.and]p1
13098 // C++ [expr.log.or]p1
13099 // The operands are both contextually converted to type bool.
13101 if (LHSRes.isInvalid())
13102 return InvalidOperands(Loc, LHS, RHS);
13103 LHS = LHSRes;
13104
13106 if (RHSRes.isInvalid())
13107 return InvalidOperands(Loc, LHS, RHS);
13108 RHS = RHSRes;
13109
13110 // C++ [expr.log.and]p2
13111 // C++ [expr.log.or]p2
13112 // The result is a bool.
13113 return Context.BoolTy;
13114}
13115
13116static bool IsReadonlyMessage(Expr *E, Sema &S) {
13117 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13118 if (!ME) return false;
13119 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13120 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13122 if (!Base) return false;
13123 return Base->getMethodDecl() != nullptr;
13124}
13125
13126/// Is the given expression (which must be 'const') a reference to a
13127/// variable which was originally non-const, but which has become
13128/// 'const' due to being captured within a block?
13131 assert(E->isLValue() && E->getType().isConstQualified());
13132 E = E->IgnoreParens();
13133
13134 // Must be a reference to a declaration from an enclosing scope.
13135 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13136 if (!DRE) return NCCK_None;
13138
13139 // The declaration must be a variable which is not declared 'const'.
13140 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13141 if (!var) return NCCK_None;
13142 if (var->getType().isConstQualified()) return NCCK_None;
13143 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
13144
13145 // Decide whether the first capture was for a block or a lambda.
13146 DeclContext *DC = S.CurContext, *Prev = nullptr;
13147 // Decide whether the first capture was for a block or a lambda.
13148 while (DC) {
13149 // For init-capture, it is possible that the variable belongs to the
13150 // template pattern of the current context.
13151 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13152 if (var->isInitCapture() &&
13153 FD->getTemplateInstantiationPattern() == var->getDeclContext())
13154 break;
13155 if (DC == var->getDeclContext())
13156 break;
13157 Prev = DC;
13158 DC = DC->getParent();
13159 }
13160 // Unless we have an init-capture, we've gone one step too far.
13161 if (!var->isInitCapture())
13162 DC = Prev;
13163 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13164}
13165
13166static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13167 Ty = Ty.getNonReferenceType();
13168 if (IsDereference && Ty->isPointerType())
13169 Ty = Ty->getPointeeType();
13170 return !Ty.isConstQualified();
13171}
13172
13173// Update err_typecheck_assign_const and note_typecheck_assign_const
13174// when this enum is changed.
13175enum {
13181 ConstUnknown, // Keep as last element
13182};
13183
13184/// Emit the "read-only variable not assignable" error and print notes to give
13185/// more information about why the variable is not assignable, such as pointing
13186/// to the declaration of a const variable, showing that a method is const, or
13187/// that the function is returning a const reference.
13188static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13190 SourceRange ExprRange = E->getSourceRange();
13191
13192 // Only emit one error on the first const found. All other consts will emit
13193 // a note to the error.
13194 bool DiagnosticEmitted = false;
13195
13196 // Track if the current expression is the result of a dereference, and if the
13197 // next checked expression is the result of a dereference.
13198 bool IsDereference = false;
13199 bool NextIsDereference = false;
13200
13201 // Loop to process MemberExpr chains.
13202 while (true) {
13203 IsDereference = NextIsDereference;
13204
13206 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13207 NextIsDereference = ME->isArrow();
13208 const ValueDecl *VD = ME->getMemberDecl();
13209 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13210 // Mutable fields can be modified even if the class is const.
13211 if (Field->isMutable()) {
13212 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13213 break;
13214 }
13215
13216 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13217 if (!DiagnosticEmitted) {
13218 S.Diag(Loc, diag::err_typecheck_assign_const)
13219 << ExprRange << ConstMember << false /*static*/ << Field
13220 << Field->getType();
13221 DiagnosticEmitted = true;
13222 }
13223 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13224 << ConstMember << false /*static*/ << Field << Field->getType()
13225 << Field->getSourceRange();
13226 }
13227 E = ME->getBase();
13228 continue;
13229 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13230 if (VDecl->getType().isConstQualified()) {
13231 if (!DiagnosticEmitted) {
13232 S.Diag(Loc, diag::err_typecheck_assign_const)
13233 << ExprRange << ConstMember << true /*static*/ << VDecl
13234 << VDecl->getType();
13235 DiagnosticEmitted = true;
13236 }
13237 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13238 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13239 << VDecl->getSourceRange();
13240 }
13241 // Static fields do not inherit constness from parents.
13242 break;
13243 }
13244 break; // End MemberExpr
13245 } else if (const ArraySubscriptExpr *ASE =
13246 dyn_cast<ArraySubscriptExpr>(E)) {
13247 E = ASE->getBase()->IgnoreParenImpCasts();
13248 continue;
13249 } else if (const ExtVectorElementExpr *EVE =
13250 dyn_cast<ExtVectorElementExpr>(E)) {
13251 E = EVE->getBase()->IgnoreParenImpCasts();
13252 continue;
13253 }
13254 break;
13255 }
13256
13257 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13258 // Function calls
13259 const FunctionDecl *FD = CE->getDirectCallee();
13260 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13261 if (!DiagnosticEmitted) {
13262 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13263 << ConstFunction << FD;
13264 DiagnosticEmitted = true;
13265 }
13267 diag::note_typecheck_assign_const)
13268 << ConstFunction << FD << FD->getReturnType()
13269 << FD->getReturnTypeSourceRange();
13270 }
13271 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13272 // Point to variable declaration.
13273 if (const ValueDecl *VD = DRE->getDecl()) {
13274 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13275 if (!DiagnosticEmitted) {
13276 S.Diag(Loc, diag::err_typecheck_assign_const)
13277 << ExprRange << ConstVariable << VD << VD->getType();
13278 DiagnosticEmitted = true;
13279 }
13280 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13281 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13282 }
13283 }
13284 } else if (isa<CXXThisExpr>(E)) {
13285 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13286 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13287 if (MD->isConst()) {
13288 if (!DiagnosticEmitted) {
13289 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13290 << ConstMethod << MD;
13291 DiagnosticEmitted = true;
13292 }
13293 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13294 << ConstMethod << MD << MD->getSourceRange();
13295 }
13296 }
13297 }
13298 }
13299
13300 if (DiagnosticEmitted)
13301 return;
13302
13303 // Can't determine a more specific message, so display the generic error.
13304 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13305}
13306
13312
13314 const RecordType *Ty,
13316 OriginalExprKind OEK,
13317 bool &DiagnosticEmitted) {
13318 std::vector<const RecordType *> RecordTypeList;
13319 RecordTypeList.push_back(Ty);
13320 unsigned NextToCheckIndex = 0;
13321 // We walk the record hierarchy breadth-first to ensure that we print
13322 // diagnostics in field nesting order.
13323 while (RecordTypeList.size() > NextToCheckIndex) {
13324 bool IsNested = NextToCheckIndex > 0;
13325 for (const FieldDecl *Field :
13326 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13327 // First, check every field for constness.
13328 QualType FieldTy = Field->getType();
13329 if (FieldTy.isConstQualified()) {
13330 if (!DiagnosticEmitted) {
13331 S.Diag(Loc, diag::err_typecheck_assign_const)
13332 << Range << NestedConstMember << OEK << VD
13333 << IsNested << Field;
13334 DiagnosticEmitted = true;
13335 }
13336 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13337 << NestedConstMember << IsNested << Field
13338 << FieldTy << Field->getSourceRange();
13339 }
13340
13341 // Then we append it to the list to check next in order.
13342 FieldTy = FieldTy.getCanonicalType();
13343 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13344 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13345 RecordTypeList.push_back(FieldRecTy);
13346 }
13347 }
13348 ++NextToCheckIndex;
13349 }
13350}
13351
13352/// Emit an error for the case where a record we are trying to assign to has a
13353/// const-qualified field somewhere in its hierarchy.
13356 QualType Ty = E->getType();
13357 assert(Ty->isRecordType() && "lvalue was not record?");
13359 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13360 bool DiagEmitted = false;
13361
13362 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13363 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13364 Range, OEK_Member, DiagEmitted);
13365 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13366 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13367 Range, OEK_Variable, DiagEmitted);
13368 else
13369 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13370 Range, OEK_LValue, DiagEmitted);
13371 if (!DiagEmitted)
13373}
13374
13375/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13376/// emit an error and return true. If so, return false.
13378 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13379
13381
13382 SourceLocation OrigLoc = Loc;
13384 &Loc);
13385 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13387 if (IsLV == Expr::MLV_Valid)
13388 return false;
13389
13390 unsigned DiagID = 0;
13391 bool NeedType = false;
13392 switch (IsLV) { // C99 6.5.16p2
13394 // Use a specialized diagnostic when we're assigning to an object
13395 // from an enclosing function or block.
13397 if (NCCK == NCCK_Block)
13398 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13399 else
13400 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13401 break;
13402 }
13403
13404 // In ARC, use some specialized diagnostics for occasions where we
13405 // infer 'const'. These are always pseudo-strong variables.
13406 if (S.getLangOpts().ObjCAutoRefCount) {
13407 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13408 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13409 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13410
13411 // Use the normal diagnostic if it's pseudo-__strong but the
13412 // user actually wrote 'const'.
13413 if (var->isARCPseudoStrong() &&
13414 (!var->getTypeSourceInfo() ||
13415 !var->getTypeSourceInfo()->getType().isConstQualified())) {
13416 // There are three pseudo-strong cases:
13417 // - self
13418 ObjCMethodDecl *method = S.getCurMethodDecl();
13419 if (method && var == method->getSelfDecl()) {
13420 DiagID = method->isClassMethod()
13421 ? diag::err_typecheck_arc_assign_self_class_method
13422 : diag::err_typecheck_arc_assign_self;
13423
13424 // - Objective-C externally_retained attribute.
13425 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13426 isa<ParmVarDecl>(var)) {
13427 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13428
13429 // - fast enumeration variables
13430 } else {
13431 DiagID = diag::err_typecheck_arr_assign_enumeration;
13432 }
13433
13434 SourceRange Assign;
13435 if (Loc != OrigLoc)
13436 Assign = SourceRange(OrigLoc, OrigLoc);
13437 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13438 // We need to preserve the AST regardless, so migration tool
13439 // can do its job.
13440 return false;
13441 }
13442 }
13443 }
13444
13445 // If none of the special cases above are triggered, then this is a
13446 // simple const assignment.
13447 if (DiagID == 0) {
13449 return true;
13450 }
13451
13452 break;
13455 return true;
13458 return true;
13461 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13462 NeedType = true;
13463 break;
13465 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13466 NeedType = true;
13467 break;
13469 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13470 break;
13471 case Expr::MLV_Valid:
13472 llvm_unreachable("did not take early return for MLV_Valid");
13476 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13477 break;
13480 return S.RequireCompleteType(Loc, E->getType(),
13481 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13483 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13484 break;
13486 llvm_unreachable("readonly properties should be processed differently");
13488 DiagID = diag::err_readonly_message_assignment;
13489 break;
13491 DiagID = diag::err_no_subobject_property_setting;
13492 break;
13493 }
13494
13495 SourceRange Assign;
13496 if (Loc != OrigLoc)
13497 Assign = SourceRange(OrigLoc, OrigLoc);
13498 if (NeedType)
13499 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13500 else
13501 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13502 return true;
13503}
13504
13505static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13507 Sema &Sema) {
13509 return;
13511 return;
13512 if (Loc.isInvalid() || Loc.isMacroID())
13513 return;
13514 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13515 return;
13516
13517 // C / C++ fields
13518 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13519 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13520 if (ML && MR) {
13521 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13522 return;
13523 const ValueDecl *LHSDecl =
13524 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13525 const ValueDecl *RHSDecl =
13526 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13527 if (LHSDecl != RHSDecl)
13528 return;
13529 if (LHSDecl->getType().isVolatileQualified())
13530 return;
13531 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13532 if (RefTy->getPointeeType().isVolatileQualified())
13533 return;
13534
13535 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13536 }
13537
13538 // Objective-C instance variables
13539 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13540 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13541 if (OL && OR && OL->getDecl() == OR->getDecl()) {
13542 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13543 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13544 if (RL && RR && RL->getDecl() == RR->getDecl())
13545 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13546 }
13547}
13548
13549// C99 6.5.16.1
13552 QualType CompoundType,
13553 BinaryOperatorKind Opc) {
13554 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13555
13556 // Verify that LHS is a modifiable lvalue, and emit error if not.
13557 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13558 return QualType();
13559
13560 QualType LHSType = LHSExpr->getType();
13561 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13562 CompoundType;
13563 // OpenCL v1.2 s6.1.1.1 p2:
13564 // The half data type can only be used to declare a pointer to a buffer that
13565 // contains half values
13566 if (getLangOpts().OpenCL &&
13567 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13568 LHSType->isHalfType()) {
13569 Diag(Loc, diag::err_opencl_half_load_store) << 1
13570 << LHSType.getUnqualifiedType();
13571 return QualType();
13572 }
13573
13574 // WebAssembly tables can't be used on RHS of an assignment expression.
13575 if (RHSType->isWebAssemblyTableType()) {
13576 Diag(Loc, diag::err_wasm_table_art) << 0;
13577 return QualType();
13578 }
13579
13580 AssignConvertType ConvTy;
13581 if (CompoundType.isNull()) {
13582 Expr *RHSCheck = RHS.get();
13583
13584 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13585
13586 QualType LHSTy(LHSType);
13587 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13588 if (RHS.isInvalid())
13589 return QualType();
13590 // Special case of NSObject attributes on c-style pointer types.
13591 if (ConvTy == IncompatiblePointer &&
13592 ((Context.isObjCNSObjectType(LHSType) &&
13593 RHSType->isObjCObjectPointerType()) ||
13594 (Context.isObjCNSObjectType(RHSType) &&
13595 LHSType->isObjCObjectPointerType())))
13596 ConvTy = Compatible;
13597
13598 if (ConvTy == Compatible &&
13599 LHSType->isObjCObjectType())
13600 Diag(Loc, diag::err_objc_object_assignment)
13601 << LHSType;
13602
13603 // If the RHS is a unary plus or minus, check to see if they = and + are
13604 // right next to each other. If so, the user may have typo'd "x =+ 4"
13605 // instead of "x += 4".
13606 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13607 RHSCheck = ICE->getSubExpr();
13608 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13609 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13610 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13611 // Only if the two operators are exactly adjacent.
13612 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13613 // And there is a space or other character before the subexpr of the
13614 // unary +/-. We don't want to warn on "x=-1".
13615 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13616 UO->getSubExpr()->getBeginLoc().isFileID()) {
13617 Diag(Loc, diag::warn_not_compound_assign)
13618 << (UO->getOpcode() == UO_Plus ? "+" : "-")
13619 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13620 }
13621 }
13622
13623 if (ConvTy == Compatible) {
13624 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13625 // Warn about retain cycles where a block captures the LHS, but
13626 // not if the LHS is a simple variable into which the block is
13627 // being stored...unless that variable can be captured by reference!
13628 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13629 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13630 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13631 ObjC().checkRetainCycles(LHSExpr, RHS.get());
13632 }
13633
13634 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13636 // It is safe to assign a weak reference into a strong variable.
13637 // Although this code can still have problems:
13638 // id x = self.weakProp;
13639 // id y = self.weakProp;
13640 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13641 // paths through the function. This should be revisited if
13642 // -Wrepeated-use-of-weak is made flow-sensitive.
13643 // For ObjCWeak only, we do not warn if the assign is to a non-weak
13644 // variable, which will be valid for the current autorelease scope.
13645 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13646 RHS.get()->getBeginLoc()))
13648
13649 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13650 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13651 }
13652 }
13653 } else {
13654 // Compound assignment "x += y"
13655 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13656 }
13657
13658 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13659 RHS.get(), AA_Assigning))
13660 return QualType();
13661
13662 CheckForNullPointerDereference(*this, LHSExpr);
13663
13664 AssignedEntity AE{LHSExpr};
13665 checkExprLifetime(*this, AE, RHS.get());
13666
13667 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13668 if (CompoundType.isNull()) {
13669 // C++2a [expr.ass]p5:
13670 // A simple-assignment whose left operand is of a volatile-qualified
13671 // type is deprecated unless the assignment is either a discarded-value
13672 // expression or an unevaluated operand
13673 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13674 }
13675 }
13676
13677 // C11 6.5.16p3: The type of an assignment expression is the type of the
13678 // left operand would have after lvalue conversion.
13679 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13680 // qualified type, the value has the unqualified version of the type of the
13681 // lvalue; additionally, if the lvalue has atomic type, the value has the
13682 // non-atomic version of the type of the lvalue.
13683 // C++ 5.17p1: the type of the assignment expression is that of its left
13684 // operand.
13685 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13686}
13687
13688// Scenarios to ignore if expression E is:
13689// 1. an explicit cast expression into void
13690// 2. a function call expression that returns void
13691static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
13692 E = E->IgnoreParens();
13693
13694 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13695 if (CE->getCastKind() == CK_ToVoid) {
13696 return true;
13697 }
13698
13699 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13700 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13701 CE->getSubExpr()->getType()->isDependentType()) {
13702 return true;
13703 }
13704 }
13705
13706 if (const auto *CE = dyn_cast<CallExpr>(E))
13707 return CE->getCallReturnType(Context)->isVoidType();
13708 return false;
13709}
13710
13712 // No warnings in macros
13713 if (Loc.isMacroID())
13714 return;
13715
13716 // Don't warn in template instantiations.
13718 return;
13719
13720 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13721 // instead, skip more than needed, then call back into here with the
13722 // CommaVisitor in SemaStmt.cpp.
13723 // The listed locations are the initialization and increment portions
13724 // of a for loop. The additional checks are on the condition of
13725 // if statements, do/while loops, and for loops.
13726 // Differences in scope flags for C89 mode requires the extra logic.
13727 const unsigned ForIncrementFlags =
13728 getLangOpts().C99 || getLangOpts().CPlusPlus
13731 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13732 const unsigned ScopeFlags = getCurScope()->getFlags();
13733 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13734 (ScopeFlags & ForInitFlags) == ForInitFlags)
13735 return;
13736
13737 // If there are multiple comma operators used together, get the RHS of the
13738 // of the comma operator as the LHS.
13739 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13740 if (BO->getOpcode() != BO_Comma)
13741 break;
13742 LHS = BO->getRHS();
13743 }
13744
13745 // Only allow some expressions on LHS to not warn.
13746 if (IgnoreCommaOperand(LHS, Context))
13747 return;
13748
13749 Diag(Loc, diag::warn_comma_operator);
13750 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13751 << LHS->getSourceRange()
13753 LangOpts.CPlusPlus ? "static_cast<void>("
13754 : "(void)(")
13756 ")");
13757}
13758
13759// C99 6.5.17
13762 LHS = S.CheckPlaceholderExpr(LHS.get());
13763 RHS = S.CheckPlaceholderExpr(RHS.get());
13764 if (LHS.isInvalid() || RHS.isInvalid())
13765 return QualType();
13766
13767 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13768 // operands, but not unary promotions.
13769 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13770
13771 // So we treat the LHS as a ignored value, and in C++ we allow the
13772 // containing site to determine what should be done with the RHS.
13773 LHS = S.IgnoredValueConversions(LHS.get());
13774 if (LHS.isInvalid())
13775 return QualType();
13776
13777 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13778
13779 if (!S.getLangOpts().CPlusPlus) {
13781 if (RHS.isInvalid())
13782 return QualType();
13783 if (!RHS.get()->getType()->isVoidType())
13784 S.RequireCompleteType(Loc, RHS.get()->getType(),
13785 diag::err_incomplete_type);
13786 }
13787
13788 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13789 S.DiagnoseCommaOperator(LHS.get(), Loc);
13790
13791 return RHS.get()->getType();
13792}
13793
13794/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13795/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13797 ExprValueKind &VK,
13798 ExprObjectKind &OK,
13799 SourceLocation OpLoc, bool IsInc,
13800 bool IsPrefix) {
13801 QualType ResType = Op->getType();
13802 // Atomic types can be used for increment / decrement where the non-atomic
13803 // versions can, so ignore the _Atomic() specifier for the purpose of
13804 // checking.
13805 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13806 ResType = ResAtomicType->getValueType();
13807
13808 assert(!ResType.isNull() && "no type for increment/decrement expression");
13809
13810 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13811 // Decrement of bool is not allowed.
13812 if (!IsInc) {
13813 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13814 return QualType();
13815 }
13816 // Increment of bool sets it to true, but is deprecated.
13817 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13818 : diag::warn_increment_bool)
13819 << Op->getSourceRange();
13820 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13821 // Error on enum increments and decrements in C++ mode
13822 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13823 return QualType();
13824 } else if (ResType->isRealType()) {
13825 // OK!
13826 } else if (ResType->isPointerType()) {
13827 // C99 6.5.2.4p2, 6.5.6p2
13828 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13829 return QualType();
13830 } else if (ResType->isObjCObjectPointerType()) {
13831 // On modern runtimes, ObjC pointer arithmetic is forbidden.
13832 // Otherwise, we just need a complete type.
13833 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13834 checkArithmeticOnObjCPointer(S, OpLoc, Op))
13835 return QualType();
13836 } else if (ResType->isAnyComplexType()) {
13837 // C99 does not support ++/-- on complex types, we allow as an extension.
13838 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
13839 : diag::ext_c2y_increment_complex)
13840 << IsInc << Op->getSourceRange();
13841 } else if (ResType->isPlaceholderType()) {
13843 if (PR.isInvalid()) return QualType();
13844 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13845 IsInc, IsPrefix);
13846 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13847 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13848 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13849 (ResType->castAs<VectorType>()->getVectorKind() !=
13851 // The z vector extensions allow ++ and -- for non-bool vectors.
13852 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
13853 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13854 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13855 } else {
13856 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13857 << ResType << int(IsInc) << Op->getSourceRange();
13858 return QualType();
13859 }
13860 // At this point, we know we have a real, complex or pointer type.
13861 // Now make sure the operand is a modifiable lvalue.
13862 if (CheckForModifiableLvalue(Op, OpLoc, S))
13863 return QualType();
13864 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13865 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13866 // An operand with volatile-qualified type is deprecated
13867 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13868 << IsInc << ResType;
13869 }
13870 // In C++, a prefix increment is the same type as the operand. Otherwise
13871 // (in C or with postfix), the increment is the unqualified type of the
13872 // operand.
13873 if (IsPrefix && S.getLangOpts().CPlusPlus) {
13874 VK = VK_LValue;
13875 OK = Op->getObjectKind();
13876 return ResType;
13877 } else {
13878 VK = VK_PRValue;
13879 return ResType.getUnqualifiedType();
13880 }
13881}
13882
13883/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13884/// This routine allows us to typecheck complex/recursive expressions
13885/// where the declaration is needed for type checking. We only need to
13886/// handle cases when the expression references a function designator
13887/// or is an lvalue. Here are some examples:
13888/// - &(x) => x
13889/// - &*****f => f for f a function designator.
13890/// - &s.xx => s
13891/// - &s.zz[1].yy -> s, if zz is an array
13892/// - *(x + 1) -> x, if x is an array
13893/// - &"123"[2] -> 0
13894/// - & __real__ x -> x
13895///
13896/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13897/// members.
13899 switch (E->getStmtClass()) {
13900 case Stmt::DeclRefExprClass:
13901 return cast<DeclRefExpr>(E)->getDecl();
13902 case Stmt::MemberExprClass:
13903 // If this is an arrow operator, the address is an offset from
13904 // the base's value, so the object the base refers to is
13905 // irrelevant.
13906 if (cast<MemberExpr>(E)->isArrow())
13907 return nullptr;
13908 // Otherwise, the expression refers to a part of the base
13909 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13910 case Stmt::ArraySubscriptExprClass: {
13911 // FIXME: This code shouldn't be necessary! We should catch the implicit
13912 // promotion of register arrays earlier.
13913 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13914 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13915 if (ICE->getSubExpr()->getType()->isArrayType())
13916 return getPrimaryDecl(ICE->getSubExpr());
13917 }
13918 return nullptr;
13919 }
13920 case Stmt::UnaryOperatorClass: {
13921 UnaryOperator *UO = cast<UnaryOperator>(E);
13922
13923 switch(UO->getOpcode()) {
13924 case UO_Real:
13925 case UO_Imag:
13926 case UO_Extension:
13927 return getPrimaryDecl(UO->getSubExpr());
13928 default:
13929 return nullptr;
13930 }
13931 }
13932 case Stmt::ParenExprClass:
13933 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13934 case Stmt::ImplicitCastExprClass:
13935 // If the result of an implicit cast is an l-value, we care about
13936 // the sub-expression; otherwise, the result here doesn't matter.
13937 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13938 case Stmt::CXXUuidofExprClass:
13939 return cast<CXXUuidofExpr>(E)->getGuidDecl();
13940 default:
13941 return nullptr;
13942 }
13943}
13944
13945namespace {
13946enum {
13947 AO_Bit_Field = 0,
13948 AO_Vector_Element = 1,
13949 AO_Property_Expansion = 2,
13950 AO_Register_Variable = 3,
13951 AO_Matrix_Element = 4,
13952 AO_No_Error = 5
13953};
13954}
13955/// Diagnose invalid operand for address of operations.
13956///
13957/// \param Type The type of operand which cannot have its address taken.
13959 Expr *E, unsigned Type) {
13960 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13961}
13962
13964 const Expr *Op,
13965 const CXXMethodDecl *MD) {
13966 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
13967
13968 if (Op != DRE)
13969 return Diag(OpLoc, diag::err_parens_pointer_member_function)
13970 << Op->getSourceRange();
13971
13972 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13973 if (isa<CXXDestructorDecl>(MD))
13974 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
13975 << DRE->getSourceRange();
13976
13977 if (DRE->getQualifier())
13978 return false;
13979
13980 if (MD->getParent()->getName().empty())
13981 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13982 << DRE->getSourceRange();
13983
13984 SmallString<32> Str;
13985 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13986 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13987 << DRE->getSourceRange()
13988 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
13989}
13990
13992 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13993 if (PTy->getKind() == BuiltinType::Overload) {
13994 Expr *E = OrigOp.get()->IgnoreParens();
13995 if (!isa<OverloadExpr>(E)) {
13996 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13997 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13998 << OrigOp.get()->getSourceRange();
13999 return QualType();
14000 }
14001
14002 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14003 if (isa<UnresolvedMemberExpr>(Ovl))
14005 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14006 << OrigOp.get()->getSourceRange();
14007 return QualType();
14008 }
14009
14010 return Context.OverloadTy;
14011 }
14012
14013 if (PTy->getKind() == BuiltinType::UnknownAny)
14014 return Context.UnknownAnyTy;
14015
14016 if (PTy->getKind() == BuiltinType::BoundMember) {
14017 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14018 << OrigOp.get()->getSourceRange();
14019 return QualType();
14020 }
14021
14022 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14023 if (OrigOp.isInvalid()) return QualType();
14024 }
14025
14026 if (OrigOp.get()->isTypeDependent())
14027 return Context.DependentTy;
14028
14029 assert(!OrigOp.get()->hasPlaceholderType());
14030
14031 // Make sure to ignore parentheses in subsequent checks
14032 Expr *op = OrigOp.get()->IgnoreParens();
14033
14034 // In OpenCL captures for blocks called as lambda functions
14035 // are located in the private address space. Blocks used in
14036 // enqueue_kernel can be located in a different address space
14037 // depending on a vendor implementation. Thus preventing
14038 // taking an address of the capture to avoid invalid AS casts.
14039 if (LangOpts.OpenCL) {
14040 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14041 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14042 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14043 return QualType();
14044 }
14045 }
14046
14047 if (getLangOpts().C99) {
14048 // Implement C99-only parts of addressof rules.
14049 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14050 if (uOp->getOpcode() == UO_Deref)
14051 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14052 // (assuming the deref expression is valid).
14053 return uOp->getSubExpr()->getType();
14054 }
14055 // Technically, there should be a check for array subscript
14056 // expressions here, but the result of one is always an lvalue anyway.
14057 }
14058 ValueDecl *dcl = getPrimaryDecl(op);
14059
14060 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14061 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14062 op->getBeginLoc()))
14063 return QualType();
14064
14066 unsigned AddressOfError = AO_No_Error;
14067
14068 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14069 bool sfinae = (bool)isSFINAEContext();
14070 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14071 : diag::ext_typecheck_addrof_temporary)
14072 << op->getType() << op->getSourceRange();
14073 if (sfinae)
14074 return QualType();
14075 // Materialize the temporary as an lvalue so that we can take its address.
14076 OrigOp = op =
14077 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14078 } else if (isa<ObjCSelectorExpr>(op)) {
14079 return Context.getPointerType(op->getType());
14080 } else if (lval == Expr::LV_MemberFunction) {
14081 // If it's an instance method, make a member pointer.
14082 // The expression must have exactly the form &A::foo.
14083
14084 // If the underlying expression isn't a decl ref, give up.
14085 if (!isa<DeclRefExpr>(op)) {
14086 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14087 << OrigOp.get()->getSourceRange();
14088 return QualType();
14089 }
14090 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14091 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14092
14093 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14094
14097
14098 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14099 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14100 // When pointer authentication is enabled, argument and return types of
14101 // vitual member functions must be complete. This is because vitrual
14102 // member function pointers are implemented using virtual dispatch
14103 // thunks and the thunks cannot be emitted if the argument or return
14104 // types are incomplete.
14105 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14106 SourceLocation DeclRefLoc,
14107 SourceLocation RetArgTypeLoc) {
14108 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
14109 Diag(DeclRefLoc,
14110 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14111 Diag(RetArgTypeLoc,
14112 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14113 << T;
14114 return true;
14115 }
14116 return false;
14117 };
14118 QualType RetTy = MD->getReturnType();
14119 bool IsIncomplete =
14120 !RetTy->isVoidType() &&
14121 ReturnOrParamTypeIsIncomplete(
14122 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14123 for (auto *PVD : MD->parameters())
14124 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14125 PVD->getBeginLoc());
14126 if (IsIncomplete)
14127 return QualType();
14128 }
14129
14130 // Under the MS ABI, lock down the inheritance model now.
14132 (void)isCompleteType(OpLoc, MPTy);
14133 return MPTy;
14134 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14135 // C99 6.5.3.2p1
14136 // The operand must be either an l-value or a function designator
14137 if (!op->getType()->isFunctionType()) {
14138 // Use a special diagnostic for loads from property references.
14139 if (isa<PseudoObjectExpr>(op)) {
14140 AddressOfError = AO_Property_Expansion;
14141 } else {
14142 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14143 << op->getType() << op->getSourceRange();
14144 return QualType();
14145 }
14146 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14147 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14148 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14149 }
14150
14151 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14152 // The operand cannot be a bit-field
14153 AddressOfError = AO_Bit_Field;
14154 } else if (op->getObjectKind() == OK_VectorComponent) {
14155 // The operand cannot be an element of a vector
14156 AddressOfError = AO_Vector_Element;
14157 } else if (op->getObjectKind() == OK_MatrixComponent) {
14158 // The operand cannot be an element of a matrix.
14159 AddressOfError = AO_Matrix_Element;
14160 } else if (dcl) { // C99 6.5.3.2p1
14161 // We have an lvalue with a decl. Make sure the decl is not declared
14162 // with the register storage-class specifier.
14163 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14164 // in C++ it is not error to take address of a register
14165 // variable (c++03 7.1.1P3)
14166 if (vd->getStorageClass() == SC_Register &&
14168 AddressOfError = AO_Register_Variable;
14169 }
14170 } else if (isa<MSPropertyDecl>(dcl)) {
14171 AddressOfError = AO_Property_Expansion;
14172 } else if (isa<FunctionTemplateDecl>(dcl)) {
14173 return Context.OverloadTy;
14174 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14175 // Okay: we can take the address of a field.
14176 // Could be a pointer to member, though, if there is an explicit
14177 // scope qualifier for the class.
14178
14179 // [C++26] [expr.prim.id.general]
14180 // If an id-expression E denotes a non-static non-type member
14181 // of some class C [...] and if E is a qualified-id, E is
14182 // not the un-parenthesized operand of the unary & operator [...]
14183 // the id-expression is transformed into a class member access expression.
14184 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
14185 !isa<ParenExpr>(OrigOp.get())) {
14186 DeclContext *Ctx = dcl->getDeclContext();
14187 if (Ctx && Ctx->isRecord()) {
14188 if (dcl->getType()->isReferenceType()) {
14189 Diag(OpLoc,
14190 diag::err_cannot_form_pointer_to_member_of_reference_type)
14191 << dcl->getDeclName() << dcl->getType();
14192 return QualType();
14193 }
14194
14195 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14196 Ctx = Ctx->getParent();
14197
14199 op->getType(),
14200 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14201 // Under the MS ABI, lock down the inheritance model now.
14203 (void)isCompleteType(OpLoc, MPTy);
14204 return MPTy;
14205 }
14206 }
14209 llvm_unreachable("Unknown/unexpected decl type");
14210 }
14211
14212 if (AddressOfError != AO_No_Error) {
14213 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14214 return QualType();
14215 }
14216
14217 if (lval == Expr::LV_IncompleteVoidType) {
14218 // Taking the address of a void variable is technically illegal, but we
14219 // allow it in cases which are otherwise valid.
14220 // Example: "extern void x; void* y = &x;".
14221 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14222 }
14223
14224 // If the operand has type "type", the result has type "pointer to type".
14225 if (op->getType()->isObjCObjectType())
14227
14228 // Cannot take the address of WebAssembly references or tables.
14229 if (Context.getTargetInfo().getTriple().isWasm()) {
14230 QualType OpTy = op->getType();
14231 if (OpTy.isWebAssemblyReferenceType()) {
14232 Diag(OpLoc, diag::err_wasm_ca_reference)
14233 << 1 << OrigOp.get()->getSourceRange();
14234 return QualType();
14235 }
14236 if (OpTy->isWebAssemblyTableType()) {
14237 Diag(OpLoc, diag::err_wasm_table_pr)
14238 << 1 << OrigOp.get()->getSourceRange();
14239 return QualType();
14240 }
14241 }
14242
14243 CheckAddressOfPackedMember(op);
14244
14245 return Context.getPointerType(op->getType());
14246}
14247
14248static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14249 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14250 if (!DRE)
14251 return;
14252 const Decl *D = DRE->getDecl();
14253 if (!D)
14254 return;
14255 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14256 if (!Param)
14257 return;
14258 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14259 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14260 return;
14261 if (FunctionScopeInfo *FD = S.getCurFunction())
14262 FD->ModifiedNonNullParams.insert(Param);
14263}
14264
14265/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14267 SourceLocation OpLoc,
14268 bool IsAfterAmp = false) {
14269 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14270 if (ConvResult.isInvalid())
14271 return QualType();
14272 Op = ConvResult.get();
14273 QualType OpTy = Op->getType();
14275
14276 if (isa<CXXReinterpretCastExpr>(Op)) {
14277 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14278 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14279 Op->getSourceRange());
14280 }
14281
14282 if (const PointerType *PT = OpTy->getAs<PointerType>())
14283 {
14284 Result = PT->getPointeeType();
14285 }
14286 else if (const ObjCObjectPointerType *OPT =
14288 Result = OPT->getPointeeType();
14289 else {
14291 if (PR.isInvalid()) return QualType();
14292 if (PR.get() != Op)
14293 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14294 }
14295
14296 if (Result.isNull()) {
14297 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14298 << OpTy << Op->getSourceRange();
14299 return QualType();
14300 }
14301
14302 if (Result->isVoidType()) {
14303 // C++ [expr.unary.op]p1:
14304 // [...] the expression to which [the unary * operator] is applied shall
14305 // be a pointer to an object type, or a pointer to a function type
14306 LangOptions LO = S.getLangOpts();
14307 if (LO.CPlusPlus)
14308 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14309 << OpTy << Op->getSourceRange();
14310 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14311 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14312 << OpTy << Op->getSourceRange();
14313 }
14314
14315 // Dereferences are usually l-values...
14316 VK = VK_LValue;
14317
14318 // ...except that certain expressions are never l-values in C.
14319 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14320 VK = VK_PRValue;
14321
14322 return Result;
14323}
14324
14325BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14327 switch (Kind) {
14328 default: llvm_unreachable("Unknown binop!");
14329 case tok::periodstar: Opc = BO_PtrMemD; break;
14330 case tok::arrowstar: Opc = BO_PtrMemI; break;
14331 case tok::star: Opc = BO_Mul; break;
14332 case tok::slash: Opc = BO_Div; break;
14333 case tok::percent: Opc = BO_Rem; break;
14334 case tok::plus: Opc = BO_Add; break;
14335 case tok::minus: Opc = BO_Sub; break;
14336 case tok::lessless: Opc = BO_Shl; break;
14337 case tok::greatergreater: Opc = BO_Shr; break;
14338 case tok::lessequal: Opc = BO_LE; break;
14339 case tok::less: Opc = BO_LT; break;
14340 case tok::greaterequal: Opc = BO_GE; break;
14341 case tok::greater: Opc = BO_GT; break;
14342 case tok::exclaimequal: Opc = BO_NE; break;
14343 case tok::equalequal: Opc = BO_EQ; break;
14344 case tok::spaceship: Opc = BO_Cmp; break;
14345 case tok::amp: Opc = BO_And; break;
14346 case tok::caret: Opc = BO_Xor; break;
14347 case tok::pipe: Opc = BO_Or; break;
14348 case tok::ampamp: Opc = BO_LAnd; break;
14349 case tok::pipepipe: Opc = BO_LOr; break;
14350 case tok::equal: Opc = BO_Assign; break;
14351 case tok::starequal: Opc = BO_MulAssign; break;
14352 case tok::slashequal: Opc = BO_DivAssign; break;
14353 case tok::percentequal: Opc = BO_RemAssign; break;
14354 case tok::plusequal: Opc = BO_AddAssign; break;
14355 case tok::minusequal: Opc = BO_SubAssign; break;
14356 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14357 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14358 case tok::ampequal: Opc = BO_AndAssign; break;
14359 case tok::caretequal: Opc = BO_XorAssign; break;
14360 case tok::pipeequal: Opc = BO_OrAssign; break;
14361 case tok::comma: Opc = BO_Comma; break;
14362 }
14363 return Opc;
14364}
14365
14367 tok::TokenKind Kind) {
14369 switch (Kind) {
14370 default: llvm_unreachable("Unknown unary op!");
14371 case tok::plusplus: Opc = UO_PreInc; break;
14372 case tok::minusminus: Opc = UO_PreDec; break;
14373 case tok::amp: Opc = UO_AddrOf; break;
14374 case tok::star: Opc = UO_Deref; break;
14375 case tok::plus: Opc = UO_Plus; break;
14376 case tok::minus: Opc = UO_Minus; break;
14377 case tok::tilde: Opc = UO_Not; break;
14378 case tok::exclaim: Opc = UO_LNot; break;
14379 case tok::kw___real: Opc = UO_Real; break;
14380 case tok::kw___imag: Opc = UO_Imag; break;
14381 case tok::kw___extension__: Opc = UO_Extension; break;
14382 }
14383 return Opc;
14384}
14385
14386const FieldDecl *
14388 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14389 // common for setters.
14390 // struct A {
14391 // int X;
14392 // -void setX(int X) { X = X; }
14393 // +void setX(int X) { this->X = X; }
14394 // };
14395
14396 // Only consider parameters for self assignment fixes.
14397 if (!isa<ParmVarDecl>(SelfAssigned))
14398 return nullptr;
14399 const auto *Method =
14400 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14401 if (!Method)
14402 return nullptr;
14403
14404 const CXXRecordDecl *Parent = Method->getParent();
14405 // In theory this is fixable if the lambda explicitly captures this, but
14406 // that's added complexity that's rarely going to be used.
14407 if (Parent->isLambda())
14408 return nullptr;
14409
14410 // FIXME: Use an actual Lookup operation instead of just traversing fields
14411 // in order to get base class fields.
14412 auto Field =
14413 llvm::find_if(Parent->fields(),
14414 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14415 return F->getDeclName() == Name;
14416 });
14417 return (Field != Parent->field_end()) ? *Field : nullptr;
14418}
14419
14420/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14421/// This warning suppressed in the event of macro expansions.
14422static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14423 SourceLocation OpLoc, bool IsBuiltin) {
14425 return;
14426 if (S.isUnevaluatedContext())
14427 return;
14428 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14429 return;
14430 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14431 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14432 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14433 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14434 if (!LHSDeclRef || !RHSDeclRef ||
14435 LHSDeclRef->getLocation().isMacroID() ||
14436 RHSDeclRef->getLocation().isMacroID())
14437 return;
14438 const ValueDecl *LHSDecl =
14439 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14440 const ValueDecl *RHSDecl =
14441 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14442 if (LHSDecl != RHSDecl)
14443 return;
14444 if (LHSDecl->getType().isVolatileQualified())
14445 return;
14446 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14447 if (RefTy->getPointeeType().isVolatileQualified())
14448 return;
14449
14450 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14451 : diag::warn_self_assignment_overloaded)
14452 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14453 << RHSExpr->getSourceRange();
14454 if (const FieldDecl *SelfAssignField =
14456 Diag << 1 << SelfAssignField
14457 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14458 else
14459 Diag << 0;
14460}
14461
14462/// Check if a bitwise-& is performed on an Objective-C pointer. This
14463/// is usually indicative of introspection within the Objective-C pointer.
14465 SourceLocation OpLoc) {
14466 if (!S.getLangOpts().ObjC)
14467 return;
14468
14469 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14470 const Expr *LHS = L.get();
14471 const Expr *RHS = R.get();
14472
14474 ObjCPointerExpr = LHS;
14475 OtherExpr = RHS;
14476 }
14477 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14478 ObjCPointerExpr = RHS;
14479 OtherExpr = LHS;
14480 }
14481
14482 // This warning is deliberately made very specific to reduce false
14483 // positives with logic that uses '&' for hashing. This logic mainly
14484 // looks for code trying to introspect into tagged pointers, which
14485 // code should generally never do.
14486 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14487 unsigned Diag = diag::warn_objc_pointer_masking;
14488 // Determine if we are introspecting the result of performSelectorXXX.
14489 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14490 // Special case messages to -performSelector and friends, which
14491 // can return non-pointer values boxed in a pointer value.
14492 // Some clients may wish to silence warnings in this subcase.
14493 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14494 Selector S = ME->getSelector();
14495 StringRef SelArg0 = S.getNameForSlot(0);
14496 if (SelArg0.starts_with("performSelector"))
14497 Diag = diag::warn_objc_pointer_masking_performSelector;
14498 }
14499
14500 S.Diag(OpLoc, Diag)
14501 << ObjCPointerExpr->getSourceRange();
14502 }
14503}
14504
14506 if (!E)
14507 return nullptr;
14508 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14509 return DRE->getDecl();
14510 if (auto *ME = dyn_cast<MemberExpr>(E))
14511 return ME->getMemberDecl();
14512 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14513 return IRE->getDecl();
14514 return nullptr;
14515}
14516
14517// This helper function promotes a binary operator's operands (which are of a
14518// half vector type) to a vector of floats and then truncates the result to
14519// a vector of either half or short.
14521 BinaryOperatorKind Opc, QualType ResultTy,
14523 bool IsCompAssign, SourceLocation OpLoc,
14524 FPOptionsOverride FPFeatures) {
14525 auto &Context = S.getASTContext();
14526 assert((isVector(ResultTy, Context.HalfTy) ||
14527 isVector(ResultTy, Context.ShortTy)) &&
14528 "Result must be a vector of half or short");
14529 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14530 isVector(RHS.get()->getType(), Context.HalfTy) &&
14531 "both operands expected to be a half vector");
14532
14533 RHS = convertVector(RHS.get(), Context.FloatTy, S);
14534 QualType BinOpResTy = RHS.get()->getType();
14535
14536 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14537 // change BinOpResTy to a vector of ints.
14538 if (isVector(ResultTy, Context.ShortTy))
14539 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14540
14541 if (IsCompAssign)
14542 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14543 ResultTy, VK, OK, OpLoc, FPFeatures,
14544 BinOpResTy, BinOpResTy);
14545
14546 LHS = convertVector(LHS.get(), Context.FloatTy, S);
14547 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14548 BinOpResTy, VK, OK, OpLoc, FPFeatures);
14549 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14550}
14551
14552static std::pair<ExprResult, ExprResult>
14554 Expr *RHSExpr) {
14555 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14556 if (!S.Context.isDependenceAllowed()) {
14557 // C cannot handle TypoExpr nodes on either side of a binop because it
14558 // doesn't handle dependent types properly, so make sure any TypoExprs have
14559 // been dealt with before checking the operands.
14560 LHS = S.CorrectDelayedTyposInExpr(LHS);
14562 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14563 [Opc, LHS](Expr *E) {
14564 if (Opc != BO_Assign)
14565 return ExprResult(E);
14566 // Avoid correcting the RHS to the same Expr as the LHS.
14567 Decl *D = getDeclFromExpr(E);
14568 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14569 });
14570 }
14571 return std::make_pair(LHS, RHS);
14572}
14573
14574/// Returns true if conversion between vectors of halfs and vectors of floats
14575/// is needed.
14576static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14577 Expr *E0, Expr *E1 = nullptr) {
14578 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14580 return false;
14581
14582 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14583 QualType Ty = E->IgnoreImplicit()->getType();
14584
14585 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14586 // to vectors of floats. Although the element type of the vectors is __fp16,
14587 // the vectors shouldn't be treated as storage-only types. See the
14588 // discussion here: https://reviews.llvm.org/rG825235c140e7
14589 if (const VectorType *VT = Ty->getAs<VectorType>()) {
14590 if (VT->getVectorKind() == VectorKind::Neon)
14591 return false;
14592 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14593 }
14594 return false;
14595 };
14596
14597 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14598}
14599
14602 Expr *LHSExpr, Expr *RHSExpr) {
14603 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14604 // The syntax only allows initializer lists on the RHS of assignment,
14605 // so we don't need to worry about accepting invalid code for
14606 // non-assignment operators.
14607 // C++11 5.17p9:
14608 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14609 // of x = {} is x = T().
14611 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14612 InitializedEntity Entity =
14614 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14615 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14616 if (Init.isInvalid())
14617 return Init;
14618 RHSExpr = Init.get();
14619 }
14620
14621 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14622 QualType ResultTy; // Result type of the binary operator.
14623 // The following two variables are used for compound assignment operators
14624 QualType CompLHSTy; // Type of LHS after promotions for computation
14625 QualType CompResultTy; // Type of computation result
14628 bool ConvertHalfVec = false;
14629
14630 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14631 if (!LHS.isUsable() || !RHS.isUsable())
14632 return ExprError();
14633
14634 if (getLangOpts().OpenCL) {
14635 QualType LHSTy = LHSExpr->getType();
14636 QualType RHSTy = RHSExpr->getType();
14637 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14638 // the ATOMIC_VAR_INIT macro.
14639 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14640 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14641 if (BO_Assign == Opc)
14642 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14643 else
14644 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14645 return ExprError();
14646 }
14647
14648 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14649 // only with a builtin functions and therefore should be disallowed here.
14650 if (LHSTy->isImageType() || RHSTy->isImageType() ||
14651 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14652 LHSTy->isPipeType() || RHSTy->isPipeType() ||
14653 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14654 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14655 return ExprError();
14656 }
14657 }
14658
14659 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14660 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14661
14662 switch (Opc) {
14663 case BO_Assign:
14664 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
14665 if (getLangOpts().CPlusPlus &&
14666 LHS.get()->getObjectKind() != OK_ObjCProperty) {
14667 VK = LHS.get()->getValueKind();
14668 OK = LHS.get()->getObjectKind();
14669 }
14670 if (!ResultTy.isNull()) {
14671 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14672 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14673
14674 // Avoid copying a block to the heap if the block is assigned to a local
14675 // auto variable that is declared in the same scope as the block. This
14676 // optimization is unsafe if the local variable is declared in an outer
14677 // scope. For example:
14678 //
14679 // BlockTy b;
14680 // {
14681 // b = ^{...};
14682 // }
14683 // // It is unsafe to invoke the block here if it wasn't copied to the
14684 // // heap.
14685 // b();
14686
14687 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14688 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14689 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14690 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14691 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14692
14694 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14696 }
14697 RecordModifiableNonNullParam(*this, LHS.get());
14698 break;
14699 case BO_PtrMemD:
14700 case BO_PtrMemI:
14701 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14702 Opc == BO_PtrMemI);
14703 break;
14704 case BO_Mul:
14705 case BO_Div:
14706 ConvertHalfVec = true;
14707 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14708 Opc == BO_Div);
14709 break;
14710 case BO_Rem:
14711 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14712 break;
14713 case BO_Add:
14714 ConvertHalfVec = true;
14715 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14716 break;
14717 case BO_Sub:
14718 ConvertHalfVec = true;
14719 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14720 break;
14721 case BO_Shl:
14722 case BO_Shr:
14723 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14724 break;
14725 case BO_LE:
14726 case BO_LT:
14727 case BO_GE:
14728 case BO_GT:
14729 ConvertHalfVec = true;
14730 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14731
14732 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
14733 BI && BI->isComparisonOp())
14734 Diag(OpLoc, diag::warn_consecutive_comparison);
14735
14736 break;
14737 case BO_EQ:
14738 case BO_NE:
14739 ConvertHalfVec = true;
14740 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14741 break;
14742 case BO_Cmp:
14743 ConvertHalfVec = true;
14744 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14745 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14746 break;
14747 case BO_And:
14748 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14749 [[fallthrough]];
14750 case BO_Xor:
14751 case BO_Or:
14752 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14753 break;
14754 case BO_LAnd:
14755 case BO_LOr:
14756 ConvertHalfVec = true;
14757 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14758 break;
14759 case BO_MulAssign:
14760 case BO_DivAssign:
14761 ConvertHalfVec = true;
14762 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14763 Opc == BO_DivAssign);
14764 CompLHSTy = CompResultTy;
14765 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14766 ResultTy =
14767 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14768 break;
14769 case BO_RemAssign:
14770 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14771 CompLHSTy = CompResultTy;
14772 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14773 ResultTy =
14774 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14775 break;
14776 case BO_AddAssign:
14777 ConvertHalfVec = true;
14778 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14779 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14780 ResultTy =
14781 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14782 break;
14783 case BO_SubAssign:
14784 ConvertHalfVec = true;
14785 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14786 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14787 ResultTy =
14788 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14789 break;
14790 case BO_ShlAssign:
14791 case BO_ShrAssign:
14792 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14793 CompLHSTy = CompResultTy;
14794 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14795 ResultTy =
14796 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14797 break;
14798 case BO_AndAssign:
14799 case BO_OrAssign: // fallthrough
14800 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14801 [[fallthrough]];
14802 case BO_XorAssign:
14803 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14804 CompLHSTy = CompResultTy;
14805 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14806 ResultTy =
14807 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14808 break;
14809 case BO_Comma:
14810 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14811 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14812 VK = RHS.get()->getValueKind();
14813 OK = RHS.get()->getObjectKind();
14814 }
14815 break;
14816 }
14817 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14818 return ExprError();
14819
14820 // Some of the binary operations require promoting operands of half vector to
14821 // float vectors and truncating the result back to half vector. For now, we do
14822 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14823 // arm64).
14824 assert(
14825 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14826 isVector(LHS.get()->getType(), Context.HalfTy)) &&
14827 "both sides are half vectors or neither sides are");
14828 ConvertHalfVec =
14829 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14830
14831 // Check for array bounds violations for both sides of the BinaryOperator
14832 CheckArrayAccess(LHS.get());
14833 CheckArrayAccess(RHS.get());
14834
14835 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14836 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14837 &Context.Idents.get("object_setClass"),
14839 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14840 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14841 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14843 "object_setClass(")
14844 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14845 ",")
14846 << FixItHint::CreateInsertion(RHSLocEnd, ")");
14847 }
14848 else
14849 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14850 }
14851 else if (const ObjCIvarRefExpr *OIRE =
14852 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14853 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14854
14855 // Opc is not a compound assignment if CompResultTy is null.
14856 if (CompResultTy.isNull()) {
14857 if (ConvertHalfVec)
14858 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14859 OpLoc, CurFPFeatureOverrides());
14860 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14861 VK, OK, OpLoc, CurFPFeatureOverrides());
14862 }
14863
14864 // Handle compound assignments.
14865 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14867 VK = VK_LValue;
14868 OK = LHS.get()->getObjectKind();
14869 }
14870
14871 // The LHS is not converted to the result type for fixed-point compound
14872 // assignment as the common type is computed on demand. Reset the CompLHSTy
14873 // to the LHS type we would have gotten after unary conversions.
14874 if (CompResultTy->isFixedPointType())
14875 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14876
14877 if (ConvertHalfVec)
14878 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14879 OpLoc, CurFPFeatureOverrides());
14880
14882 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14883 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14884}
14885
14886/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14887/// operators are mixed in a way that suggests that the programmer forgot that
14888/// comparison operators have higher precedence. The most typical example of
14889/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14891 SourceLocation OpLoc, Expr *LHSExpr,
14892 Expr *RHSExpr) {
14893 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14894 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14895
14896 // Check that one of the sides is a comparison operator and the other isn't.
14897 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14898 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14899 if (isLeftComp == isRightComp)
14900 return;
14901
14902 // Bitwise operations are sometimes used as eager logical ops.
14903 // Don't diagnose this.
14904 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14905 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14906 if (isLeftBitwise || isRightBitwise)
14907 return;
14908
14909 SourceRange DiagRange = isLeftComp
14910 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14911 : SourceRange(OpLoc, RHSExpr->getEndLoc());
14912 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14913 SourceRange ParensRange =
14914 isLeftComp
14915 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14916 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14917
14918 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14919 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14920 SuggestParentheses(Self, OpLoc,
14921 Self.PDiag(diag::note_precedence_silence) << OpStr,
14922 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14923 SuggestParentheses(Self, OpLoc,
14924 Self.PDiag(diag::note_precedence_bitwise_first)
14926 ParensRange);
14927}
14928
14929/// It accepts a '&&' expr that is inside a '||' one.
14930/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14931/// in parentheses.
14932static void
14934 BinaryOperator *Bop) {
14935 assert(Bop->getOpcode() == BO_LAnd);
14936 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14937 << Bop->getSourceRange() << OpLoc;
14939 Self.PDiag(diag::note_precedence_silence)
14940 << Bop->getOpcodeStr(),
14941 Bop->getSourceRange());
14942}
14943
14944/// Look for '&&' in the left hand of a '||' expr.
14946 Expr *LHSExpr, Expr *RHSExpr) {
14947 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14948 if (Bop->getOpcode() == BO_LAnd) {
14949 // If it's "string_literal && a || b" don't warn since the precedence
14950 // doesn't matter.
14951 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
14952 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14953 } else if (Bop->getOpcode() == BO_LOr) {
14954 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14955 // If it's "a || b && string_literal || c" we didn't warn earlier for
14956 // "a || b && string_literal", but warn now.
14957 if (RBop->getOpcode() == BO_LAnd &&
14958 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
14959 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14960 }
14961 }
14962 }
14963}
14964
14965/// Look for '&&' in the right hand of a '||' expr.
14967 Expr *LHSExpr, Expr *RHSExpr) {
14968 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14969 if (Bop->getOpcode() == BO_LAnd) {
14970 // If it's "a || b && string_literal" don't warn since the precedence
14971 // doesn't matter.
14972 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
14973 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14974 }
14975 }
14976}
14977
14978/// Look for bitwise op in the left or right hand of a bitwise op with
14979/// lower precedence and emit a diagnostic together with a fixit hint that wraps
14980/// the '&' expression in parentheses.
14982 SourceLocation OpLoc, Expr *SubExpr) {
14983 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14984 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14985 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14986 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14987 << Bop->getSourceRange() << OpLoc;
14988 SuggestParentheses(S, Bop->getOperatorLoc(),
14989 S.PDiag(diag::note_precedence_silence)
14990 << Bop->getOpcodeStr(),
14991 Bop->getSourceRange());
14992 }
14993 }
14994}
14995
14997 Expr *SubExpr, StringRef Shift) {
14998 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14999 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15000 StringRef Op = Bop->getOpcodeStr();
15001 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15002 << Bop->getSourceRange() << OpLoc << Shift << Op;
15003 SuggestParentheses(S, Bop->getOperatorLoc(),
15004 S.PDiag(diag::note_precedence_silence) << Op,
15005 Bop->getSourceRange());
15006 }
15007 }
15008}
15009
15011 Expr *LHSExpr, Expr *RHSExpr) {
15012 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15013 if (!OCE)
15014 return;
15015
15016 FunctionDecl *FD = OCE->getDirectCallee();
15017 if (!FD || !FD->isOverloadedOperator())
15018 return;
15019
15021 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15022 return;
15023
15024 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15025 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15026 << (Kind == OO_LessLess);
15028 S.PDiag(diag::note_precedence_silence)
15029 << (Kind == OO_LessLess ? "<<" : ">>"),
15030 OCE->getSourceRange());
15032 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15033 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15034}
15035
15036/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15037/// precedence.
15039 SourceLocation OpLoc, Expr *LHSExpr,
15040 Expr *RHSExpr){
15041 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15043 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15044
15045 // Diagnose "arg1 & arg2 | arg3"
15046 if ((Opc == BO_Or || Opc == BO_Xor) &&
15047 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15048 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15049 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15050 }
15051
15052 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15053 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15054 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15055 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15056 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15057 }
15058
15059 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15060 || Opc == BO_Shr) {
15061 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15062 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15063 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15064 }
15065
15066 // Warn on overloaded shift operators and comparisons, such as:
15067 // cout << 5 == 4;
15069 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15070}
15071
15073 tok::TokenKind Kind,
15074 Expr *LHSExpr, Expr *RHSExpr) {
15075 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15076 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15077 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15078
15079 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15080 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15081
15082 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15083}
15084
15086 UnresolvedSetImpl &Functions) {
15088 if (OverOp != OO_None && OverOp != OO_Equal)
15089 LookupOverloadedOperatorName(OverOp, S, Functions);
15090
15091 // In C++20 onwards, we may have a second operator to look up.
15092 if (getLangOpts().CPlusPlus20) {
15094 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15095 }
15096}
15097
15098/// Build an overloaded binary operator expression in the given scope.
15101 Expr *LHS, Expr *RHS) {
15102 switch (Opc) {
15103 case BO_Assign:
15104 // In the non-overloaded case, we warn about self-assignment (x = x) for
15105 // both simple assignment and certain compound assignments where algebra
15106 // tells us the operation yields a constant result. When the operator is
15107 // overloaded, we can't do the latter because we don't want to assume that
15108 // those algebraic identities still apply; for example, a path-building
15109 // library might use operator/= to append paths. But it's still reasonable
15110 // to assume that simple assignment is just moving/copying values around
15111 // and so self-assignment is likely a bug.
15112 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15113 [[fallthrough]];
15114 case BO_DivAssign:
15115 case BO_RemAssign:
15116 case BO_SubAssign:
15117 case BO_AndAssign:
15118 case BO_OrAssign:
15119 case BO_XorAssign:
15120 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15121 break;
15122 default:
15123 break;
15124 }
15125
15126 // Find all of the overloaded operators visible from this point.
15127 UnresolvedSet<16> Functions;
15128 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15129
15130 // Build the (potentially-overloaded, potentially-dependent)
15131 // binary operation.
15132 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15133}
15134
15137 Expr *LHSExpr, Expr *RHSExpr) {
15138 ExprResult LHS, RHS;
15139 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15140 if (!LHS.isUsable() || !RHS.isUsable())
15141 return ExprError();
15142 LHSExpr = LHS.get();
15143 RHSExpr = RHS.get();
15144
15145 // We want to end up calling one of SemaPseudoObject::checkAssignment
15146 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15147 // both expressions are overloadable or either is type-dependent),
15148 // or CreateBuiltinBinOp (in any other case). We also want to get
15149 // any placeholder types out of the way.
15150
15151 // Handle pseudo-objects in the LHS.
15152 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15153 // Assignments with a pseudo-object l-value need special analysis.
15154 if (pty->getKind() == BuiltinType::PseudoObject &&
15156 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15157
15158 // Don't resolve overloads if the other type is overloadable.
15159 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15160 // We can't actually test that if we still have a placeholder,
15161 // though. Fortunately, none of the exceptions we see in that
15162 // code below are valid when the LHS is an overload set. Note
15163 // that an overload set can be dependently-typed, but it never
15164 // instantiates to having an overloadable type.
15165 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15166 if (resolvedRHS.isInvalid()) return ExprError();
15167 RHSExpr = resolvedRHS.get();
15168
15169 if (RHSExpr->isTypeDependent() ||
15170 RHSExpr->getType()->isOverloadableType())
15171 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15172 }
15173
15174 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15175 // template, diagnose the missing 'template' keyword instead of diagnosing
15176 // an invalid use of a bound member function.
15177 //
15178 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15179 // to C++1z [over.over]/1.4, but we already checked for that case above.
15180 if (Opc == BO_LT && inTemplateInstantiation() &&
15181 (pty->getKind() == BuiltinType::BoundMember ||
15182 pty->getKind() == BuiltinType::Overload)) {
15183 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15184 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15185 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15186 return isa<FunctionTemplateDecl>(ND);
15187 })) {
15188 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15189 : OE->getNameLoc(),
15190 diag::err_template_kw_missing)
15191 << OE->getName().getAsString() << "";
15192 return ExprError();
15193 }
15194 }
15195
15196 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15197 if (LHS.isInvalid()) return ExprError();
15198 LHSExpr = LHS.get();
15199 }
15200
15201 // Handle pseudo-objects in the RHS.
15202 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15203 // An overload in the RHS can potentially be resolved by the type
15204 // being assigned to.
15205 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15206 if (getLangOpts().CPlusPlus &&
15207 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15208 LHSExpr->getType()->isOverloadableType()))
15209 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15210
15211 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15212 }
15213
15214 // Don't resolve overloads if the other type is overloadable.
15215 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15216 LHSExpr->getType()->isOverloadableType())
15217 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15218
15219 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15220 if (!resolvedRHS.isUsable()) return ExprError();
15221 RHSExpr = resolvedRHS.get();
15222 }
15223
15224 if (getLangOpts().CPlusPlus) {
15225 // Otherwise, build an overloaded op if either expression is type-dependent
15226 // or has an overloadable type.
15227 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15228 LHSExpr->getType()->isOverloadableType() ||
15229 RHSExpr->getType()->isOverloadableType())
15230 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15231 }
15232
15233 if (getLangOpts().RecoveryAST &&
15234 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15235 assert(!getLangOpts().CPlusPlus);
15236 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15237 "Should only occur in error-recovery path.");
15239 // C [6.15.16] p3:
15240 // An assignment expression has the value of the left operand after the
15241 // assignment, but is not an lvalue.
15243 Context, LHSExpr, RHSExpr, Opc,
15245 OpLoc, CurFPFeatureOverrides());
15246 QualType ResultType;
15247 switch (Opc) {
15248 case BO_Assign:
15249 ResultType = LHSExpr->getType().getUnqualifiedType();
15250 break;
15251 case BO_LT:
15252 case BO_GT:
15253 case BO_LE:
15254 case BO_GE:
15255 case BO_EQ:
15256 case BO_NE:
15257 case BO_LAnd:
15258 case BO_LOr:
15259 // These operators have a fixed result type regardless of operands.
15260 ResultType = Context.IntTy;
15261 break;
15262 case BO_Comma:
15263 ResultType = RHSExpr->getType();
15264 break;
15265 default:
15266 ResultType = Context.DependentTy;
15267 break;
15268 }
15269 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15270 VK_PRValue, OK_Ordinary, OpLoc,
15272 }
15273
15274 // Build a built-in binary operation.
15275 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15276}
15277
15279 if (T.isNull() || T->isDependentType())
15280 return false;
15281
15282 if (!Ctx.isPromotableIntegerType(T))
15283 return true;
15284
15285 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15286}
15287
15289 UnaryOperatorKind Opc, Expr *InputExpr,
15290 bool IsAfterAmp) {
15291 ExprResult Input = InputExpr;
15294 QualType resultType;
15295 bool CanOverflow = false;
15296
15297 bool ConvertHalfVec = false;
15298 if (getLangOpts().OpenCL) {
15299 QualType Ty = InputExpr->getType();
15300 // The only legal unary operation for atomics is '&'.
15301 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15302 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15303 // only with a builtin functions and therefore should be disallowed here.
15304 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15305 || Ty->isBlockPointerType())) {
15306 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15307 << InputExpr->getType()
15308 << Input.get()->getSourceRange());
15309 }
15310 }
15311
15312 if (getLangOpts().HLSL && OpLoc.isValid()) {
15313 if (Opc == UO_AddrOf)
15314 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15315 if (Opc == UO_Deref)
15316 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15317 }
15318
15319 if (InputExpr->isTypeDependent() &&
15320 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
15321 resultType = Context.DependentTy;
15322 } else {
15323 switch (Opc) {
15324 case UO_PreInc:
15325 case UO_PreDec:
15326 case UO_PostInc:
15327 case UO_PostDec:
15328 resultType =
15329 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
15330 Opc == UO_PreInc || Opc == UO_PostInc,
15331 Opc == UO_PreInc || Opc == UO_PreDec);
15332 CanOverflow = isOverflowingIntegerType(Context, resultType);
15333 break;
15334 case UO_AddrOf:
15335 resultType = CheckAddressOfOperand(Input, OpLoc);
15336 CheckAddressOfNoDeref(InputExpr);
15337 RecordModifiableNonNullParam(*this, InputExpr);
15338 break;
15339 case UO_Deref: {
15341 if (Input.isInvalid())
15342 return ExprError();
15343 resultType =
15344 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15345 break;
15346 }
15347 case UO_Plus:
15348 case UO_Minus:
15349 CanOverflow = Opc == UO_Minus &&
15351 Input = UsualUnaryConversions(Input.get());
15352 if (Input.isInvalid())
15353 return ExprError();
15354 // Unary plus and minus require promoting an operand of half vector to a
15355 // float vector and truncating the result back to a half vector. For now,
15356 // we do this only when HalfArgsAndReturns is set (that is, when the
15357 // target is arm or arm64).
15358 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15359
15360 // If the operand is a half vector, promote it to a float vector.
15361 if (ConvertHalfVec)
15362 Input = convertVector(Input.get(), Context.FloatTy, *this);
15363 resultType = Input.get()->getType();
15364 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15365 break;
15366 else if (resultType->isVectorType() &&
15367 // The z vector extensions don't allow + or - with bool vectors.
15368 (!Context.getLangOpts().ZVector ||
15369 resultType->castAs<VectorType>()->getVectorKind() !=
15371 break;
15372 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
15373 break;
15374 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15375 Opc == UO_Plus && resultType->isPointerType())
15376 break;
15377
15378 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15379 << resultType << Input.get()->getSourceRange());
15380
15381 case UO_Not: // bitwise complement
15382 Input = UsualUnaryConversions(Input.get());
15383 if (Input.isInvalid())
15384 return ExprError();
15385 resultType = Input.get()->getType();
15386 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15387 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15388 // C99 does not support '~' for complex conjugation.
15389 Diag(OpLoc, diag::ext_integer_complement_complex)
15390 << resultType << Input.get()->getSourceRange();
15391 else if (resultType->hasIntegerRepresentation())
15392 break;
15393 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15394 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15395 // on vector float types.
15396 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15397 if (!T->isIntegerType())
15398 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15399 << resultType << Input.get()->getSourceRange());
15400 } else {
15401 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15402 << resultType << Input.get()->getSourceRange());
15403 }
15404 break;
15405
15406 case UO_LNot: // logical negation
15407 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15409 if (Input.isInvalid())
15410 return ExprError();
15411 resultType = Input.get()->getType();
15412
15413 // Though we still have to promote half FP to float...
15414 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15415 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
15416 .get();
15417 resultType = Context.FloatTy;
15418 }
15419
15420 // WebAsembly tables can't be used in unary expressions.
15421 if (resultType->isPointerType() &&
15423 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15424 << resultType << Input.get()->getSourceRange());
15425 }
15426
15427 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15428 // C99 6.5.3.3p1: ok, fallthrough;
15429 if (Context.getLangOpts().CPlusPlus) {
15430 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15431 // operand contextually converted to bool.
15432 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15433 ScalarTypeToBooleanCastKind(resultType));
15434 } else if (Context.getLangOpts().OpenCL &&
15435 Context.getLangOpts().OpenCLVersion < 120) {
15436 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15437 // operate on scalar float types.
15438 if (!resultType->isIntegerType() && !resultType->isPointerType())
15439 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15440 << resultType << Input.get()->getSourceRange());
15441 }
15442 } else if (resultType->isExtVectorType()) {
15443 if (Context.getLangOpts().OpenCL &&
15445 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15446 // operate on vector float types.
15447 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15448 if (!T->isIntegerType())
15449 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15450 << resultType << Input.get()->getSourceRange());
15451 }
15452 // Vector logical not returns the signed variant of the operand type.
15453 resultType = GetSignedVectorType(resultType);
15454 break;
15455 } else if (Context.getLangOpts().CPlusPlus &&
15456 resultType->isVectorType()) {
15457 const VectorType *VTy = resultType->castAs<VectorType>();
15458 if (VTy->getVectorKind() != VectorKind::Generic)
15459 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15460 << resultType << Input.get()->getSourceRange());
15461
15462 // Vector logical not returns the signed variant of the operand type.
15463 resultType = GetSignedVectorType(resultType);
15464 break;
15465 } else {
15466 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15467 << resultType << Input.get()->getSourceRange());
15468 }
15469
15470 // LNot always has type int. C99 6.5.3.3p5.
15471 // In C++, it's bool. C++ 5.3.1p8
15472 resultType = Context.getLogicalOperationType();
15473 break;
15474 case UO_Real:
15475 case UO_Imag:
15476 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15477 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
15478 // ordinary complex l-values to ordinary l-values and all other values to
15479 // r-values.
15480 if (Input.isInvalid())
15481 return ExprError();
15482 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15483 if (Input.get()->isGLValue() &&
15484 Input.get()->getObjectKind() == OK_Ordinary)
15485 VK = Input.get()->getValueKind();
15486 } else if (!getLangOpts().CPlusPlus) {
15487 // In C, a volatile scalar is read by __imag. In C++, it is not.
15488 Input = DefaultLvalueConversion(Input.get());
15489 }
15490 break;
15491 case UO_Extension:
15492 resultType = Input.get()->getType();
15493 VK = Input.get()->getValueKind();
15494 OK = Input.get()->getObjectKind();
15495 break;
15496 case UO_Coawait:
15497 // It's unnecessary to represent the pass-through operator co_await in the
15498 // AST; just return the input expression instead.
15499 assert(!Input.get()->getType()->isDependentType() &&
15500 "the co_await expression must be non-dependant before "
15501 "building operator co_await");
15502 return Input;
15503 }
15504 }
15505 if (resultType.isNull() || Input.isInvalid())
15506 return ExprError();
15507
15508 // Check for array bounds violations in the operand of the UnaryOperator,
15509 // except for the '*' and '&' operators that have to be handled specially
15510 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15511 // that are explicitly defined as valid by the standard).
15512 if (Opc != UO_AddrOf && Opc != UO_Deref)
15513 CheckArrayAccess(Input.get());
15514
15515 auto *UO =
15516 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15517 OpLoc, CanOverflow, CurFPFeatureOverrides());
15518
15519 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15520 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15522 ExprEvalContexts.back().PossibleDerefs.insert(UO);
15523
15524 // Convert the result back to a half vector.
15525 if (ConvertHalfVec)
15526 return convertVector(UO, Context.HalfTy, *this);
15527 return UO;
15528}
15529
15531 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15532 if (!DRE->getQualifier())
15533 return false;
15534
15535 ValueDecl *VD = DRE->getDecl();
15536 if (!VD->isCXXClassMember())
15537 return false;
15538
15539 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15540 return true;
15541 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15542 return Method->isImplicitObjectMemberFunction();
15543
15544 return false;
15545 }
15546
15547 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15548 if (!ULE->getQualifier())
15549 return false;
15550
15551 for (NamedDecl *D : ULE->decls()) {
15552 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15553 if (Method->isImplicitObjectMemberFunction())
15554 return true;
15555 } else {
15556 // Overload set does not contain methods.
15557 break;
15558 }
15559 }
15560
15561 return false;
15562 }
15563
15564 return false;
15565}
15566
15568 UnaryOperatorKind Opc, Expr *Input,
15569 bool IsAfterAmp) {
15570 // First things first: handle placeholders so that the
15571 // overloaded-operator check considers the right type.
15572 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15573 // Increment and decrement of pseudo-object references.
15574 if (pty->getKind() == BuiltinType::PseudoObject &&
15576 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
15577
15578 // extension is always a builtin operator.
15579 if (Opc == UO_Extension)
15580 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15581
15582 // & gets special logic for several kinds of placeholder.
15583 // The builtin code knows what to do.
15584 if (Opc == UO_AddrOf &&
15585 (pty->getKind() == BuiltinType::Overload ||
15586 pty->getKind() == BuiltinType::UnknownAny ||
15587 pty->getKind() == BuiltinType::BoundMember))
15588 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15589
15590 // Anything else needs to be handled now.
15592 if (Result.isInvalid()) return ExprError();
15593 Input = Result.get();
15594 }
15595
15596 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15598 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15599 // Find all of the overloaded operators visible from this point.
15600 UnresolvedSet<16> Functions;
15602 if (S && OverOp != OO_None)
15603 LookupOverloadedOperatorName(OverOp, S, Functions);
15604
15605 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15606 }
15607
15608 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
15609}
15610
15612 Expr *Input, bool IsAfterAmp) {
15613 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
15614 IsAfterAmp);
15615}
15616
15618 LabelDecl *TheDecl) {
15619 TheDecl->markUsed(Context);
15620 // Create the AST node. The address of a label always has type 'void*'.
15621 auto *Res = new (Context) AddrLabelExpr(
15622 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
15623
15624 if (getCurFunction())
15625 getCurFunction()->AddrLabels.push_back(Res);
15626
15627 return Res;
15628}
15629
15632 // Make sure we diagnose jumping into a statement expression.
15634}
15635
15637 // Note that function is also called by TreeTransform when leaving a
15638 // StmtExpr scope without rebuilding anything.
15639
15642}
15643
15645 SourceLocation RPLoc) {
15646 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15647}
15648
15650 SourceLocation RPLoc, unsigned TemplateDepth) {
15651 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15652 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15653
15656 assert(!Cleanup.exprNeedsCleanups() &&
15657 "cleanups within StmtExpr not correctly bound!");
15659
15660 // FIXME: there are a variety of strange constraints to enforce here, for
15661 // example, it is not possible to goto into a stmt expression apparently.
15662 // More semantic analysis is needed.
15663
15664 // If there are sub-stmts in the compound stmt, take the type of the last one
15665 // as the type of the stmtexpr.
15666 QualType Ty = Context.VoidTy;
15667 bool StmtExprMayBindToTemp = false;
15668 if (!Compound->body_empty()) {
15669 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15670 if (const auto *LastStmt =
15671 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15672 if (const Expr *Value = LastStmt->getExprStmt()) {
15673 StmtExprMayBindToTemp = true;
15674 Ty = Value->getType();
15675 }
15676 }
15677 }
15678
15679 // FIXME: Check that expression type is complete/non-abstract; statement
15680 // expressions are not lvalues.
15681 Expr *ResStmtExpr =
15682 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15683 if (StmtExprMayBindToTemp)
15684 return MaybeBindToTemporary(ResStmtExpr);
15685 return ResStmtExpr;
15686}
15687
15689 if (ER.isInvalid())
15690 return ExprError();
15691
15692 // Do function/array conversion on the last expression, but not
15693 // lvalue-to-rvalue. However, initialize an unqualified type.
15695 if (ER.isInvalid())
15696 return ExprError();
15697 Expr *E = ER.get();
15698
15699 if (E->isTypeDependent())
15700 return E;
15701
15702 // In ARC, if the final expression ends in a consume, splice
15703 // the consume out and bind it later. In the alternate case
15704 // (when dealing with a retainable type), the result
15705 // initialization will create a produce. In both cases the
15706 // result will be +1, and we'll need to balance that out with
15707 // a bind.
15708 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15709 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15710 return Cast->getSubExpr();
15711
15712 // FIXME: Provide a better location for the initialization.
15716 SourceLocation(), E);
15717}
15718
15720 TypeSourceInfo *TInfo,
15721 ArrayRef<OffsetOfComponent> Components,
15722 SourceLocation RParenLoc) {
15723 QualType ArgTy = TInfo->getType();
15724 bool Dependent = ArgTy->isDependentType();
15725 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15726
15727 // We must have at least one component that refers to the type, and the first
15728 // one is known to be a field designator. Verify that the ArgTy represents
15729 // a struct/union/class.
15730 if (!Dependent && !ArgTy->isRecordType())
15731 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15732 << ArgTy << TypeRange);
15733
15734 // Type must be complete per C99 7.17p3 because a declaring a variable
15735 // with an incomplete type would be ill-formed.
15736 if (!Dependent
15737 && RequireCompleteType(BuiltinLoc, ArgTy,
15738 diag::err_offsetof_incomplete_type, TypeRange))
15739 return ExprError();
15740
15741 bool DidWarnAboutNonPOD = false;
15742 QualType CurrentType = ArgTy;
15745 for (const OffsetOfComponent &OC : Components) {
15746 if (OC.isBrackets) {
15747 // Offset of an array sub-field. TODO: Should we allow vector elements?
15748 if (!CurrentType->isDependentType()) {
15749 const ArrayType *AT = Context.getAsArrayType(CurrentType);
15750 if(!AT)
15751 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15752 << CurrentType);
15753 CurrentType = AT->getElementType();
15754 } else
15755 CurrentType = Context.DependentTy;
15756
15757 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15758 if (IdxRval.isInvalid())
15759 return ExprError();
15760 Expr *Idx = IdxRval.get();
15761
15762 // The expression must be an integral expression.
15763 // FIXME: An integral constant expression?
15764 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15765 !Idx->getType()->isIntegerType())
15766 return ExprError(
15767 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15768 << Idx->getSourceRange());
15769
15770 // Record this array index.
15771 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15772 Exprs.push_back(Idx);
15773 continue;
15774 }
15775
15776 // Offset of a field.
15777 if (CurrentType->isDependentType()) {
15778 // We have the offset of a field, but we can't look into the dependent
15779 // type. Just record the identifier of the field.
15780 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15781 CurrentType = Context.DependentTy;
15782 continue;
15783 }
15784
15785 // We need to have a complete type to look into.
15786 if (RequireCompleteType(OC.LocStart, CurrentType,
15787 diag::err_offsetof_incomplete_type))
15788 return ExprError();
15789
15790 // Look for the designated field.
15791 const RecordType *RC = CurrentType->getAs<RecordType>();
15792 if (!RC)
15793 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15794 << CurrentType);
15795 RecordDecl *RD = RC->getDecl();
15796
15797 // C++ [lib.support.types]p5:
15798 // The macro offsetof accepts a restricted set of type arguments in this
15799 // International Standard. type shall be a POD structure or a POD union
15800 // (clause 9).
15801 // C++11 [support.types]p4:
15802 // If type is not a standard-layout class (Clause 9), the results are
15803 // undefined.
15804 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15805 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15806 unsigned DiagID =
15807 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15808 : diag::ext_offsetof_non_pod_type;
15809
15810 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
15811 Diag(BuiltinLoc, DiagID)
15812 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
15813 DidWarnAboutNonPOD = true;
15814 }
15815 }
15816
15817 // Look for the field.
15818 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15819 LookupQualifiedName(R, RD);
15820 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15821 IndirectFieldDecl *IndirectMemberDecl = nullptr;
15822 if (!MemberDecl) {
15823 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15824 MemberDecl = IndirectMemberDecl->getAnonField();
15825 }
15826
15827 if (!MemberDecl) {
15828 // Lookup could be ambiguous when looking up a placeholder variable
15829 // __builtin_offsetof(S, _).
15830 // In that case we would already have emitted a diagnostic
15831 if (!R.isAmbiguous())
15832 Diag(BuiltinLoc, diag::err_no_member)
15833 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
15834 return ExprError();
15835 }
15836
15837 // C99 7.17p3:
15838 // (If the specified member is a bit-field, the behavior is undefined.)
15839 //
15840 // We diagnose this as an error.
15841 if (MemberDecl->isBitField()) {
15842 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15843 << MemberDecl->getDeclName()
15844 << SourceRange(BuiltinLoc, RParenLoc);
15845 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15846 return ExprError();
15847 }
15848
15849 RecordDecl *Parent = MemberDecl->getParent();
15850 if (IndirectMemberDecl)
15851 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15852
15853 // If the member was found in a base class, introduce OffsetOfNodes for
15854 // the base class indirections.
15855 CXXBasePaths Paths;
15856 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15857 Paths)) {
15858 if (Paths.getDetectedVirtual()) {
15859 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15860 << MemberDecl->getDeclName()
15861 << SourceRange(BuiltinLoc, RParenLoc);
15862 return ExprError();
15863 }
15864
15865 CXXBasePath &Path = Paths.front();
15866 for (const CXXBasePathElement &B : Path)
15867 Comps.push_back(OffsetOfNode(B.Base));
15868 }
15869
15870 if (IndirectMemberDecl) {
15871 for (auto *FI : IndirectMemberDecl->chain()) {
15872 assert(isa<FieldDecl>(FI));
15873 Comps.push_back(OffsetOfNode(OC.LocStart,
15874 cast<FieldDecl>(FI), OC.LocEnd));
15875 }
15876 } else
15877 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15878
15879 CurrentType = MemberDecl->getType().getNonReferenceType();
15880 }
15881
15882 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15883 Comps, Exprs, RParenLoc);
15884}
15885
15887 SourceLocation BuiltinLoc,
15889 ParsedType ParsedArgTy,
15890 ArrayRef<OffsetOfComponent> Components,
15891 SourceLocation RParenLoc) {
15892
15893 TypeSourceInfo *ArgTInfo;
15894 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15895 if (ArgTy.isNull())
15896 return ExprError();
15897
15898 if (!ArgTInfo)
15899 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15900
15901 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15902}
15903
15904
15906 Expr *CondExpr,
15907 Expr *LHSExpr, Expr *RHSExpr,
15908 SourceLocation RPLoc) {
15909 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15910
15913 QualType resType;
15914 bool CondIsTrue = false;
15915 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15916 resType = Context.DependentTy;
15917 } else {
15918 // The conditional expression is required to be a constant expression.
15919 llvm::APSInt condEval(32);
15921 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15922 if (CondICE.isInvalid())
15923 return ExprError();
15924 CondExpr = CondICE.get();
15925 CondIsTrue = condEval.getZExtValue();
15926
15927 // If the condition is > zero, then the AST type is the same as the LHSExpr.
15928 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15929
15930 resType = ActiveExpr->getType();
15931 VK = ActiveExpr->getValueKind();
15932 OK = ActiveExpr->getObjectKind();
15933 }
15934
15935 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15936 resType, VK, OK, RPLoc, CondIsTrue);
15937}
15938
15939//===----------------------------------------------------------------------===//
15940// Clang Extensions.
15941//===----------------------------------------------------------------------===//
15942
15943void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15945
15946 if (LangOpts.CPlusPlus) {
15948 Decl *ManglingContextDecl;
15949 std::tie(MCtx, ManglingContextDecl) =
15950 getCurrentMangleNumberContext(Block->getDeclContext());
15951 if (MCtx) {
15952 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15953 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15954 }
15955 }
15956
15957 PushBlockScope(CurScope, Block);
15959 if (CurScope)
15960 PushDeclContext(CurScope, Block);
15961 else
15962 CurContext = Block;
15963
15965
15966 // Enter a new evaluation context to insulate the block from any
15967 // cleanups from the enclosing full-expression.
15970}
15971
15973 Scope *CurScope) {
15974 assert(ParamInfo.getIdentifier() == nullptr &&
15975 "block-id should have no identifier!");
15976 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15977 BlockScopeInfo *CurBlock = getCurBlock();
15978
15979 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
15980 QualType T = Sig->getType();
15981
15982 // FIXME: We should allow unexpanded parameter packs here, but that would,
15983 // in turn, make the block expression contain unexpanded parameter packs.
15984 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15985 // Drop the parameters.
15987 EPI.HasTrailingReturn = false;
15988 EPI.TypeQuals.addConst();
15989 T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
15991 }
15992
15993 // GetTypeForDeclarator always produces a function type for a block
15994 // literal signature. Furthermore, it is always a FunctionProtoType
15995 // unless the function was written with a typedef.
15996 assert(T->isFunctionType() &&
15997 "GetTypeForDeclarator made a non-function block signature");
15998
15999 // Look for an explicit signature in that function type.
16000 FunctionProtoTypeLoc ExplicitSignature;
16001
16002 if ((ExplicitSignature = Sig->getTypeLoc()
16004
16005 // Check whether that explicit signature was synthesized by
16006 // GetTypeForDeclarator. If so, don't save that as part of the
16007 // written signature.
16008 if (ExplicitSignature.getLocalRangeBegin() ==
16009 ExplicitSignature.getLocalRangeEnd()) {
16010 // This would be much cheaper if we stored TypeLocs instead of
16011 // TypeSourceInfos.
16012 TypeLoc Result = ExplicitSignature.getReturnLoc();
16013 unsigned Size = Result.getFullDataSize();
16014 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16015 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16016
16017 ExplicitSignature = FunctionProtoTypeLoc();
16018 }
16019 }
16020
16021 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16022 CurBlock->FunctionType = T;
16023
16024 const auto *Fn = T->castAs<FunctionType>();
16025 QualType RetTy = Fn->getReturnType();
16026 bool isVariadic =
16027 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16028
16029 CurBlock->TheDecl->setIsVariadic(isVariadic);
16030
16031 // Context.DependentTy is used as a placeholder for a missing block
16032 // return type. TODO: what should we do with declarators like:
16033 // ^ * { ... }
16034 // If the answer is "apply template argument deduction"....
16035 if (RetTy != Context.DependentTy) {
16036 CurBlock->ReturnType = RetTy;
16037 CurBlock->TheDecl->setBlockMissingReturnType(false);
16038 CurBlock->HasImplicitReturnType = false;
16039 }
16040
16041 // Push block parameters from the declarator if we had them.
16043 if (ExplicitSignature) {
16044 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16045 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16046 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16047 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16048 // Diagnose this as an extension in C17 and earlier.
16049 if (!getLangOpts().C23)
16050 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16051 }
16052 Params.push_back(Param);
16053 }
16054
16055 // Fake up parameter variables if we have a typedef, like
16056 // ^ fntype { ... }
16057 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16058 for (const auto &I : Fn->param_types()) {
16060 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16061 Params.push_back(Param);
16062 }
16063 }
16064
16065 // Set the parameters on the block decl.
16066 if (!Params.empty()) {
16067 CurBlock->TheDecl->setParams(Params);
16069 /*CheckParameterNames=*/false);
16070 }
16071
16072 // Finally we can process decl attributes.
16073 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16074
16075 // Put the parameter variables in scope.
16076 for (auto *AI : CurBlock->TheDecl->parameters()) {
16077 AI->setOwningFunction(CurBlock->TheDecl);
16078
16079 // If this has an identifier, add it to the scope stack.
16080 if (AI->getIdentifier()) {
16081 CheckShadow(CurBlock->TheScope, AI);
16082
16083 PushOnScopeChains(AI, CurBlock->TheScope);
16084 }
16085
16086 if (AI->isInvalidDecl())
16087 CurBlock->TheDecl->setInvalidDecl();
16088 }
16089}
16090
16091void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16092 // Leave the expression-evaluation context.
16095
16096 // Pop off CurBlock, handle nested blocks.
16099}
16100
16102 Stmt *Body, Scope *CurScope) {
16103 // If blocks are disabled, emit an error.
16104 if (!LangOpts.Blocks)
16105 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16106
16107 // Leave the expression-evaluation context.
16110 assert(!Cleanup.exprNeedsCleanups() &&
16111 "cleanups within block not correctly bound!");
16113
16114 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16115 BlockDecl *BD = BSI->TheDecl;
16116
16117 if (BSI->HasImplicitReturnType)
16119
16120 QualType RetTy = Context.VoidTy;
16121 if (!BSI->ReturnType.isNull())
16122 RetTy = BSI->ReturnType;
16123
16124 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16125 QualType BlockTy;
16126
16127 // If the user wrote a function type in some form, try to use that.
16128 if (!BSI->FunctionType.isNull()) {
16129 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16130
16131 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16132 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16133
16134 // Turn protoless block types into nullary block types.
16135 if (isa<FunctionNoProtoType>(FTy)) {
16137 EPI.ExtInfo = Ext;
16138 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16139
16140 // Otherwise, if we don't need to change anything about the function type,
16141 // preserve its sugar structure.
16142 } else if (FTy->getReturnType() == RetTy &&
16143 (!NoReturn || FTy->getNoReturnAttr())) {
16144 BlockTy = BSI->FunctionType;
16145
16146 // Otherwise, make the minimal modifications to the function type.
16147 } else {
16148 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16150 EPI.TypeQuals = Qualifiers();
16151 EPI.ExtInfo = Ext;
16152 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16153 }
16154
16155 // If we don't have a function type, just build one from nothing.
16156 } else {
16158 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16159 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16160 }
16161
16163 BlockTy = Context.getBlockPointerType(BlockTy);
16164
16165 // If needed, diagnose invalid gotos and switches in the block.
16166 if (getCurFunction()->NeedsScopeChecking() &&
16168 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16169
16170 BD->setBody(cast<CompoundStmt>(Body));
16171
16172 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16174
16175 // Try to apply the named return value optimization. We have to check again
16176 // if we can do this, though, because blocks keep return statements around
16177 // to deduce an implicit return type.
16178 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16179 !BD->isDependentContext())
16180 computeNRVO(Body, BSI);
16181
16186
16188
16189 // Set the captured variables on the block.
16191 for (Capture &Cap : BSI->Captures) {
16192 if (Cap.isInvalid() || Cap.isThisCapture())
16193 continue;
16194 // Cap.getVariable() is always a VarDecl because
16195 // blocks cannot capture structured bindings or other ValueDecl kinds.
16196 auto *Var = cast<VarDecl>(Cap.getVariable());
16197 Expr *CopyExpr = nullptr;
16198 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16199 if (const RecordType *Record =
16200 Cap.getCaptureType()->getAs<RecordType>()) {
16201 // The capture logic needs the destructor, so make sure we mark it.
16202 // Usually this is unnecessary because most local variables have
16203 // their destructors marked at declaration time, but parameters are
16204 // an exception because it's technically only the call site that
16205 // actually requires the destructor.
16206 if (isa<ParmVarDecl>(Var))
16208
16209 // Enter a separate potentially-evaluated context while building block
16210 // initializers to isolate their cleanups from those of the block
16211 // itself.
16212 // FIXME: Is this appropriate even when the block itself occurs in an
16213 // unevaluated operand?
16216
16218
16220 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16221
16222 // According to the blocks spec, the capture of a variable from
16223 // the stack requires a const copy constructor. This is not true
16224 // of the copy/move done to move a __block variable to the heap.
16225 if (!Result.isInvalid() &&
16226 !Result.get()->getType().isConstQualified()) {
16228 Result.get()->getType().withConst(),
16229 CK_NoOp, VK_LValue);
16230 }
16231
16232 if (!Result.isInvalid()) {
16234 InitializedEntity::InitializeBlock(Var->getLocation(),
16235 Cap.getCaptureType()),
16236 Loc, Result.get());
16237 }
16238
16239 // Build a full-expression copy expression if initialization
16240 // succeeded and used a non-trivial constructor. Recover from
16241 // errors by pretending that the copy isn't necessary.
16242 if (!Result.isInvalid() &&
16243 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16244 ->isTrivial()) {
16246 CopyExpr = Result.get();
16247 }
16248 }
16249 }
16250
16251 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16252 CopyExpr);
16253 Captures.push_back(NewCap);
16254 }
16255 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16256
16257 // Pop the block scope now but keep it alive to the end of this function.
16259 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16260
16261 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16262
16263 // If the block isn't obviously global, i.e. it captures anything at
16264 // all, then we need to do a few things in the surrounding context:
16265 if (Result->getBlockDecl()->hasCaptures()) {
16266 // First, this expression has a new cleanup object.
16267 ExprCleanupObjects.push_back(Result->getBlockDecl());
16269
16270 // It also gets a branch-protected scope if any of the captured
16271 // variables needs destruction.
16272 for (const auto &CI : Result->getBlockDecl()->captures()) {
16273 const VarDecl *var = CI.getVariable();
16274 if (var->getType().isDestructedType() != QualType::DK_none) {
16276 break;
16277 }
16278 }
16279 }
16280
16281 if (getCurFunction())
16282 getCurFunction()->addBlock(BD);
16283
16284 if (BD->isInvalidDecl())
16285 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16286 {Result}, Result->getType());
16287 return Result;
16288}
16289
16291 SourceLocation RPLoc) {
16292 TypeSourceInfo *TInfo;
16293 GetTypeFromParser(Ty, &TInfo);
16294 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16295}
16296
16298 Expr *E, TypeSourceInfo *TInfo,
16299 SourceLocation RPLoc) {
16300 Expr *OrigExpr = E;
16301 bool IsMS = false;
16302
16303 // CUDA device code does not support varargs.
16304 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16305 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16309 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16310 }
16311 }
16312
16313 // NVPTX does not support va_arg expression.
16314 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16315 Context.getTargetInfo().getTriple().isNVPTX())
16316 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16317
16318 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16319 // as Microsoft ABI on an actual Microsoft platform, where
16320 // __builtin_ms_va_list and __builtin_va_list are the same.)
16323 QualType MSVaListType = Context.getBuiltinMSVaListType();
16324 if (Context.hasSameType(MSVaListType, E->getType())) {
16325 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16326 return ExprError();
16327 IsMS = true;
16328 }
16329 }
16330
16331 // Get the va_list type
16332 QualType VaListType = Context.getBuiltinVaListType();
16333 if (!IsMS) {
16334 if (VaListType->isArrayType()) {
16335 // Deal with implicit array decay; for example, on x86-64,
16336 // va_list is an array, but it's supposed to decay to
16337 // a pointer for va_arg.
16338 VaListType = Context.getArrayDecayedType(VaListType);
16339 // Make sure the input expression also decays appropriately.
16341 if (Result.isInvalid())
16342 return ExprError();
16343 E = Result.get();
16344 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16345 // If va_list is a record type and we are compiling in C++ mode,
16346 // check the argument using reference binding.
16348 Context, Context.getLValueReferenceType(VaListType), false);
16350 if (Init.isInvalid())
16351 return ExprError();
16352 E = Init.getAs<Expr>();
16353 } else {
16354 // Otherwise, the va_list argument must be an l-value because
16355 // it is modified by va_arg.
16356 if (!E->isTypeDependent() &&
16357 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16358 return ExprError();
16359 }
16360 }
16361
16362 if (!IsMS && !E->isTypeDependent() &&
16363 !Context.hasSameType(VaListType, E->getType()))
16364 return ExprError(
16365 Diag(E->getBeginLoc(),
16366 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16367 << OrigExpr->getType() << E->getSourceRange());
16368
16369 if (!TInfo->getType()->isDependentType()) {
16370 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16371 diag::err_second_parameter_to_va_arg_incomplete,
16372 TInfo->getTypeLoc()))
16373 return ExprError();
16374
16376 TInfo->getType(),
16377 diag::err_second_parameter_to_va_arg_abstract,
16378 TInfo->getTypeLoc()))
16379 return ExprError();
16380
16381 if (!TInfo->getType().isPODType(Context)) {
16382 Diag(TInfo->getTypeLoc().getBeginLoc(),
16383 TInfo->getType()->isObjCLifetimeType()
16384 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16385 : diag::warn_second_parameter_to_va_arg_not_pod)
16386 << TInfo->getType()
16387 << TInfo->getTypeLoc().getSourceRange();
16388 }
16389
16390 // Check for va_arg where arguments of the given type will be promoted
16391 // (i.e. this va_arg is guaranteed to have undefined behavior).
16392 QualType PromoteType;
16393 if (Context.isPromotableIntegerType(TInfo->getType())) {
16394 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16395 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16396 // and C23 7.16.1.1p2 says, in part:
16397 // If type is not compatible with the type of the actual next argument
16398 // (as promoted according to the default argument promotions), the
16399 // behavior is undefined, except for the following cases:
16400 // - both types are pointers to qualified or unqualified versions of
16401 // compatible types;
16402 // - one type is compatible with a signed integer type, the other
16403 // type is compatible with the corresponding unsigned integer type,
16404 // and the value is representable in both types;
16405 // - one type is pointer to qualified or unqualified void and the
16406 // other is a pointer to a qualified or unqualified character type;
16407 // - or, the type of the next argument is nullptr_t and type is a
16408 // pointer type that has the same representation and alignment
16409 // requirements as a pointer to a character type.
16410 // Given that type compatibility is the primary requirement (ignoring
16411 // qualifications), you would think we could call typesAreCompatible()
16412 // directly to test this. However, in C++, that checks for *same type*,
16413 // which causes false positives when passing an enumeration type to
16414 // va_arg. Instead, get the underlying type of the enumeration and pass
16415 // that.
16416 QualType UnderlyingType = TInfo->getType();
16417 if (const auto *ET = UnderlyingType->getAs<EnumType>())
16418 UnderlyingType = ET->getDecl()->getIntegerType();
16419 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16420 /*CompareUnqualified*/ true))
16421 PromoteType = QualType();
16422
16423 // If the types are still not compatible, we need to test whether the
16424 // promoted type and the underlying type are the same except for
16425 // signedness. Ask the AST for the correctly corresponding type and see
16426 // if that's compatible.
16427 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16428 PromoteType->isUnsignedIntegerType() !=
16429 UnderlyingType->isUnsignedIntegerType()) {
16430 UnderlyingType =
16431 UnderlyingType->isUnsignedIntegerType()
16432 ? Context.getCorrespondingSignedType(UnderlyingType)
16433 : Context.getCorrespondingUnsignedType(UnderlyingType);
16434 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16435 /*CompareUnqualified*/ true))
16436 PromoteType = QualType();
16437 }
16438 }
16439 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16440 PromoteType = Context.DoubleTy;
16441 if (!PromoteType.isNull())
16443 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16444 << TInfo->getType()
16445 << PromoteType
16446 << TInfo->getTypeLoc().getSourceRange());
16447 }
16448
16450 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16451}
16452
16454 // The type of __null will be int or long, depending on the size of
16455 // pointers on the target.
16456 QualType Ty;
16458 if (pw == Context.getTargetInfo().getIntWidth())
16459 Ty = Context.IntTy;
16460 else if (pw == Context.getTargetInfo().getLongWidth())
16461 Ty = Context.LongTy;
16462 else if (pw == Context.getTargetInfo().getLongLongWidth())
16463 Ty = Context.LongLongTy;
16464 else {
16465 llvm_unreachable("I don't know size of pointer!");
16466 }
16467
16468 return new (Context) GNUNullExpr(Ty, TokenLoc);
16469}
16470
16472 CXXRecordDecl *ImplDecl = nullptr;
16473
16474 // Fetch the std::source_location::__impl decl.
16475 if (NamespaceDecl *Std = S.getStdNamespace()) {
16476 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16478 if (S.LookupQualifiedName(ResultSL, Std)) {
16479 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16480 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16482 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16483 S.LookupQualifiedName(ResultImpl, SLDecl)) {
16484 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16485 }
16486 }
16487 }
16488 }
16489
16490 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16491 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16492 return nullptr;
16493 }
16494
16495 // Verify that __impl is a trivial struct type, with no base classes, and with
16496 // only the four expected fields.
16497 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16498 ImplDecl->getNumBases() != 0) {
16499 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16500 return nullptr;
16501 }
16502
16503 unsigned Count = 0;
16504 for (FieldDecl *F : ImplDecl->fields()) {
16505 StringRef Name = F->getName();
16506
16507 if (Name == "_M_file_name") {
16508 if (F->getType() !=
16510 break;
16511 Count++;
16512 } else if (Name == "_M_function_name") {
16513 if (F->getType() !=
16515 break;
16516 Count++;
16517 } else if (Name == "_M_line") {
16518 if (!F->getType()->isIntegerType())
16519 break;
16520 Count++;
16521 } else if (Name == "_M_column") {
16522 if (!F->getType()->isIntegerType())
16523 break;
16524 Count++;
16525 } else {
16526 Count = 100; // invalid
16527 break;
16528 }
16529 }
16530 if (Count != 4) {
16531 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16532 return nullptr;
16533 }
16534
16535 return ImplDecl;
16536}
16537
16539 SourceLocation BuiltinLoc,
16540 SourceLocation RPLoc) {
16541 QualType ResultTy;
16542 switch (Kind) {
16548 ResultTy =
16550 break;
16551 }
16554 ResultTy = Context.UnsignedIntTy;
16555 break;
16559 LookupStdSourceLocationImpl(*this, BuiltinLoc);
16561 return ExprError();
16562 }
16563 ResultTy = Context.getPointerType(
16565 break;
16566 }
16567
16568 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16569}
16570
16572 SourceLocation BuiltinLoc,
16573 SourceLocation RPLoc,
16574 DeclContext *ParentContext) {
16575 return new (Context)
16576 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16577}
16578
16580 StringLiteral *BinaryData) {
16582 Data->BinaryData = BinaryData;
16583 return new (Context)
16584 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
16585 Data->getDataElementCount());
16586}
16587
16589 const Expr *SrcExpr) {
16590 if (!DstType->isFunctionPointerType() ||
16591 !SrcExpr->getType()->isFunctionType())
16592 return false;
16593
16594 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16595 if (!DRE)
16596 return false;
16597
16598 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16599 if (!FD)
16600 return false;
16601
16603 /*Complain=*/true,
16604 SrcExpr->getBeginLoc());
16605}
16606
16609 QualType DstType, QualType SrcType,
16610 Expr *SrcExpr, AssignmentAction Action,
16611 bool *Complained) {
16612 if (Complained)
16613 *Complained = false;
16614
16615 // Decode the result (notice that AST's are still created for extensions).
16616 bool CheckInferredResultType = false;
16617 bool isInvalid = false;
16618 unsigned DiagKind = 0;
16619 ConversionFixItGenerator ConvHints;
16620 bool MayHaveConvFixit = false;
16621 bool MayHaveFunctionDiff = false;
16622 const ObjCInterfaceDecl *IFace = nullptr;
16623 const ObjCProtocolDecl *PDecl = nullptr;
16624
16625 switch (ConvTy) {
16626 case Compatible:
16627 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16628 return false;
16629
16630 case PointerToInt:
16631 if (getLangOpts().CPlusPlus) {
16632 DiagKind = diag::err_typecheck_convert_pointer_int;
16633 isInvalid = true;
16634 } else {
16635 DiagKind = diag::ext_typecheck_convert_pointer_int;
16636 }
16637 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16638 MayHaveConvFixit = true;
16639 break;
16640 case IntToPointer:
16641 if (getLangOpts().CPlusPlus) {
16642 DiagKind = diag::err_typecheck_convert_int_pointer;
16643 isInvalid = true;
16644 } else {
16645 DiagKind = diag::ext_typecheck_convert_int_pointer;
16646 }
16647 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16648 MayHaveConvFixit = true;
16649 break;
16651 DiagKind =
16652 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
16653 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16654 MayHaveConvFixit = true;
16655 break;
16657 if (getLangOpts().CPlusPlus) {
16658 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16659 isInvalid = true;
16660 } else {
16661 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16662 }
16663 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16664 MayHaveConvFixit = true;
16665 break;
16667 if (Action == AA_Passing_CFAudited) {
16668 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16669 } else if (getLangOpts().CPlusPlus) {
16670 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16671 isInvalid = true;
16672 } else {
16673 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16674 }
16675 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16676 SrcType->isObjCObjectPointerType();
16677 if (CheckInferredResultType) {
16678 SrcType = SrcType.getUnqualifiedType();
16679 DstType = DstType.getUnqualifiedType();
16680 } else {
16681 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16682 }
16683 MayHaveConvFixit = true;
16684 break;
16686 if (getLangOpts().CPlusPlus) {
16687 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16688 isInvalid = true;
16689 } else {
16690 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16691 }
16692 break;
16694 if (getLangOpts().CPlusPlus) {
16695 DiagKind = diag::err_typecheck_convert_pointer_void_func;
16696 isInvalid = true;
16697 } else {
16698 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16699 }
16700 break;
16702 // Perform array-to-pointer decay if necessary.
16703 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16704
16705 isInvalid = true;
16706
16707 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16708 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16709 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16710 DiagKind = diag::err_typecheck_incompatible_address_space;
16711 break;
16712 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16713 DiagKind = diag::err_typecheck_incompatible_ownership;
16714 break;
16715 }
16716
16717 llvm_unreachable("unknown error case for discarding qualifiers!");
16718 // fallthrough
16719 }
16721 // If the qualifiers lost were because we were applying the
16722 // (deprecated) C++ conversion from a string literal to a char*
16723 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16724 // Ideally, this check would be performed in
16725 // checkPointerTypesForAssignment. However, that would require a
16726 // bit of refactoring (so that the second argument is an
16727 // expression, rather than a type), which should be done as part
16728 // of a larger effort to fix checkPointerTypesForAssignment for
16729 // C++ semantics.
16730 if (getLangOpts().CPlusPlus &&
16732 return false;
16733 if (getLangOpts().CPlusPlus) {
16734 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
16735 isInvalid = true;
16736 } else {
16737 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
16738 }
16739
16740 break;
16742 if (getLangOpts().CPlusPlus) {
16743 isInvalid = true;
16744 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16745 } else {
16746 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16747 }
16748 break;
16750 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16751 isInvalid = true;
16752 break;
16753 case IntToBlockPointer:
16754 DiagKind = diag::err_int_to_block_pointer;
16755 isInvalid = true;
16756 break;
16758 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16759 isInvalid = true;
16760 break;
16762 if (SrcType->isObjCQualifiedIdType()) {
16763 const ObjCObjectPointerType *srcOPT =
16764 SrcType->castAs<ObjCObjectPointerType>();
16765 for (auto *srcProto : srcOPT->quals()) {
16766 PDecl = srcProto;
16767 break;
16768 }
16769 if (const ObjCInterfaceType *IFaceT =
16771 IFace = IFaceT->getDecl();
16772 }
16773 else if (DstType->isObjCQualifiedIdType()) {
16774 const ObjCObjectPointerType *dstOPT =
16775 DstType->castAs<ObjCObjectPointerType>();
16776 for (auto *dstProto : dstOPT->quals()) {
16777 PDecl = dstProto;
16778 break;
16779 }
16780 if (const ObjCInterfaceType *IFaceT =
16782 IFace = IFaceT->getDecl();
16783 }
16784 if (getLangOpts().CPlusPlus) {
16785 DiagKind = diag::err_incompatible_qualified_id;
16786 isInvalid = true;
16787 } else {
16788 DiagKind = diag::warn_incompatible_qualified_id;
16789 }
16790 break;
16791 }
16793 if (getLangOpts().CPlusPlus) {
16794 DiagKind = diag::err_incompatible_vectors;
16795 isInvalid = true;
16796 } else {
16797 DiagKind = diag::warn_incompatible_vectors;
16798 }
16799 break;
16801 DiagKind = diag::err_arc_weak_unavailable_assign;
16802 isInvalid = true;
16803 break;
16804 case Incompatible:
16805 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16806 if (Complained)
16807 *Complained = true;
16808 return true;
16809 }
16810
16811 DiagKind = diag::err_typecheck_convert_incompatible;
16812 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16813 MayHaveConvFixit = true;
16814 isInvalid = true;
16815 MayHaveFunctionDiff = true;
16816 break;
16817 }
16818
16819 QualType FirstType, SecondType;
16820 switch (Action) {
16821 case AA_Assigning:
16822 case AA_Initializing:
16823 // The destination type comes first.
16824 FirstType = DstType;
16825 SecondType = SrcType;
16826 break;
16827
16828 case AA_Returning:
16829 case AA_Passing:
16831 case AA_Converting:
16832 case AA_Sending:
16833 case AA_Casting:
16834 // The source type comes first.
16835 FirstType = SrcType;
16836 SecondType = DstType;
16837 break;
16838 }
16839
16840 PartialDiagnostic FDiag = PDiag(DiagKind);
16841 AssignmentAction ActionForDiag = Action;
16842 if (Action == AA_Passing_CFAudited)
16843 ActionForDiag = AA_Passing;
16844
16845 FDiag << FirstType << SecondType << ActionForDiag
16846 << SrcExpr->getSourceRange();
16847
16848 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16849 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16850 auto isPlainChar = [](const clang::Type *Type) {
16851 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16852 Type->isSpecificBuiltinType(BuiltinType::Char_U);
16853 };
16854 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16855 isPlainChar(SecondType->getPointeeOrArrayElementType()));
16856 }
16857
16858 // If we can fix the conversion, suggest the FixIts.
16859 if (!ConvHints.isNull()) {
16860 for (FixItHint &H : ConvHints.Hints)
16861 FDiag << H;
16862 }
16863
16864 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16865
16866 if (MayHaveFunctionDiff)
16867 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16868
16869 Diag(Loc, FDiag);
16870 if ((DiagKind == diag::warn_incompatible_qualified_id ||
16871 DiagKind == diag::err_incompatible_qualified_id) &&
16872 PDecl && IFace && !IFace->hasDefinition())
16873 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16874 << IFace << PDecl;
16875
16876 if (SecondType == Context.OverloadTy)
16878 FirstType, /*TakingAddress=*/true);
16879
16880 if (CheckInferredResultType)
16882
16883 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16885
16886 if (Complained)
16887 *Complained = true;
16888 return isInvalid;
16889}
16890
16892 llvm::APSInt *Result,
16893 AllowFoldKind CanFold) {
16894 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16895 public:
16896 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16897 QualType T) override {
16898 return S.Diag(Loc, diag::err_ice_not_integral)
16899 << T << S.LangOpts.CPlusPlus;
16900 }
16901 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16902 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16903 }
16904 } Diagnoser;
16905
16906 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16907}
16908
16910 llvm::APSInt *Result,
16911 unsigned DiagID,
16912 AllowFoldKind CanFold) {
16913 class IDDiagnoser : public VerifyICEDiagnoser {
16914 unsigned DiagID;
16915
16916 public:
16917 IDDiagnoser(unsigned DiagID)
16918 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16919
16920 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16921 return S.Diag(Loc, DiagID);
16922 }
16923 } Diagnoser(DiagID);
16924
16925 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16926}
16927
16930 QualType T) {
16931 return diagnoseNotICE(S, Loc);
16932}
16933
16936 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16937}
16938
16941 VerifyICEDiagnoser &Diagnoser,
16942 AllowFoldKind CanFold) {
16943 SourceLocation DiagLoc = E->getBeginLoc();
16944
16945 if (getLangOpts().CPlusPlus11) {
16946 // C++11 [expr.const]p5:
16947 // If an expression of literal class type is used in a context where an
16948 // integral constant expression is required, then that class type shall
16949 // have a single non-explicit conversion function to an integral or
16950 // unscoped enumeration type
16951 ExprResult Converted;
16952 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16953 VerifyICEDiagnoser &BaseDiagnoser;
16954 public:
16955 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16956 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16957 BaseDiagnoser.Suppress, true),
16958 BaseDiagnoser(BaseDiagnoser) {}
16959
16960 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16961 QualType T) override {
16962 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16963 }
16964
16965 SemaDiagnosticBuilder diagnoseIncomplete(
16966 Sema &S, SourceLocation Loc, QualType T) override {
16967 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16968 }
16969
16970 SemaDiagnosticBuilder diagnoseExplicitConv(
16971 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16972 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16973 }
16974
16975 SemaDiagnosticBuilder noteExplicitConv(
16976 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16977 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16978 << ConvTy->isEnumeralType() << ConvTy;
16979 }
16980
16981 SemaDiagnosticBuilder diagnoseAmbiguous(
16982 Sema &S, SourceLocation Loc, QualType T) override {
16983 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16984 }
16985
16986 SemaDiagnosticBuilder noteAmbiguous(
16987 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16988 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16989 << ConvTy->isEnumeralType() << ConvTy;
16990 }
16991
16992 SemaDiagnosticBuilder diagnoseConversion(
16993 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16994 llvm_unreachable("conversion functions are permitted");
16995 }
16996 } ConvertDiagnoser(Diagnoser);
16997
16998 Converted = PerformContextualImplicitConversion(DiagLoc, E,
16999 ConvertDiagnoser);
17000 if (Converted.isInvalid())
17001 return Converted;
17002 E = Converted.get();
17003 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17004 // don't try to evaluate it later. We also don't want to return the
17005 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17006 // this function will attempt to use 'Value'.
17007 if (isa<RecoveryExpr>(E))
17008 return ExprError();
17010 return ExprError();
17011 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17012 // An ICE must be of integral or unscoped enumeration type.
17013 if (!Diagnoser.Suppress)
17014 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17015 << E->getSourceRange();
17016 return ExprError();
17017 }
17018
17019 ExprResult RValueExpr = DefaultLvalueConversion(E);
17020 if (RValueExpr.isInvalid())
17021 return ExprError();
17022
17023 E = RValueExpr.get();
17024
17025 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17026 // in the non-ICE case.
17029 if (Result)
17031 if (!isa<ConstantExpr>(E))
17034
17035 if (Notes.empty())
17036 return E;
17037
17038 // If our only note is the usual "invalid subexpression" note, just point
17039 // the caret at its location rather than producing an essentially
17040 // redundant note.
17041 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17042 diag::note_invalid_subexpr_in_const_expr) {
17043 DiagLoc = Notes[0].first;
17044 Notes.clear();
17045 }
17046
17047 if (getLangOpts().CPlusPlus) {
17048 if (!Diagnoser.Suppress) {
17049 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17050 for (const PartialDiagnosticAt &Note : Notes)
17051 Diag(Note.first, Note.second);
17052 }
17053 return ExprError();
17054 }
17055
17056 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17057 for (const PartialDiagnosticAt &Note : Notes)
17058 Diag(Note.first, Note.second);
17059
17060 return E;
17061 }
17062
17063 Expr::EvalResult EvalResult;
17065 EvalResult.Diag = &Notes;
17066
17067 // Try to evaluate the expression, and produce diagnostics explaining why it's
17068 // not a constant expression as a side-effect.
17069 bool Folded =
17070 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17071 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17072 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17073
17074 if (!isa<ConstantExpr>(E))
17075 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17076
17077 // In C++11, we can rely on diagnostics being produced for any expression
17078 // which is not a constant expression. If no diagnostics were produced, then
17079 // this is a constant expression.
17080 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17081 if (Result)
17082 *Result = EvalResult.Val.getInt();
17083 return E;
17084 }
17085
17086 // If our only note is the usual "invalid subexpression" note, just point
17087 // the caret at its location rather than producing an essentially
17088 // redundant note.
17089 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17090 diag::note_invalid_subexpr_in_const_expr) {
17091 DiagLoc = Notes[0].first;
17092 Notes.clear();
17093 }
17094
17095 if (!Folded || !CanFold) {
17096 if (!Diagnoser.Suppress) {
17097 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17098 for (const PartialDiagnosticAt &Note : Notes)
17099 Diag(Note.first, Note.second);
17100 }
17101
17102 return ExprError();
17103 }
17104
17105 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17106 for (const PartialDiagnosticAt &Note : Notes)
17107 Diag(Note.first, Note.second);
17108
17109 if (Result)
17110 *Result = EvalResult.Val.getInt();
17111 return E;
17112}
17113
17114namespace {
17115 // Handle the case where we conclude a expression which we speculatively
17116 // considered to be unevaluated is actually evaluated.
17117 class TransformToPE : public TreeTransform<TransformToPE> {
17118 typedef TreeTransform<TransformToPE> BaseTransform;
17119
17120 public:
17121 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17122
17123 // Make sure we redo semantic analysis
17124 bool AlwaysRebuild() { return true; }
17125 bool ReplacingOriginal() { return true; }
17126
17127 // We need to special-case DeclRefExprs referring to FieldDecls which
17128 // are not part of a member pointer formation; normal TreeTransforming
17129 // doesn't catch this case because of the way we represent them in the AST.
17130 // FIXME: This is a bit ugly; is it really the best way to handle this
17131 // case?
17132 //
17133 // Error on DeclRefExprs referring to FieldDecls.
17134 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17135 if (isa<FieldDecl>(E->getDecl()) &&
17136 !SemaRef.isUnevaluatedContext())
17137 return SemaRef.Diag(E->getLocation(),
17138 diag::err_invalid_non_static_member_use)
17139 << E->getDecl() << E->getSourceRange();
17140
17141 return BaseTransform::TransformDeclRefExpr(E);
17142 }
17143
17144 // Exception: filter out member pointer formation
17145 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17146 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17147 return E;
17148
17149 return BaseTransform::TransformUnaryOperator(E);
17150 }
17151
17152 // The body of a lambda-expression is in a separate expression evaluation
17153 // context so never needs to be transformed.
17154 // FIXME: Ideally we wouldn't transform the closure type either, and would
17155 // just recreate the capture expressions and lambda expression.
17156 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17157 return SkipLambdaBody(E, Body);
17158 }
17159 };
17160}
17161
17163 assert(isUnevaluatedContext() &&
17164 "Should only transform unevaluated expressions");
17165 ExprEvalContexts.back().Context =
17166 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17168 return E;
17169 return TransformToPE(*this).TransformExpr(E);
17170}
17171
17173 assert(isUnevaluatedContext() &&
17174 "Should only transform unevaluated expressions");
17177 return TInfo;
17178 return TransformToPE(*this).TransformType(TInfo);
17179}
17180
17181void
17183 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17185 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17186 LambdaContextDecl, ExprContext);
17187
17188 // Discarded statements and immediate contexts nested in other
17189 // discarded statements or immediate context are themselves
17190 // a discarded statement or an immediate context, respectively.
17191 ExprEvalContexts.back().InDiscardedStatement =
17193
17194 // C++23 [expr.const]/p15
17195 // An expression or conversion is in an immediate function context if [...]
17196 // it is a subexpression of a manifestly constant-evaluated expression or
17197 // conversion.
17198 const auto &Prev = parentEvaluationContext();
17199 ExprEvalContexts.back().InImmediateFunctionContext =
17200 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17201
17202 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17203 Prev.InImmediateEscalatingFunctionContext;
17204
17205 Cleanup.reset();
17206 if (!MaybeODRUseExprs.empty())
17207 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17208}
17209
17210void
17214 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17215 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17216}
17217
17218namespace {
17219
17220const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17221 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17222 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17223 if (E->getOpcode() == UO_Deref)
17224 return CheckPossibleDeref(S, E->getSubExpr());
17225 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17226 return CheckPossibleDeref(S, E->getBase());
17227 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17228 return CheckPossibleDeref(S, E->getBase());
17229 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17230 QualType Inner;
17231 QualType Ty = E->getType();
17232 if (const auto *Ptr = Ty->getAs<PointerType>())
17233 Inner = Ptr->getPointeeType();
17234 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17235 Inner = Arr->getElementType();
17236 else
17237 return nullptr;
17238
17239 if (Inner->hasAttr(attr::NoDeref))
17240 return E;
17241 }
17242 return nullptr;
17243}
17244
17245} // namespace
17246
17248 for (const Expr *E : Rec.PossibleDerefs) {
17249 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17250 if (DeclRef) {
17251 const ValueDecl *Decl = DeclRef->getDecl();
17252 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17253 << Decl->getName() << E->getSourceRange();
17254 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17255 } else {
17256 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17257 << E->getSourceRange();
17258 }
17259 }
17260 Rec.PossibleDerefs.clear();
17261}
17262
17265 return;
17266
17267 // Note: ignoring parens here is not justified by the standard rules, but
17268 // ignoring parentheses seems like a more reasonable approach, and this only
17269 // drives a deprecation warning so doesn't affect conformance.
17270 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17271 if (BO->getOpcode() == BO_Assign) {
17272 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17273 llvm::erase(LHSs, BO->getLHS());
17274 }
17275 }
17276}
17277
17279 assert(getLangOpts().CPlusPlus20 &&
17280 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17281 "Cannot mark an immediate escalating expression outside of an "
17282 "immediate escalating context");
17283 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17284 Call && Call->getCallee()) {
17285 if (auto *DeclRef =
17286 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17287 DeclRef->setIsImmediateEscalating(true);
17288 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
17289 Ctr->setIsImmediateEscalating(true);
17290 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
17291 DeclRef->setIsImmediateEscalating(true);
17292 } else {
17293 assert(false && "expected an immediately escalating expression");
17294 }
17296 FI->FoundImmediateEscalatingExpression = true;
17297}
17298
17300 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17301 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17304 return E;
17305
17306 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17307 /// It's OK if this fails; we'll also remove this in
17308 /// HandleImmediateInvocations, but catching it here allows us to avoid
17309 /// walking the AST looking for it in simple cases.
17310 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17311 if (auto *DeclRef =
17312 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17313 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17314
17315 // C++23 [expr.const]/p16
17316 // An expression or conversion is immediate-escalating if it is not initially
17317 // in an immediate function context and it is [...] an immediate invocation
17318 // that is not a constant expression and is not a subexpression of an
17319 // immediate invocation.
17320 APValue Cached;
17321 auto CheckConstantExpressionAndKeepResult = [&]() {
17323 Expr::EvalResult Eval;
17324 Eval.Diag = &Notes;
17325 bool Res = E.get()->EvaluateAsConstantExpr(
17326 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
17327 if (Res && Notes.empty()) {
17328 Cached = std::move(Eval.Val);
17329 return true;
17330 }
17331 return false;
17332 };
17333
17334 if (!E.get()->isValueDependent() &&
17335 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17336 !CheckConstantExpressionAndKeepResult()) {
17338 return E;
17339 }
17340
17341 if (Cleanup.exprNeedsCleanups()) {
17342 // Since an immediate invocation is a full expression itself - it requires
17343 // an additional ExprWithCleanups node, but it can participate to a bigger
17344 // full expression which actually requires cleanups to be run after so
17345 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
17346 // may discard cleanups for outer expression too early.
17347
17348 // Note that ExprWithCleanups created here must always have empty cleanup
17349 // objects:
17350 // - compound literals do not create cleanup objects in C++ and immediate
17351 // invocations are C++-only.
17352 // - blocks are not allowed inside constant expressions and compiler will
17353 // issue an error if they appear there.
17354 //
17355 // Hence, in correct code any cleanup objects created inside current
17356 // evaluation context must be outside the immediate invocation.
17359 }
17360
17362 getASTContext(), E.get(),
17363 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17364 getASTContext()),
17365 /*IsImmediateInvocation*/ true);
17366 if (Cached.hasValue())
17367 Res->MoveIntoResult(Cached, getASTContext());
17368 /// Value-dependent constant expressions should not be immediately
17369 /// evaluated until they are instantiated.
17370 if (!Res->isValueDependent())
17371 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17372 return Res;
17373}
17374
17378 Expr::EvalResult Eval;
17379 Eval.Diag = &Notes;
17380 ConstantExpr *CE = Candidate.getPointer();
17381 bool Result = CE->EvaluateAsConstantExpr(
17382 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17383 if (!Result || !Notes.empty()) {
17385 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17386 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17387 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
17388 FunctionDecl *FD = nullptr;
17389 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17390 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17391 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17392 FD = Call->getConstructor();
17393 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
17394 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
17395
17396 assert(FD && FD->isImmediateFunction() &&
17397 "could not find an immediate function in this expression");
17398 if (FD->isInvalidDecl())
17399 return;
17400 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
17401 << FD << FD->isConsteval();
17402 if (auto Context =
17404 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17405 << Context->Decl;
17406 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17407 }
17408 if (!FD->isConsteval())
17410 for (auto &Note : Notes)
17411 SemaRef.Diag(Note.first, Note.second);
17412 return;
17413 }
17415}
17416
17420 struct ComplexRemove : TreeTransform<ComplexRemove> {
17422 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17425 CurrentII;
17426 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17429 4>::reverse_iterator Current)
17430 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17431 void RemoveImmediateInvocation(ConstantExpr* E) {
17432 auto It = std::find_if(CurrentII, IISet.rend(),
17434 return Elem.getPointer() == E;
17435 });
17436 // It is possible that some subexpression of the current immediate
17437 // invocation was handled from another expression evaluation context. Do
17438 // not handle the current immediate invocation if some of its
17439 // subexpressions failed before.
17440 if (It == IISet.rend()) {
17441 if (SemaRef.FailedImmediateInvocations.contains(E))
17442 CurrentII->setInt(1);
17443 } else {
17444 It->setInt(1); // Mark as deleted
17445 }
17446 }
17447 ExprResult TransformConstantExpr(ConstantExpr *E) {
17448 if (!E->isImmediateInvocation())
17449 return Base::TransformConstantExpr(E);
17450 RemoveImmediateInvocation(E);
17451 return Base::TransformExpr(E->getSubExpr());
17452 }
17453 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17454 /// we need to remove its DeclRefExpr from the DRSet.
17455 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17456 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17457 return Base::TransformCXXOperatorCallExpr(E);
17458 }
17459 /// Base::TransformUserDefinedLiteral doesn't preserve the
17460 /// UserDefinedLiteral node.
17461 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
17462 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
17463 /// here.
17464 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17465 if (!Init)
17466 return Init;
17467 /// ConstantExpr are the first layer of implicit node to be removed so if
17468 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17469 if (auto *CE = dyn_cast<ConstantExpr>(Init))
17470 if (CE->isImmediateInvocation())
17471 RemoveImmediateInvocation(CE);
17472 return Base::TransformInitializer(Init, NotCopyInit);
17473 }
17474 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17475 DRSet.erase(E);
17476 return E;
17477 }
17478 ExprResult TransformLambdaExpr(LambdaExpr *E) {
17479 // Do not rebuild lambdas to avoid creating a new type.
17480 // Lambdas have already been processed inside their eval context.
17481 return E;
17482 }
17483 bool AlwaysRebuild() { return false; }
17484 bool ReplacingOriginal() { return true; }
17485 bool AllowSkippingCXXConstructExpr() {
17486 bool Res = AllowSkippingFirstCXXConstructExpr;
17487 AllowSkippingFirstCXXConstructExpr = true;
17488 return Res;
17489 }
17490 bool AllowSkippingFirstCXXConstructExpr = true;
17491 } Transformer(SemaRef, Rec.ReferenceToConsteval,
17493
17494 /// CXXConstructExpr with a single argument are getting skipped by
17495 /// TreeTransform in some situtation because they could be implicit. This
17496 /// can only occur for the top-level CXXConstructExpr because it is used
17497 /// nowhere in the expression being transformed therefore will not be rebuilt.
17498 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17499 /// skipping the first CXXConstructExpr.
17500 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17501 Transformer.AllowSkippingFirstCXXConstructExpr = false;
17502
17503 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17504 // The result may not be usable in case of previous compilation errors.
17505 // In this case evaluation of the expression may result in crash so just
17506 // don't do anything further with the result.
17507 if (Res.isUsable()) {
17509 It->getPointer()->setSubExpr(Res.get());
17510 }
17511}
17512
17513static void
17516 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17517 Rec.ReferenceToConsteval.size() == 0) ||
17519 return;
17520
17521 /// When we have more than 1 ImmediateInvocationCandidates or previously
17522 /// failed immediate invocations, we need to check for nested
17523 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
17524 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
17525 /// invocation.
17526 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
17528
17529 /// Prevent sema calls during the tree transform from adding pointers that
17530 /// are already in the sets.
17531 llvm::SaveAndRestore DisableIITracking(
17533
17534 /// Prevent diagnostic during tree transfrom as they are duplicates
17536
17537 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17538 It != Rec.ImmediateInvocationCandidates.rend(); It++)
17539 if (!It->getInt())
17541 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17542 Rec.ReferenceToConsteval.size()) {
17543 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17544 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17545 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17546 bool VisitDeclRefExpr(DeclRefExpr *E) {
17547 DRSet.erase(E);
17548 return DRSet.size();
17549 }
17550 } Visitor(Rec.ReferenceToConsteval);
17551 Visitor.TraverseStmt(
17552 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17553 }
17554 for (auto CE : Rec.ImmediateInvocationCandidates)
17555 if (!CE.getInt())
17557 for (auto *DR : Rec.ReferenceToConsteval) {
17558 // If the expression is immediate escalating, it is not an error;
17559 // The outer context itself becomes immediate and further errors,
17560 // if any, will be handled by DiagnoseImmediateEscalatingReason.
17561 if (DR->isImmediateEscalating())
17562 continue;
17563 auto *FD = cast<FunctionDecl>(DR->getDecl());
17564 const NamedDecl *ND = FD;
17565 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
17566 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
17567 ND = MD->getParent();
17568
17569 // C++23 [expr.const]/p16
17570 // An expression or conversion is immediate-escalating if it is not
17571 // initially in an immediate function context and it is [...] a
17572 // potentially-evaluated id-expression that denotes an immediate function
17573 // that is not a subexpression of an immediate invocation.
17574 bool ImmediateEscalating = false;
17575 bool IsPotentiallyEvaluated =
17576 Rec.Context ==
17578 Rec.Context ==
17580 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
17581 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
17582
17584 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
17585 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17586 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
17587 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
17588 if (auto Context =
17590 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17591 << Context->Decl;
17592 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17593 }
17594 if (FD->isImmediateEscalating() && !FD->isConsteval())
17596
17597 } else {
17599 }
17600 }
17601}
17602
17605 unsigned NumTypos = Rec.NumTypos;
17606
17607 if (!Rec.Lambdas.empty()) {
17609 if (!getLangOpts().CPlusPlus20 &&
17610 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17611 Rec.isUnevaluated() ||
17613 unsigned D;
17614 if (Rec.isUnevaluated()) {
17615 // C++11 [expr.prim.lambda]p2:
17616 // A lambda-expression shall not appear in an unevaluated operand
17617 // (Clause 5).
17618 D = diag::err_lambda_unevaluated_operand;
17619 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17620 // C++1y [expr.const]p2:
17621 // A conditional-expression e is a core constant expression unless the
17622 // evaluation of e, following the rules of the abstract machine, would
17623 // evaluate [...] a lambda-expression.
17624 D = diag::err_lambda_in_constant_expression;
17625 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17626 // C++17 [expr.prim.lamda]p2:
17627 // A lambda-expression shall not appear [...] in a template-argument.
17628 D = diag::err_lambda_in_invalid_context;
17629 } else
17630 llvm_unreachable("Couldn't infer lambda error message.");
17631
17632 for (const auto *L : Rec.Lambdas)
17633 Diag(L->getBeginLoc(), D);
17634 }
17635 }
17636
17637 // Append the collected materialized temporaries into previous context before
17638 // exit if the previous also is a lifetime extending context.
17639 auto &PrevRecord = parentEvaluationContext();
17641 PrevRecord.InLifetimeExtendingContext &&
17642 !Rec.ForRangeLifetimeExtendTemps.empty()) {
17643 PrevRecord.ForRangeLifetimeExtendTemps.append(
17645 }
17646
17648 HandleImmediateInvocations(*this, Rec);
17649
17650 // Warn on any volatile-qualified simple-assignments that are not discarded-
17651 // value expressions nor unevaluated operands (those cases get removed from
17652 // this list by CheckUnusedVolatileAssignment).
17653 for (auto *BO : Rec.VolatileAssignmentLHSs)
17654 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17655 << BO->getType();
17656
17657 // When are coming out of an unevaluated context, clear out any
17658 // temporaries that we may have created as part of the evaluation of
17659 // the expression in that context: they aren't relevant because they
17660 // will never be constructed.
17661 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17663 ExprCleanupObjects.end());
17664 Cleanup = Rec.ParentCleanup;
17667 // Otherwise, merge the contexts together.
17668 } else {
17670 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17671 Rec.SavedMaybeODRUseExprs.end());
17672 }
17673
17674 // Pop the current expression evaluation context off the stack.
17675 ExprEvalContexts.pop_back();
17676
17677 // The global expression evaluation context record is never popped.
17678 ExprEvalContexts.back().NumTypos += NumTypos;
17679}
17680
17682 ExprCleanupObjects.erase(
17683 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17684 ExprCleanupObjects.end());
17685 Cleanup.reset();
17686 MaybeODRUseExprs.clear();
17687}
17688
17691 if (Result.isInvalid())
17692 return ExprError();
17693 E = Result.get();
17694 if (!E->getType()->isVariablyModifiedType())
17695 return E;
17697}
17698
17699/// Are we in a context that is potentially constant evaluated per C++20
17700/// [expr.const]p12?
17702 /// C++2a [expr.const]p12:
17703 // An expression or conversion is potentially constant evaluated if it is
17704 switch (SemaRef.ExprEvalContexts.back().Context) {
17707
17708 // -- a manifestly constant-evaluated expression,
17712 // -- a potentially-evaluated expression,
17714 // -- an immediate subexpression of a braced-init-list,
17715
17716 // -- [FIXME] an expression of the form & cast-expression that occurs
17717 // within a templated entity
17718 // -- a subexpression of one of the above that is not a subexpression of
17719 // a nested unevaluated operand.
17720 return true;
17721
17724 // Expressions in this context are never evaluated.
17725 return false;
17726 }
17727 llvm_unreachable("Invalid context");
17728}
17729
17730/// Return true if this function has a calling convention that requires mangling
17731/// in the size of the parameter pack.
17733 // These manglings don't do anything on non-Windows or non-x86 platforms, so
17734 // we don't need parameter type sizes.
17735 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17736 if (!TT.isOSWindows() || !TT.isX86())
17737 return false;
17738
17739 // If this is C++ and this isn't an extern "C" function, parameters do not
17740 // need to be complete. In this case, C++ mangling will apply, which doesn't
17741 // use the size of the parameters.
17742 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17743 return false;
17744
17745 // Stdcall, fastcall, and vectorcall need this special treatment.
17746 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17747 switch (CC) {
17748 case CC_X86StdCall:
17749 case CC_X86FastCall:
17750 case CC_X86VectorCall:
17751 return true;
17752 default:
17753 break;
17754 }
17755 return false;
17756}
17757
17758/// Require that all of the parameter types of function be complete. Normally,
17759/// parameter types are only required to be complete when a function is called
17760/// or defined, but to mangle functions with certain calling conventions, the
17761/// mangler needs to know the size of the parameter list. In this situation,
17762/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17763/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17764/// result in a linker error. Clang doesn't implement this behavior, and instead
17765/// attempts to error at compile time.
17768 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17769 FunctionDecl *FD;
17770 ParmVarDecl *Param;
17771
17772 public:
17773 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17774 : FD(FD), Param(Param) {}
17775
17776 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17777 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17778 StringRef CCName;
17779 switch (CC) {
17780 case CC_X86StdCall:
17781 CCName = "stdcall";
17782 break;
17783 case CC_X86FastCall:
17784 CCName = "fastcall";
17785 break;
17786 case CC_X86VectorCall:
17787 CCName = "vectorcall";
17788 break;
17789 default:
17790 llvm_unreachable("CC does not need mangling");
17791 }
17792
17793 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17794 << Param->getDeclName() << FD->getDeclName() << CCName;
17795 }
17796 };
17797
17798 for (ParmVarDecl *Param : FD->parameters()) {
17799 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17800 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17801 }
17802}
17803
17804namespace {
17805enum class OdrUseContext {
17806 /// Declarations in this context are not odr-used.
17807 None,
17808 /// Declarations in this context are formally odr-used, but this is a
17809 /// dependent context.
17810 Dependent,
17811 /// Declarations in this context are odr-used but not actually used (yet).
17812 FormallyOdrUsed,
17813 /// Declarations in this context are used.
17814 Used
17815};
17816}
17817
17818/// Are we within a context in which references to resolved functions or to
17819/// variables result in odr-use?
17820static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17821 OdrUseContext Result;
17822
17823 switch (SemaRef.ExprEvalContexts.back().Context) {
17827 return OdrUseContext::None;
17828
17832 Result = OdrUseContext::Used;
17833 break;
17834
17836 Result = OdrUseContext::FormallyOdrUsed;
17837 break;
17838
17840 // A default argument formally results in odr-use, but doesn't actually
17841 // result in a use in any real sense until it itself is used.
17842 Result = OdrUseContext::FormallyOdrUsed;
17843 break;
17844 }
17845
17847 return OdrUseContext::Dependent;
17848
17849 return Result;
17850}
17851
17853 if (!Func->isConstexpr())
17854 return false;
17855
17856 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17857 return true;
17858 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17859 return CCD && CCD->getInheritedConstructor();
17860}
17861
17863 bool MightBeOdrUse) {
17864 assert(Func && "No function?");
17865
17866 Func->setReferenced();
17867
17868 // Recursive functions aren't really used until they're used from some other
17869 // context.
17870 bool IsRecursiveCall = CurContext == Func;
17871
17872 // C++11 [basic.def.odr]p3:
17873 // A function whose name appears as a potentially-evaluated expression is
17874 // odr-used if it is the unique lookup result or the selected member of a
17875 // set of overloaded functions [...].
17876 //
17877 // We (incorrectly) mark overload resolution as an unevaluated context, so we
17878 // can just check that here.
17879 OdrUseContext OdrUse =
17880 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17881 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17882 OdrUse = OdrUseContext::FormallyOdrUsed;
17883
17884 // Trivial default constructors and destructors are never actually used.
17885 // FIXME: What about other special members?
17886 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17887 OdrUse == OdrUseContext::Used) {
17888 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17889 if (Constructor->isDefaultConstructor())
17890 OdrUse = OdrUseContext::FormallyOdrUsed;
17891 if (isa<CXXDestructorDecl>(Func))
17892 OdrUse = OdrUseContext::FormallyOdrUsed;
17893 }
17894
17895 // C++20 [expr.const]p12:
17896 // A function [...] is needed for constant evaluation if it is [...] a
17897 // constexpr function that is named by an expression that is potentially
17898 // constant evaluated
17899 bool NeededForConstantEvaluation =
17902
17903 // Determine whether we require a function definition to exist, per
17904 // C++11 [temp.inst]p3:
17905 // Unless a function template specialization has been explicitly
17906 // instantiated or explicitly specialized, the function template
17907 // specialization is implicitly instantiated when the specialization is
17908 // referenced in a context that requires a function definition to exist.
17909 // C++20 [temp.inst]p7:
17910 // The existence of a definition of a [...] function is considered to
17911 // affect the semantics of the program if the [...] function is needed for
17912 // constant evaluation by an expression
17913 // C++20 [basic.def.odr]p10:
17914 // Every program shall contain exactly one definition of every non-inline
17915 // function or variable that is odr-used in that program outside of a
17916 // discarded statement
17917 // C++20 [special]p1:
17918 // The implementation will implicitly define [defaulted special members]
17919 // if they are odr-used or needed for constant evaluation.
17920 //
17921 // Note that we skip the implicit instantiation of templates that are only
17922 // used in unused default arguments or by recursive calls to themselves.
17923 // This is formally non-conforming, but seems reasonable in practice.
17924 bool NeedDefinition =
17925 !IsRecursiveCall &&
17926 (OdrUse == OdrUseContext::Used ||
17927 (NeededForConstantEvaluation && !Func->isPureVirtual()));
17928
17929 // C++14 [temp.expl.spec]p6:
17930 // If a template [...] is explicitly specialized then that specialization
17931 // shall be declared before the first use of that specialization that would
17932 // cause an implicit instantiation to take place, in every translation unit
17933 // in which such a use occurs
17934 if (NeedDefinition &&
17935 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17936 Func->getMemberSpecializationInfo()))
17938
17939 if (getLangOpts().CUDA)
17940 CUDA().CheckCall(Loc, Func);
17941
17942 // If we need a definition, try to create one.
17943 if (NeedDefinition && !Func->getBody()) {
17945 if (CXXConstructorDecl *Constructor =
17946 dyn_cast<CXXConstructorDecl>(Func)) {
17947 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17948 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17949 if (Constructor->isDefaultConstructor()) {
17950 if (Constructor->isTrivial() &&
17951 !Constructor->hasAttr<DLLExportAttr>())
17952 return;
17954 } else if (Constructor->isCopyConstructor()) {
17955 DefineImplicitCopyConstructor(Loc, Constructor);
17956 } else if (Constructor->isMoveConstructor()) {
17957 DefineImplicitMoveConstructor(Loc, Constructor);
17958 }
17959 } else if (Constructor->getInheritedConstructor()) {
17960 DefineInheritingConstructor(Loc, Constructor);
17961 }
17962 } else if (CXXDestructorDecl *Destructor =
17963 dyn_cast<CXXDestructorDecl>(Func)) {
17964 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17965 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17966 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17967 return;
17969 }
17970 if (Destructor->isVirtual() && getLangOpts().AppleKext)
17971 MarkVTableUsed(Loc, Destructor->getParent());
17972 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17973 if (MethodDecl->isOverloadedOperator() &&
17974 MethodDecl->getOverloadedOperator() == OO_Equal) {
17975 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17976 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17977 if (MethodDecl->isCopyAssignmentOperator())
17978 DefineImplicitCopyAssignment(Loc, MethodDecl);
17979 else if (MethodDecl->isMoveAssignmentOperator())
17980 DefineImplicitMoveAssignment(Loc, MethodDecl);
17981 }
17982 } else if (isa<CXXConversionDecl>(MethodDecl) &&
17983 MethodDecl->getParent()->isLambda()) {
17984 CXXConversionDecl *Conversion =
17985 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17986 if (Conversion->isLambdaToBlockPointerConversion())
17988 else
17990 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17991 MarkVTableUsed(Loc, MethodDecl->getParent());
17992 }
17993
17994 if (Func->isDefaulted() && !Func->isDeleted()) {
17998 }
17999
18000 // Implicit instantiation of function templates and member functions of
18001 // class templates.
18002 if (Func->isImplicitlyInstantiable()) {
18004 Func->getTemplateSpecializationKindForInstantiation();
18005 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18006 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18007 if (FirstInstantiation) {
18008 PointOfInstantiation = Loc;
18009 if (auto *MSI = Func->getMemberSpecializationInfo())
18010 MSI->setPointOfInstantiation(Loc);
18011 // FIXME: Notify listener.
18012 else
18013 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18014 } else if (TSK != TSK_ImplicitInstantiation) {
18015 // Use the point of use as the point of instantiation, instead of the
18016 // point of explicit instantiation (which we track as the actual point
18017 // of instantiation). This gives better backtraces in diagnostics.
18018 PointOfInstantiation = Loc;
18019 }
18020
18021 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18022 Func->isConstexpr()) {
18023 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18024 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18025 CodeSynthesisContexts.size())
18027 std::make_pair(Func, PointOfInstantiation));
18028 else if (Func->isConstexpr())
18029 // Do not defer instantiations of constexpr functions, to avoid the
18030 // expression evaluator needing to call back into Sema if it sees a
18031 // call to such a function.
18032 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18033 else {
18034 Func->setInstantiationIsPending(true);
18035 PendingInstantiations.push_back(
18036 std::make_pair(Func, PointOfInstantiation));
18037 // Notify the consumer that a function was implicitly instantiated.
18039 }
18040 }
18041 } else {
18042 // Walk redefinitions, as some of them may be instantiable.
18043 for (auto *i : Func->redecls()) {
18044 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18045 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18046 }
18047 }
18048 });
18049 }
18050
18051 // If a constructor was defined in the context of a default parameter
18052 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18053 // context), its initializers may not be referenced yet.
18054 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18056 *this,
18057 Constructor->isImmediateFunction()
18060 Constructor);
18061 for (CXXCtorInitializer *Init : Constructor->inits()) {
18062 if (Init->isInClassMemberInitializer())
18063 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18064 MarkDeclarationsReferencedInExpr(Init->getInit());
18065 });
18066 }
18067 }
18068
18069 // C++14 [except.spec]p17:
18070 // An exception-specification is considered to be needed when:
18071 // - the function is odr-used or, if it appears in an unevaluated operand,
18072 // would be odr-used if the expression were potentially-evaluated;
18073 //
18074 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18075 // function is a pure virtual function we're calling, and in that case the
18076 // function was selected by overload resolution and we need to resolve its
18077 // exception specification for a different reason.
18078 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18081
18082 // A callee could be called by a host function then by a device function.
18083 // If we only try recording once, we will miss recording the use on device
18084 // side. Therefore keep trying until it is recorded.
18085 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18088
18089 // If this is the first "real" use, act on that.
18090 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18091 // Keep track of used but undefined functions.
18092 if (!Func->isDefined()) {
18093 if (mightHaveNonExternalLinkage(Func))
18094 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18095 else if (Func->getMostRecentDecl()->isInlined() &&
18096 !LangOpts.GNUInline &&
18097 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18098 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18100 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18101 }
18102
18103 // Some x86 Windows calling conventions mangle the size of the parameter
18104 // pack into the name. Computing the size of the parameters requires the
18105 // parameter types to be complete. Check that now.
18108
18109 // In the MS C++ ABI, the compiler emits destructor variants where they are
18110 // used. If the destructor is used here but defined elsewhere, mark the
18111 // virtual base destructors referenced. If those virtual base destructors
18112 // are inline, this will ensure they are defined when emitting the complete
18113 // destructor variant. This checking may be redundant if the destructor is
18114 // provided later in this TU.
18116 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18117 CXXRecordDecl *Parent = Dtor->getParent();
18118 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18120 }
18121 }
18122
18123 Func->markUsed(Context);
18124 }
18125}
18126
18127/// Directly mark a variable odr-used. Given a choice, prefer to use
18128/// MarkVariableReferenced since it does additional checks and then
18129/// calls MarkVarDeclODRUsed.
18130/// If the variable must be captured:
18131/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18132/// - else capture it in the DeclContext that maps to the
18133/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18134static void
18136 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18137 // Keep track of used but undefined variables.
18138 // FIXME: We shouldn't suppress this warning for static data members.
18139 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18140 assert(Var && "expected a capturable variable");
18141
18143 (!Var->isExternallyVisible() || Var->isInline() ||
18145 !(Var->isStaticDataMember() && Var->hasInit())) {
18147 if (old.isInvalid())
18148 old = Loc;
18149 }
18150 QualType CaptureType, DeclRefType;
18151 if (SemaRef.LangOpts.OpenMP)
18154 /*EllipsisLoc*/ SourceLocation(),
18155 /*BuildAndDiagnose*/ true, CaptureType,
18156 DeclRefType, FunctionScopeIndexToStopAt);
18157
18158 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18159 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18160 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18161 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18162 if (VarTarget == SemaCUDA::CVT_Host &&
18163 (UserTarget == CUDAFunctionTarget::Device ||
18164 UserTarget == CUDAFunctionTarget::HostDevice ||
18165 UserTarget == CUDAFunctionTarget::Global)) {
18166 // Diagnose ODR-use of host global variables in device functions.
18167 // Reference of device global variables in host functions is allowed
18168 // through shadow variables therefore it is not diagnosed.
18169 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18170 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18171 << /*host*/ 2 << /*variable*/ 1 << Var
18172 << llvm::to_underlying(UserTarget);
18174 Var->getType().isConstQualified()
18175 ? diag::note_cuda_const_var_unpromoted
18176 : diag::note_cuda_host_var);
18177 }
18178 } else if (VarTarget == SemaCUDA::CVT_Device &&
18179 !Var->hasAttr<CUDASharedAttr>() &&
18180 (UserTarget == CUDAFunctionTarget::Host ||
18181 UserTarget == CUDAFunctionTarget::HostDevice)) {
18182 // Record a CUDA/HIP device side variable if it is ODR-used
18183 // by host code. This is done conservatively, when the variable is
18184 // referenced in any of the following contexts:
18185 // - a non-function context
18186 // - a host function
18187 // - a host device function
18188 // This makes the ODR-use of the device side variable by host code to
18189 // be visible in the device compilation for the compiler to be able to
18190 // emit template variables instantiated by host code only and to
18191 // externalize the static device side variable ODR-used by host code.
18192 if (!Var->hasExternalStorage())
18194 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18195 (!FD || (!FD->getDescribedFunctionTemplate() &&
18199 }
18200 }
18201
18202 V->markUsed(SemaRef.Context);
18203}
18204
18207 unsigned CapturingScopeIndex) {
18208 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18209}
18210
18212 ValueDecl *var) {
18213 DeclContext *VarDC = var->getDeclContext();
18214
18215 // If the parameter still belongs to the translation unit, then
18216 // we're actually just using one parameter in the declaration of
18217 // the next.
18218 if (isa<ParmVarDecl>(var) &&
18219 isa<TranslationUnitDecl>(VarDC))
18220 return;
18221
18222 // For C code, don't diagnose about capture if we're not actually in code
18223 // right now; it's impossible to write a non-constant expression outside of
18224 // function context, so we'll get other (more useful) diagnostics later.
18225 //
18226 // For C++, things get a bit more nasty... it would be nice to suppress this
18227 // diagnostic for certain cases like using a local variable in an array bound
18228 // for a member of a local class, but the correct predicate is not obvious.
18229 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18230 return;
18231
18232 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18233 unsigned ContextKind = 3; // unknown
18234 if (isa<CXXMethodDecl>(VarDC) &&
18235 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18236 ContextKind = 2;
18237 } else if (isa<FunctionDecl>(VarDC)) {
18238 ContextKind = 0;
18239 } else if (isa<BlockDecl>(VarDC)) {
18240 ContextKind = 1;
18241 }
18242
18243 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18244 << var << ValueKind << ContextKind << VarDC;
18245 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18246 << var;
18247
18248 // FIXME: Add additional diagnostic info about class etc. which prevents
18249 // capture.
18250}
18251
18253 ValueDecl *Var,
18254 bool &SubCapturesAreNested,
18255 QualType &CaptureType,
18256 QualType &DeclRefType) {
18257 // Check whether we've already captured it.
18258 if (CSI->CaptureMap.count(Var)) {
18259 // If we found a capture, any subcaptures are nested.
18260 SubCapturesAreNested = true;
18261
18262 // Retrieve the capture type for this variable.
18263 CaptureType = CSI->getCapture(Var).getCaptureType();
18264
18265 // Compute the type of an expression that refers to this variable.
18266 DeclRefType = CaptureType.getNonReferenceType();
18267
18268 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18269 // are mutable in the sense that user can change their value - they are
18270 // private instances of the captured declarations.
18271 const Capture &Cap = CSI->getCapture(Var);
18272 if (Cap.isCopyCapture() &&
18273 !(isa<LambdaScopeInfo>(CSI) &&
18274 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
18275 !(isa<CapturedRegionScopeInfo>(CSI) &&
18276 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18277 DeclRefType.addConst();
18278 return true;
18279 }
18280 return false;
18281}
18282
18283// Only block literals, captured statements, and lambda expressions can
18284// capture; other scopes don't work.
18286 ValueDecl *Var,
18288 const bool Diagnose,
18289 Sema &S) {
18290 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18292
18293 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18294 if (Underlying) {
18295 if (Underlying->hasLocalStorage() && Diagnose)
18297 }
18298 return nullptr;
18299}
18300
18301// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18302// certain types of variables (unnamed, variably modified types etc.)
18303// so check for eligibility.
18305 SourceLocation Loc, const bool Diagnose,
18306 Sema &S) {
18307
18308 assert((isa<VarDecl, BindingDecl>(Var)) &&
18309 "Only variables and structured bindings can be captured");
18310
18311 bool IsBlock = isa<BlockScopeInfo>(CSI);
18312 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18313
18314 // Lambdas are not allowed to capture unnamed variables
18315 // (e.g. anonymous unions).
18316 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18317 // assuming that's the intent.
18318 if (IsLambda && !Var->getDeclName()) {
18319 if (Diagnose) {
18320 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18321 S.Diag(Var->getLocation(), diag::note_declared_at);
18322 }
18323 return false;
18324 }
18325
18326 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18327 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18328 if (Diagnose) {
18329 S.Diag(Loc, diag::err_ref_vm_type);
18330 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18331 }
18332 return false;
18333 }
18334 // Prohibit structs with flexible array members too.
18335 // We cannot capture what is in the tail end of the struct.
18336 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18337 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18338 if (Diagnose) {
18339 if (IsBlock)
18340 S.Diag(Loc, diag::err_ref_flexarray_type);
18341 else
18342 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18343 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18344 }
18345 return false;
18346 }
18347 }
18348 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18349 // Lambdas and captured statements are not allowed to capture __block
18350 // variables; they don't support the expected semantics.
18351 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18352 if (Diagnose) {
18353 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18354 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18355 }
18356 return false;
18357 }
18358 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18359 if (S.getLangOpts().OpenCL && IsBlock &&
18360 Var->getType()->isBlockPointerType()) {
18361 if (Diagnose)
18362 S.Diag(Loc, diag::err_opencl_block_ref_block);
18363 return false;
18364 }
18365
18366 if (isa<BindingDecl>(Var)) {
18367 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18368 if (Diagnose)
18370 return false;
18371 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18372 S.Diag(Loc, S.LangOpts.CPlusPlus20
18373 ? diag::warn_cxx17_compat_capture_binding
18374 : diag::ext_capture_binding)
18375 << Var;
18376 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18377 }
18378 }
18379
18380 return true;
18381}
18382
18383// Returns true if the capture by block was successful.
18385 SourceLocation Loc, const bool BuildAndDiagnose,
18386 QualType &CaptureType, QualType &DeclRefType,
18387 const bool Nested, Sema &S, bool Invalid) {
18388 bool ByRef = false;
18389
18390 // Blocks are not allowed to capture arrays, excepting OpenCL.
18391 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18392 // (decayed to pointers).
18393 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18394 if (BuildAndDiagnose) {
18395 S.Diag(Loc, diag::err_ref_array_type);
18396 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18397 Invalid = true;
18398 } else {
18399 return false;
18400 }
18401 }
18402
18403 // Forbid the block-capture of autoreleasing variables.
18404 if (!Invalid &&
18406 if (BuildAndDiagnose) {
18407 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18408 << /*block*/ 0;
18409 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18410 Invalid = true;
18411 } else {
18412 return false;
18413 }
18414 }
18415
18416 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18417 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18418 QualType PointeeTy = PT->getPointeeType();
18419
18420 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18422 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18423 if (BuildAndDiagnose) {
18424 SourceLocation VarLoc = Var->getLocation();
18425 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18426 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18427 }
18428 }
18429 }
18430
18431 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18432 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18433 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
18434 // Block capture by reference does not change the capture or
18435 // declaration reference types.
18436 ByRef = true;
18437 } else {
18438 // Block capture by copy introduces 'const'.
18439 CaptureType = CaptureType.getNonReferenceType().withConst();
18440 DeclRefType = CaptureType;
18441 }
18442
18443 // Actually capture the variable.
18444 if (BuildAndDiagnose)
18445 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18446 CaptureType, Invalid);
18447
18448 return !Invalid;
18449}
18450
18451/// Capture the given variable in the captured region.
18454 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18455 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18456 bool IsTopScope, Sema &S, bool Invalid) {
18457 // By default, capture variables by reference.
18458 bool ByRef = true;
18459 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18460 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18461 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18462 // Using an LValue reference type is consistent with Lambdas (see below).
18463 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
18464 bool HasConst = DeclRefType.isConstQualified();
18465 DeclRefType = DeclRefType.getUnqualifiedType();
18466 // Don't lose diagnostics about assignments to const.
18467 if (HasConst)
18468 DeclRefType.addConst();
18469 }
18470 // Do not capture firstprivates in tasks.
18471 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
18472 RSI->OpenMPCaptureLevel) != OMPC_unknown)
18473 return true;
18474 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18475 RSI->OpenMPCaptureLevel);
18476 }
18477
18478 if (ByRef)
18479 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18480 else
18481 CaptureType = DeclRefType;
18482
18483 // Actually capture the variable.
18484 if (BuildAndDiagnose)
18485 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18486 Loc, SourceLocation(), CaptureType, Invalid);
18487
18488 return !Invalid;
18489}
18490
18491/// Capture the given variable in the lambda.
18493 SourceLocation Loc, const bool BuildAndDiagnose,
18494 QualType &CaptureType, QualType &DeclRefType,
18495 const bool RefersToCapturedVariable,
18496 const Sema::TryCaptureKind Kind,
18497 SourceLocation EllipsisLoc, const bool IsTopScope,
18498 Sema &S, bool Invalid) {
18499 // Determine whether we are capturing by reference or by value.
18500 bool ByRef = false;
18501 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18502 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18503 } else {
18504 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18505 }
18506
18507 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
18509 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
18510 Invalid = true;
18511 }
18512
18513 // Compute the type of the field that will capture this variable.
18514 if (ByRef) {
18515 // C++11 [expr.prim.lambda]p15:
18516 // An entity is captured by reference if it is implicitly or
18517 // explicitly captured but not captured by copy. It is
18518 // unspecified whether additional unnamed non-static data
18519 // members are declared in the closure type for entities
18520 // captured by reference.
18521 //
18522 // FIXME: It is not clear whether we want to build an lvalue reference
18523 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18524 // to do the former, while EDG does the latter. Core issue 1249 will
18525 // clarify, but for now we follow GCC because it's a more permissive and
18526 // easily defensible position.
18527 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18528 } else {
18529 // C++11 [expr.prim.lambda]p14:
18530 // For each entity captured by copy, an unnamed non-static
18531 // data member is declared in the closure type. The
18532 // declaration order of these members is unspecified. The type
18533 // of such a data member is the type of the corresponding
18534 // captured entity if the entity is not a reference to an
18535 // object, or the referenced type otherwise. [Note: If the
18536 // captured entity is a reference to a function, the
18537 // corresponding data member is also a reference to a
18538 // function. - end note ]
18539 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18540 if (!RefType->getPointeeType()->isFunctionType())
18541 CaptureType = RefType->getPointeeType();
18542 }
18543
18544 // Forbid the lambda copy-capture of autoreleasing variables.
18545 if (!Invalid &&
18547 if (BuildAndDiagnose) {
18548 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18549 S.Diag(Var->getLocation(), diag::note_previous_decl)
18550 << Var->getDeclName();
18551 Invalid = true;
18552 } else {
18553 return false;
18554 }
18555 }
18556
18557 // Make sure that by-copy captures are of a complete and non-abstract type.
18558 if (!Invalid && BuildAndDiagnose) {
18559 if (!CaptureType->isDependentType() &&
18561 Loc, CaptureType,
18562 diag::err_capture_of_incomplete_or_sizeless_type,
18563 Var->getDeclName()))
18564 Invalid = true;
18565 else if (S.RequireNonAbstractType(Loc, CaptureType,
18566 diag::err_capture_of_abstract_type))
18567 Invalid = true;
18568 }
18569 }
18570
18571 // Compute the type of a reference to this captured variable.
18572 if (ByRef)
18573 DeclRefType = CaptureType.getNonReferenceType();
18574 else {
18575 // C++ [expr.prim.lambda]p5:
18576 // The closure type for a lambda-expression has a public inline
18577 // function call operator [...]. This function call operator is
18578 // declared const (9.3.1) if and only if the lambda-expression's
18579 // parameter-declaration-clause is not followed by mutable.
18580 DeclRefType = CaptureType.getNonReferenceType();
18581 bool Const = LSI->lambdaCaptureShouldBeConst();
18582 if (Const && !CaptureType->isReferenceType())
18583 DeclRefType.addConst();
18584 }
18585
18586 // Add the capture.
18587 if (BuildAndDiagnose)
18588 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18589 Loc, EllipsisLoc, CaptureType, Invalid);
18590
18591 return !Invalid;
18592}
18593
18595 const ASTContext &Context) {
18596 // Offer a Copy fix even if the type is dependent.
18597 if (Var->getType()->isDependentType())
18598 return true;
18600 if (T.isTriviallyCopyableType(Context))
18601 return true;
18602 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18603
18604 if (!(RD = RD->getDefinition()))
18605 return false;
18606 if (RD->hasSimpleCopyConstructor())
18607 return true;
18608 if (RD->hasUserDeclaredCopyConstructor())
18609 for (CXXConstructorDecl *Ctor : RD->ctors())
18610 if (Ctor->isCopyConstructor())
18611 return !Ctor->isDeleted();
18612 }
18613 return false;
18614}
18615
18616/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18617/// default capture. Fixes may be omitted if they aren't allowed by the
18618/// standard, for example we can't emit a default copy capture fix-it if we
18619/// already explicitly copy capture capture another variable.
18621 ValueDecl *Var) {
18623 // Don't offer Capture by copy of default capture by copy fixes if Var is
18624 // known not to be copy constructible.
18625 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18626
18627 SmallString<32> FixBuffer;
18628 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18629 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18630 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18631 if (ShouldOfferCopyFix) {
18632 // Offer fixes to insert an explicit capture for the variable.
18633 // [] -> [VarName]
18634 // [OtherCapture] -> [OtherCapture, VarName]
18635 FixBuffer.assign({Separator, Var->getName()});
18636 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18637 << Var << /*value*/ 0
18638 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18639 }
18640 // As above but capture by reference.
18641 FixBuffer.assign({Separator, "&", Var->getName()});
18642 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18643 << Var << /*reference*/ 1
18644 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18645 }
18646
18647 // Only try to offer default capture if there are no captures excluding this
18648 // and init captures.
18649 // [this]: OK.
18650 // [X = Y]: OK.
18651 // [&A, &B]: Don't offer.
18652 // [A, B]: Don't offer.
18653 if (llvm::any_of(LSI->Captures, [](Capture &C) {
18654 return !C.isThisCapture() && !C.isInitCapture();
18655 }))
18656 return;
18657
18658 // The default capture specifiers, '=' or '&', must appear first in the
18659 // capture body.
18660 SourceLocation DefaultInsertLoc =
18662
18663 if (ShouldOfferCopyFix) {
18664 bool CanDefaultCopyCapture = true;
18665 // [=, *this] OK since c++17
18666 // [=, this] OK since c++20
18667 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18668 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18670 : false;
18671 // We can't use default capture by copy if any captures already specified
18672 // capture by copy.
18673 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18674 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18675 })) {
18676 FixBuffer.assign({"=", Separator});
18677 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18678 << /*value*/ 0
18679 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18680 }
18681 }
18682
18683 // We can't use default capture by reference if any captures already specified
18684 // capture by reference.
18685 if (llvm::none_of(LSI->Captures, [](Capture &C) {
18686 return !C.isInitCapture() && C.isReferenceCapture() &&
18687 !C.isThisCapture();
18688 })) {
18689 FixBuffer.assign({"&", Separator});
18690 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18691 << /*reference*/ 1
18692 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18693 }
18694}
18695
18697 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18698 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18699 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18700 // An init-capture is notionally from the context surrounding its
18701 // declaration, but its parent DC is the lambda class.
18702 DeclContext *VarDC = Var->getDeclContext();
18703 DeclContext *DC = CurContext;
18704
18705 // Skip past RequiresExprBodys because they don't constitute function scopes.
18706 while (DC->isRequiresExprBody())
18707 DC = DC->getParent();
18708
18709 // tryCaptureVariable is called every time a DeclRef is formed,
18710 // it can therefore have non-negigible impact on performances.
18711 // For local variables and when there is no capturing scope,
18712 // we can bailout early.
18713 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
18714 return true;
18715
18716 // Exception: Function parameters are not tied to the function's DeclContext
18717 // until we enter the function definition. Capturing them anyway would result
18718 // in an out-of-bounds error while traversing DC and its parents.
18719 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
18720 return true;
18721
18722 const auto *VD = dyn_cast<VarDecl>(Var);
18723 if (VD) {
18724 if (VD->isInitCapture())
18725 VarDC = VarDC->getParent();
18726 } else {
18728 }
18729 assert(VD && "Cannot capture a null variable");
18730
18731 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18732 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18733 // We need to sync up the Declaration Context with the
18734 // FunctionScopeIndexToStopAt
18735 if (FunctionScopeIndexToStopAt) {
18736 unsigned FSIndex = FunctionScopes.size() - 1;
18737 while (FSIndex != MaxFunctionScopesIndex) {
18739 --FSIndex;
18740 }
18741 }
18742
18743 // Capture global variables if it is required to use private copy of this
18744 // variable.
18745 bool IsGlobal = !VD->hasLocalStorage();
18746 if (IsGlobal && !(LangOpts.OpenMP &&
18747 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18748 MaxFunctionScopesIndex)))
18749 return true;
18750
18751 if (isa<VarDecl>(Var))
18752 Var = cast<VarDecl>(Var->getCanonicalDecl());
18753
18754 // Walk up the stack to determine whether we can capture the variable,
18755 // performing the "simple" checks that don't depend on type. We stop when
18756 // we've either hit the declared scope of the variable or find an existing
18757 // capture of that variable. We start from the innermost capturing-entity
18758 // (the DC) and ensure that all intervening capturing-entities
18759 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18760 // declcontext can either capture the variable or have already captured
18761 // the variable.
18762 CaptureType = Var->getType();
18763 DeclRefType = CaptureType.getNonReferenceType();
18764 bool Nested = false;
18765 bool Explicit = (Kind != TryCapture_Implicit);
18766 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18767 do {
18768
18769 LambdaScopeInfo *LSI = nullptr;
18770 if (!FunctionScopes.empty())
18771 LSI = dyn_cast_or_null<LambdaScopeInfo>(
18772 FunctionScopes[FunctionScopesIndex]);
18773
18774 bool IsInScopeDeclarationContext =
18775 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
18776
18777 if (LSI && !LSI->AfterParameterList) {
18778 // This allows capturing parameters from a default value which does not
18779 // seems correct
18780 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
18781 return true;
18782 }
18783 // If the variable is declared in the current context, there is no need to
18784 // capture it.
18785 if (IsInScopeDeclarationContext &&
18786 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
18787 return true;
18788
18789 // Only block literals, captured statements, and lambda expressions can
18790 // capture; other scopes don't work.
18791 DeclContext *ParentDC =
18792 !IsInScopeDeclarationContext
18793 ? DC->getParent()
18794 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
18795 BuildAndDiagnose, *this);
18796 // We need to check for the parent *first* because, if we *have*
18797 // private-captured a global variable, we need to recursively capture it in
18798 // intermediate blocks, lambdas, etc.
18799 if (!ParentDC) {
18800 if (IsGlobal) {
18801 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18802 break;
18803 }
18804 return true;
18805 }
18806
18807 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
18808 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18809
18810 // Check whether we've already captured it.
18811 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18812 DeclRefType)) {
18813 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18814 break;
18815 }
18816
18817 // When evaluating some attributes (like enable_if) we might refer to a
18818 // function parameter appertaining to the same declaration as that
18819 // attribute.
18820 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
18821 Parm && Parm->getDeclContext() == DC)
18822 return true;
18823
18824 // If we are instantiating a generic lambda call operator body,
18825 // we do not want to capture new variables. What was captured
18826 // during either a lambdas transformation or initial parsing
18827 // should be used.
18829 if (BuildAndDiagnose) {
18830 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18832 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18833 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18834 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18835 buildLambdaCaptureFixit(*this, LSI, Var);
18836 } else
18838 }
18839 return true;
18840 }
18841
18842 // Try to capture variable-length arrays types.
18843 if (Var->getType()->isVariablyModifiedType()) {
18844 // We're going to walk down into the type and look for VLA
18845 // expressions.
18846 QualType QTy = Var->getType();
18847 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18848 QTy = PVD->getOriginalType();
18850 }
18851
18852 if (getLangOpts().OpenMP) {
18853 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18854 // OpenMP private variables should not be captured in outer scope, so
18855 // just break here. Similarly, global variables that are captured in a
18856 // target region should not be captured outside the scope of the region.
18857 if (RSI->CapRegionKind == CR_OpenMP) {
18858 // FIXME: We should support capturing structured bindings in OpenMP.
18859 if (isa<BindingDecl>(Var)) {
18860 if (BuildAndDiagnose) {
18861 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
18862 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18863 }
18864 return true;
18865 }
18866 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
18867 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18868 // If the variable is private (i.e. not captured) and has variably
18869 // modified type, we still need to capture the type for correct
18870 // codegen in all regions, associated with the construct. Currently,
18871 // it is captured in the innermost captured region only.
18872 if (IsOpenMPPrivateDecl != OMPC_unknown &&
18873 Var->getType()->isVariablyModifiedType()) {
18874 QualType QTy = Var->getType();
18875 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18876 QTy = PVD->getOriginalType();
18877 for (int I = 1,
18878 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
18879 I < E; ++I) {
18880 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18881 FunctionScopes[FunctionScopesIndex - I]);
18882 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
18883 "Wrong number of captured regions associated with the "
18884 "OpenMP construct.");
18885 captureVariablyModifiedType(Context, QTy, OuterRSI);
18886 }
18887 }
18888 bool IsTargetCap =
18889 IsOpenMPPrivateDecl != OMPC_private &&
18890 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18891 RSI->OpenMPCaptureLevel);
18892 // Do not capture global if it is not privatized in outer regions.
18893 bool IsGlobalCap =
18894 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
18895 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18896
18897 // When we detect target captures we are looking from inside the
18898 // target region, therefore we need to propagate the capture from the
18899 // enclosing region. Therefore, the capture is not initially nested.
18900 if (IsTargetCap)
18901 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
18902 RSI->OpenMPLevel);
18903
18904 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18905 (IsGlobal && !IsGlobalCap)) {
18906 Nested = !IsTargetCap;
18907 bool HasConst = DeclRefType.isConstQualified();
18908 DeclRefType = DeclRefType.getUnqualifiedType();
18909 // Don't lose diagnostics about assignments to const.
18910 if (HasConst)
18911 DeclRefType.addConst();
18912 CaptureType = Context.getLValueReferenceType(DeclRefType);
18913 break;
18914 }
18915 }
18916 }
18917 }
18918 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18919 // No capture-default, and this is not an explicit capture
18920 // so cannot capture this variable.
18921 if (BuildAndDiagnose) {
18922 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18923 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18924 auto *LSI = cast<LambdaScopeInfo>(CSI);
18925 if (LSI->Lambda) {
18926 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18927 buildLambdaCaptureFixit(*this, LSI, Var);
18928 }
18929 // FIXME: If we error out because an outer lambda can not implicitly
18930 // capture a variable that an inner lambda explicitly captures, we
18931 // should have the inner lambda do the explicit capture - because
18932 // it makes for cleaner diagnostics later. This would purely be done
18933 // so that the diagnostic does not misleadingly claim that a variable
18934 // can not be captured by a lambda implicitly even though it is captured
18935 // explicitly. Suggestion:
18936 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18937 // at the function head
18938 // - cache the StartingDeclContext - this must be a lambda
18939 // - captureInLambda in the innermost lambda the variable.
18940 }
18941 return true;
18942 }
18943 Explicit = false;
18944 FunctionScopesIndex--;
18945 if (IsInScopeDeclarationContext)
18946 DC = ParentDC;
18947 } while (!VarDC->Equals(DC));
18948
18949 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18950 // computing the type of the capture at each step, checking type-specific
18951 // requirements, and adding captures if requested.
18952 // If the variable had already been captured previously, we start capturing
18953 // at the lambda nested within that one.
18954 bool Invalid = false;
18955 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18956 ++I) {
18957 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18958
18959 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18960 // certain types of variables (unnamed, variably modified types etc.)
18961 // so check for eligibility.
18962 if (!Invalid)
18963 Invalid =
18964 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18965
18966 // After encountering an error, if we're actually supposed to capture, keep
18967 // capturing in nested contexts to suppress any follow-on diagnostics.
18968 if (Invalid && !BuildAndDiagnose)
18969 return true;
18970
18971 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18972 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18973 DeclRefType, Nested, *this, Invalid);
18974 Nested = true;
18975 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18977 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18978 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18979 Nested = true;
18980 } else {
18981 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18982 Invalid =
18983 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18984 DeclRefType, Nested, Kind, EllipsisLoc,
18985 /*IsTopScope*/ I == N - 1, *this, Invalid);
18986 Nested = true;
18987 }
18988
18989 if (Invalid && !BuildAndDiagnose)
18990 return true;
18991 }
18992 return Invalid;
18993}
18994
18996 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18997 QualType CaptureType;
18998 QualType DeclRefType;
18999 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19000 /*BuildAndDiagnose=*/true, CaptureType,
19001 DeclRefType, nullptr);
19002}
19003
19005 QualType CaptureType;
19006 QualType DeclRefType;
19008 /*BuildAndDiagnose=*/false, CaptureType,
19009 DeclRefType, nullptr);
19010}
19011
19013 QualType CaptureType;
19014 QualType DeclRefType;
19015
19016 // Determine whether we can capture this variable.
19018 /*BuildAndDiagnose=*/false, CaptureType,
19019 DeclRefType, nullptr))
19020 return QualType();
19021
19022 return DeclRefType;
19023}
19024
19025namespace {
19026// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19027// The produced TemplateArgumentListInfo* points to data stored within this
19028// object, so should only be used in contexts where the pointer will not be
19029// used after the CopiedTemplateArgs object is destroyed.
19030class CopiedTemplateArgs {
19031 bool HasArgs;
19032 TemplateArgumentListInfo TemplateArgStorage;
19033public:
19034 template<typename RefExpr>
19035 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19036 if (HasArgs)
19037 E->copyTemplateArgumentsInto(TemplateArgStorage);
19038 }
19039 operator TemplateArgumentListInfo*()
19040#ifdef __has_cpp_attribute
19041#if __has_cpp_attribute(clang::lifetimebound)
19042 [[clang::lifetimebound]]
19043#endif
19044#endif
19045 {
19046 return HasArgs ? &TemplateArgStorage : nullptr;
19047 }
19048};
19049}
19050
19051/// Walk the set of potential results of an expression and mark them all as
19052/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19053///
19054/// \return A new expression if we found any potential results, ExprEmpty() if
19055/// not, and ExprError() if we diagnosed an error.
19057 NonOdrUseReason NOUR) {
19058 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19059 // an object that satisfies the requirements for appearing in a
19060 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19061 // is immediately applied." This function handles the lvalue-to-rvalue
19062 // conversion part.
19063 //
19064 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19065 // transform it into the relevant kind of non-odr-use node and rebuild the
19066 // tree of nodes leading to it.
19067 //
19068 // This is a mini-TreeTransform that only transforms a restricted subset of
19069 // nodes (and only certain operands of them).
19070
19071 // Rebuild a subexpression.
19072 auto Rebuild = [&](Expr *Sub) {
19073 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19074 };
19075
19076 // Check whether a potential result satisfies the requirements of NOUR.
19077 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19078 // Any entity other than a VarDecl is always odr-used whenever it's named
19079 // in a potentially-evaluated expression.
19080 auto *VD = dyn_cast<VarDecl>(D);
19081 if (!VD)
19082 return true;
19083
19084 // C++2a [basic.def.odr]p4:
19085 // A variable x whose name appears as a potentially-evalauted expression
19086 // e is odr-used by e unless
19087 // -- x is a reference that is usable in constant expressions, or
19088 // -- x is a variable of non-reference type that is usable in constant
19089 // expressions and has no mutable subobjects, and e is an element of
19090 // the set of potential results of an expression of
19091 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19092 // conversion is applied, or
19093 // -- x is a variable of non-reference type, and e is an element of the
19094 // set of potential results of a discarded-value expression to which
19095 // the lvalue-to-rvalue conversion is not applied
19096 //
19097 // We check the first bullet and the "potentially-evaluated" condition in
19098 // BuildDeclRefExpr. We check the type requirements in the second bullet
19099 // in CheckLValueToRValueConversionOperand below.
19100 switch (NOUR) {
19101 case NOUR_None:
19102 case NOUR_Unevaluated:
19103 llvm_unreachable("unexpected non-odr-use-reason");
19104
19105 case NOUR_Constant:
19106 // Constant references were handled when they were built.
19107 if (VD->getType()->isReferenceType())
19108 return true;
19109 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19110 if (RD->hasMutableFields())
19111 return true;
19112 if (!VD->isUsableInConstantExpressions(S.Context))
19113 return true;
19114 break;
19115
19116 case NOUR_Discarded:
19117 if (VD->getType()->isReferenceType())
19118 return true;
19119 break;
19120 }
19121 return false;
19122 };
19123
19124 // Mark that this expression does not constitute an odr-use.
19125 auto MarkNotOdrUsed = [&] {
19126 S.MaybeODRUseExprs.remove(E);
19127 if (LambdaScopeInfo *LSI = S.getCurLambda())
19128 LSI->markVariableExprAsNonODRUsed(E);
19129 };
19130
19131 // C++2a [basic.def.odr]p2:
19132 // The set of potential results of an expression e is defined as follows:
19133 switch (E->getStmtClass()) {
19134 // -- If e is an id-expression, ...
19135 case Expr::DeclRefExprClass: {
19136 auto *DRE = cast<DeclRefExpr>(E);
19137 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19138 break;
19139
19140 // Rebuild as a non-odr-use DeclRefExpr.
19141 MarkNotOdrUsed();
19142 return DeclRefExpr::Create(
19143 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19144 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19145 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19146 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19147 }
19148
19149 case Expr::FunctionParmPackExprClass: {
19150 auto *FPPE = cast<FunctionParmPackExpr>(E);
19151 // If any of the declarations in the pack is odr-used, then the expression
19152 // as a whole constitutes an odr-use.
19153 for (VarDecl *D : *FPPE)
19154 if (IsPotentialResultOdrUsed(D))
19155 return ExprEmpty();
19156
19157 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19158 // nothing cares about whether we marked this as an odr-use, but it might
19159 // be useful for non-compiler tools.
19160 MarkNotOdrUsed();
19161 break;
19162 }
19163
19164 // -- If e is a subscripting operation with an array operand...
19165 case Expr::ArraySubscriptExprClass: {
19166 auto *ASE = cast<ArraySubscriptExpr>(E);
19167 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19168 if (!OldBase->getType()->isArrayType())
19169 break;
19170 ExprResult Base = Rebuild(OldBase);
19171 if (!Base.isUsable())
19172 return Base;
19173 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19174 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19175 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19176 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19177 ASE->getRBracketLoc());
19178 }
19179
19180 case Expr::MemberExprClass: {
19181 auto *ME = cast<MemberExpr>(E);
19182 // -- If e is a class member access expression [...] naming a non-static
19183 // data member...
19184 if (isa<FieldDecl>(ME->getMemberDecl())) {
19185 ExprResult Base = Rebuild(ME->getBase());
19186 if (!Base.isUsable())
19187 return Base;
19188 return MemberExpr::Create(
19189 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19190 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19191 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19192 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19193 ME->getObjectKind(), ME->isNonOdrUse());
19194 }
19195
19196 if (ME->getMemberDecl()->isCXXInstanceMember())
19197 break;
19198
19199 // -- If e is a class member access expression naming a static data member,
19200 // ...
19201 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19202 break;
19203
19204 // Rebuild as a non-odr-use MemberExpr.
19205 MarkNotOdrUsed();
19206 return MemberExpr::Create(
19207 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19208 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19209 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19210 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19211 }
19212
19213 case Expr::BinaryOperatorClass: {
19214 auto *BO = cast<BinaryOperator>(E);
19215 Expr *LHS = BO->getLHS();
19216 Expr *RHS = BO->getRHS();
19217 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19218 if (BO->getOpcode() == BO_PtrMemD) {
19219 ExprResult Sub = Rebuild(LHS);
19220 if (!Sub.isUsable())
19221 return Sub;
19222 BO->setLHS(Sub.get());
19223 // -- If e is a comma expression, ...
19224 } else if (BO->getOpcode() == BO_Comma) {
19225 ExprResult Sub = Rebuild(RHS);
19226 if (!Sub.isUsable())
19227 return Sub;
19228 BO->setRHS(Sub.get());
19229 } else {
19230 break;
19231 }
19232 return ExprResult(BO);
19233 }
19234
19235 // -- If e has the form (e1)...
19236 case Expr::ParenExprClass: {
19237 auto *PE = cast<ParenExpr>(E);
19238 ExprResult Sub = Rebuild(PE->getSubExpr());
19239 if (!Sub.isUsable())
19240 return Sub;
19241 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19242 }
19243
19244 // -- If e is a glvalue conditional expression, ...
19245 // We don't apply this to a binary conditional operator. FIXME: Should we?
19246 case Expr::ConditionalOperatorClass: {
19247 auto *CO = cast<ConditionalOperator>(E);
19248 ExprResult LHS = Rebuild(CO->getLHS());
19249 if (LHS.isInvalid())
19250 return ExprError();
19251 ExprResult RHS = Rebuild(CO->getRHS());
19252 if (RHS.isInvalid())
19253 return ExprError();
19254 if (!LHS.isUsable() && !RHS.isUsable())
19255 return ExprEmpty();
19256 if (!LHS.isUsable())
19257 LHS = CO->getLHS();
19258 if (!RHS.isUsable())
19259 RHS = CO->getRHS();
19260 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19261 CO->getCond(), LHS.get(), RHS.get());
19262 }
19263
19264 // [Clang extension]
19265 // -- If e has the form __extension__ e1...
19266 case Expr::UnaryOperatorClass: {
19267 auto *UO = cast<UnaryOperator>(E);
19268 if (UO->getOpcode() != UO_Extension)
19269 break;
19270 ExprResult Sub = Rebuild(UO->getSubExpr());
19271 if (!Sub.isUsable())
19272 return Sub;
19273 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19274 Sub.get());
19275 }
19276
19277 // [Clang extension]
19278 // -- If e has the form _Generic(...), the set of potential results is the
19279 // union of the sets of potential results of the associated expressions.
19280 case Expr::GenericSelectionExprClass: {
19281 auto *GSE = cast<GenericSelectionExpr>(E);
19282
19283 SmallVector<Expr *, 4> AssocExprs;
19284 bool AnyChanged = false;
19285 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19286 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19287 if (AssocExpr.isInvalid())
19288 return ExprError();
19289 if (AssocExpr.isUsable()) {
19290 AssocExprs.push_back(AssocExpr.get());
19291 AnyChanged = true;
19292 } else {
19293 AssocExprs.push_back(OrigAssocExpr);
19294 }
19295 }
19296
19297 void *ExOrTy = nullptr;
19298 bool IsExpr = GSE->isExprPredicate();
19299 if (IsExpr)
19300 ExOrTy = GSE->getControllingExpr();
19301 else
19302 ExOrTy = GSE->getControllingType();
19303 return AnyChanged ? S.CreateGenericSelectionExpr(
19304 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19305 GSE->getRParenLoc(), IsExpr, ExOrTy,
19306 GSE->getAssocTypeSourceInfos(), AssocExprs)
19307 : ExprEmpty();
19308 }
19309
19310 // [Clang extension]
19311 // -- If e has the form __builtin_choose_expr(...), the set of potential
19312 // results is the union of the sets of potential results of the
19313 // second and third subexpressions.
19314 case Expr::ChooseExprClass: {
19315 auto *CE = cast<ChooseExpr>(E);
19316
19317 ExprResult LHS = Rebuild(CE->getLHS());
19318 if (LHS.isInvalid())
19319 return ExprError();
19320
19321 ExprResult RHS = Rebuild(CE->getLHS());
19322 if (RHS.isInvalid())
19323 return ExprError();
19324
19325 if (!LHS.get() && !RHS.get())
19326 return ExprEmpty();
19327 if (!LHS.isUsable())
19328 LHS = CE->getLHS();
19329 if (!RHS.isUsable())
19330 RHS = CE->getRHS();
19331
19332 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19333 RHS.get(), CE->getRParenLoc());
19334 }
19335
19336 // Step through non-syntactic nodes.
19337 case Expr::ConstantExprClass: {
19338 auto *CE = cast<ConstantExpr>(E);
19339 ExprResult Sub = Rebuild(CE->getSubExpr());
19340 if (!Sub.isUsable())
19341 return Sub;
19342 return ConstantExpr::Create(S.Context, Sub.get());
19343 }
19344
19345 // We could mostly rely on the recursive rebuilding to rebuild implicit
19346 // casts, but not at the top level, so rebuild them here.
19347 case Expr::ImplicitCastExprClass: {
19348 auto *ICE = cast<ImplicitCastExpr>(E);
19349 // Only step through the narrow set of cast kinds we expect to encounter.
19350 // Anything else suggests we've left the region in which potential results
19351 // can be found.
19352 switch (ICE->getCastKind()) {
19353 case CK_NoOp:
19354 case CK_DerivedToBase:
19355 case CK_UncheckedDerivedToBase: {
19356 ExprResult Sub = Rebuild(ICE->getSubExpr());
19357 if (!Sub.isUsable())
19358 return Sub;
19359 CXXCastPath Path(ICE->path());
19360 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19361 ICE->getValueKind(), &Path);
19362 }
19363
19364 default:
19365 break;
19366 }
19367 break;
19368 }
19369
19370 default:
19371 break;
19372 }
19373
19374 // Can't traverse through this node. Nothing to do.
19375 return ExprEmpty();
19376}
19377
19379 // Check whether the operand is or contains an object of non-trivial C union
19380 // type.
19381 if (E->getType().isVolatileQualified() &&
19387
19388 // C++2a [basic.def.odr]p4:
19389 // [...] an expression of non-volatile-qualified non-class type to which
19390 // the lvalue-to-rvalue conversion is applied [...]
19392 return E;
19393
19396 if (Result.isInvalid())
19397 return ExprError();
19398 return Result.get() ? Result : E;
19399}
19400
19402 Res = CorrectDelayedTyposInExpr(Res);
19403
19404 if (!Res.isUsable())
19405 return Res;
19406
19407 // If a constant-expression is a reference to a variable where we delay
19408 // deciding whether it is an odr-use, just assume we will apply the
19409 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19410 // (a non-type template argument), we have special handling anyway.
19412}
19413
19415 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19416 // call.
19417 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19418 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19419
19420 for (Expr *E : LocalMaybeODRUseExprs) {
19421 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19422 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19423 DRE->getLocation(), *this);
19424 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19425 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19426 *this);
19427 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19428 for (VarDecl *VD : *FP)
19429 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19430 } else {
19431 llvm_unreachable("Unexpected expression");
19432 }
19433 }
19434
19435 assert(MaybeODRUseExprs.empty() &&
19436 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19437}
19438
19440 ValueDecl *Var, Expr *E) {
19442 if (!VD)
19443 return;
19444
19445 const bool RefersToEnclosingScope =
19446 (SemaRef.CurContext != VD->getDeclContext() &&
19448 if (RefersToEnclosingScope) {
19449 LambdaScopeInfo *const LSI =
19450 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19451 if (LSI && (!LSI->CallOperator ||
19452 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19453 // If a variable could potentially be odr-used, defer marking it so
19454 // until we finish analyzing the full expression for any
19455 // lvalue-to-rvalue
19456 // or discarded value conversions that would obviate odr-use.
19457 // Add it to the list of potential captures that will be analyzed
19458 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19459 // unless the variable is a reference that was initialized by a constant
19460 // expression (this will never need to be captured or odr-used).
19461 //
19462 // FIXME: We can simplify this a lot after implementing P0588R1.
19463 assert(E && "Capture variable should be used in an expression.");
19464 if (!Var->getType()->isReferenceType() ||
19467 }
19468 }
19469}
19470
19473 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19474 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19475 isa<FunctionParmPackExpr>(E)) &&
19476 "Invalid Expr argument to DoMarkVarDeclReferenced");
19477 Var->setReferenced();
19478
19479 if (Var->isInvalidDecl())
19480 return;
19481
19482 auto *MSI = Var->getMemberSpecializationInfo();
19485
19486 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19487 bool UsableInConstantExpr =
19489
19490 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19491 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19492 }
19493
19494 // C++20 [expr.const]p12:
19495 // A variable [...] is needed for constant evaluation if it is [...] a
19496 // variable whose name appears as a potentially constant evaluated
19497 // expression that is either a contexpr variable or is of non-volatile
19498 // const-qualified integral type or of reference type
19499 bool NeededForConstantEvaluation =
19500 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19501
19502 bool NeedDefinition =
19503 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19504
19505 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19506 "Can't instantiate a partial template specialization.");
19507
19508 // If this might be a member specialization of a static data member, check
19509 // the specialization is visible. We already did the checks for variable
19510 // template specializations when we created them.
19511 if (NeedDefinition && TSK != TSK_Undeclared &&
19512 !isa<VarTemplateSpecializationDecl>(Var))
19514
19515 // Perform implicit instantiation of static data members, static data member
19516 // templates of class templates, and variable template specializations. Delay
19517 // instantiations of variable templates, except for those that could be used
19518 // in a constant expression.
19519 if (NeedDefinition && isTemplateInstantiation(TSK)) {
19520 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19521 // instantiation declaration if a variable is usable in a constant
19522 // expression (among other cases).
19523 bool TryInstantiating =
19525 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19526
19527 if (TryInstantiating) {
19528 SourceLocation PointOfInstantiation =
19529 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19530 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19531 if (FirstInstantiation) {
19532 PointOfInstantiation = Loc;
19533 if (MSI)
19534 MSI->setPointOfInstantiation(PointOfInstantiation);
19535 // FIXME: Notify listener.
19536 else
19537 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19538 }
19539
19540 if (UsableInConstantExpr) {
19541 // Do not defer instantiations of variables that could be used in a
19542 // constant expression.
19543 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19544 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19545 });
19546
19547 // Re-set the member to trigger a recomputation of the dependence bits
19548 // for the expression.
19549 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19550 DRE->setDecl(DRE->getDecl());
19551 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19552 ME->setMemberDecl(ME->getMemberDecl());
19553 } else if (FirstInstantiation) {
19555 .push_back(std::make_pair(Var, PointOfInstantiation));
19556 } else {
19557 bool Inserted = false;
19558 for (auto &I : SemaRef.SavedPendingInstantiations) {
19559 auto Iter = llvm::find_if(
19560 I, [Var](const Sema::PendingImplicitInstantiation &P) {
19561 return P.first == Var;
19562 });
19563 if (Iter != I.end()) {
19565 I.erase(Iter);
19566 Inserted = true;
19567 break;
19568 }
19569 }
19570
19571 // FIXME: For a specialization of a variable template, we don't
19572 // distinguish between "declaration and type implicitly instantiated"
19573 // and "implicit instantiation of definition requested", so we have
19574 // no direct way to avoid enqueueing the pending instantiation
19575 // multiple times.
19576 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
19578 .push_back(std::make_pair(Var, PointOfInstantiation));
19579 }
19580 }
19581 }
19582
19583 // C++2a [basic.def.odr]p4:
19584 // A variable x whose name appears as a potentially-evaluated expression e
19585 // is odr-used by e unless
19586 // -- x is a reference that is usable in constant expressions
19587 // -- x is a variable of non-reference type that is usable in constant
19588 // expressions and has no mutable subobjects [FIXME], and e is an
19589 // element of the set of potential results of an expression of
19590 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19591 // conversion is applied
19592 // -- x is a variable of non-reference type, and e is an element of the set
19593 // of potential results of a discarded-value expression to which the
19594 // lvalue-to-rvalue conversion is not applied [FIXME]
19595 //
19596 // We check the first part of the second bullet here, and
19597 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19598 // FIXME: To get the third bullet right, we need to delay this even for
19599 // variables that are not usable in constant expressions.
19600
19601 // If we already know this isn't an odr-use, there's nothing more to do.
19602 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19603 if (DRE->isNonOdrUse())
19604 return;
19605 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19606 if (ME->isNonOdrUse())
19607 return;
19608
19609 switch (OdrUse) {
19610 case OdrUseContext::None:
19611 // In some cases, a variable may not have been marked unevaluated, if it
19612 // appears in a defaukt initializer.
19613 assert((!E || isa<FunctionParmPackExpr>(E) ||
19615 "missing non-odr-use marking for unevaluated decl ref");
19616 break;
19617
19618 case OdrUseContext::FormallyOdrUsed:
19619 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19620 // behavior.
19621 break;
19622
19623 case OdrUseContext::Used:
19624 // If we might later find that this expression isn't actually an odr-use,
19625 // delay the marking.
19627 SemaRef.MaybeODRUseExprs.insert(E);
19628 else
19630 break;
19631
19632 case OdrUseContext::Dependent:
19633 // If this is a dependent context, we don't need to mark variables as
19634 // odr-used, but we may still need to track them for lambda capture.
19635 // FIXME: Do we also need to do this inside dependent typeid expressions
19636 // (which are modeled as unevaluated at this point)?
19638 break;
19639 }
19640}
19641
19643 BindingDecl *BD, Expr *E) {
19644 BD->setReferenced();
19645
19646 if (BD->isInvalidDecl())
19647 return;
19648
19649 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19650 if (OdrUse == OdrUseContext::Used) {
19651 QualType CaptureType, DeclRefType;
19653 /*EllipsisLoc*/ SourceLocation(),
19654 /*BuildAndDiagnose*/ true, CaptureType,
19655 DeclRefType,
19656 /*FunctionScopeIndexToStopAt*/ nullptr);
19657 } else if (OdrUse == OdrUseContext::Dependent) {
19659 }
19660}
19661
19663 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19664}
19665
19666// C++ [temp.dep.expr]p3:
19667// An id-expression is type-dependent if it contains:
19668// - an identifier associated by name lookup with an entity captured by copy
19669// in a lambda-expression that has an explicit object parameter whose type
19670// is dependent ([dcl.fct]),
19672 Sema &SemaRef, ValueDecl *D, Expr *E) {
19673 auto *ID = dyn_cast<DeclRefExpr>(E);
19674 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
19675 return;
19676
19677 // If any enclosing lambda with a dependent explicit object parameter either
19678 // explicitly captures the variable by value, or has a capture default of '='
19679 // and does not capture the variable by reference, then the type of the DRE
19680 // is dependent on the type of that lambda's explicit object parameter.
19681 auto IsDependent = [&]() {
19682 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
19683 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
19684 if (!LSI)
19685 continue;
19686
19687 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
19688 LSI->AfterParameterList)
19689 return false;
19690
19691 const auto *MD = LSI->CallOperator;
19692 if (MD->getType().isNull())
19693 continue;
19694
19695 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
19696 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
19697 !Ty->getParamType(0)->isDependentType())
19698 continue;
19699
19700 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
19701 if (C->isCopyCapture())
19702 return true;
19703 continue;
19704 }
19705
19706 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
19707 return true;
19708 }
19709 return false;
19710 }();
19711
19712 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
19713 IsDependent, SemaRef.getASTContext());
19714}
19715
19716static void
19718 bool MightBeOdrUse,
19719 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19722
19723 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19725 if (SemaRef.getLangOpts().CPlusPlus)
19727 Var, E);
19728 return;
19729 }
19730
19731 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
19733 if (SemaRef.getLangOpts().CPlusPlus)
19735 Decl, E);
19736 return;
19737 }
19738 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19739
19740 // If this is a call to a method via a cast, also mark the method in the
19741 // derived class used in case codegen can devirtualize the call.
19742 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19743 if (!ME)
19744 return;
19745 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19746 if (!MD)
19747 return;
19748 // Only attempt to devirtualize if this is truly a virtual call.
19749 bool IsVirtualCall = MD->isVirtual() &&
19751 if (!IsVirtualCall)
19752 return;
19753
19754 // If it's possible to devirtualize the call, mark the called function
19755 // referenced.
19757 ME->getBase(), SemaRef.getLangOpts().AppleKext);
19758 if (DM)
19759 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19760}
19761
19763 // TODO: update this with DR# once a defect report is filed.
19764 // C++11 defect. The address of a pure member should not be an ODR use, even
19765 // if it's a qualified reference.
19766 bool OdrUse = true;
19767 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19768 if (Method->isVirtual() &&
19769 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19770 OdrUse = false;
19771
19772 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
19776 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
19777 !FD->isDependentContext())
19778 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19779 }
19780 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19782}
19783
19785 // C++11 [basic.def.odr]p2:
19786 // A non-overloaded function whose name appears as a potentially-evaluated
19787 // expression or a member of a set of candidate functions, if selected by
19788 // overload resolution when referred to from a potentially-evaluated
19789 // expression, is odr-used, unless it is a pure virtual function and its
19790 // name is not explicitly qualified.
19791 bool MightBeOdrUse = true;
19792 if (E->performsVirtualDispatch(getLangOpts())) {
19793 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
19794 if (Method->isPureVirtual())
19795 MightBeOdrUse = false;
19796 }
19798 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19799 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19801}
19802
19804 for (VarDecl *VD : *E)
19805 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19807}
19808
19809/// Perform marking for a reference to an arbitrary declaration. It
19810/// marks the declaration referenced, and performs odr-use checking for
19811/// functions and variables. This method should not be used when building a
19812/// normal expression which refers to a variable.
19814 bool MightBeOdrUse) {
19815 if (MightBeOdrUse) {
19816 if (auto *VD = dyn_cast<VarDecl>(D)) {
19818 return;
19819 }
19820 }
19821 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19822 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19823 return;
19824 }
19825 D->setReferenced();
19826}
19827
19828namespace {
19829 // Mark all of the declarations used by a type as referenced.
19830 // FIXME: Not fully implemented yet! We need to have a better understanding
19831 // of when we're entering a context we should not recurse into.
19832 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19833 // TreeTransforms rebuilding the type in a new context. Rather than
19834 // duplicating the TreeTransform logic, we should consider reusing it here.
19835 // Currently that causes problems when rebuilding LambdaExprs.
19836 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19837 Sema &S;
19839
19840 public:
19842
19843 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19844
19845 bool TraverseTemplateArgument(const TemplateArgument &Arg);
19846 };
19847}
19848
19849bool MarkReferencedDecls::TraverseTemplateArgument(
19850 const TemplateArgument &Arg) {
19851 {
19852 // A non-type template argument is a constant-evaluated context.
19856 if (Decl *D = Arg.getAsDecl())
19857 S.MarkAnyDeclReferenced(Loc, D, true);
19858 } else if (Arg.getKind() == TemplateArgument::Expression) {
19860 }
19861 }
19862
19863 return Inherited::TraverseTemplateArgument(Arg);
19864}
19865
19867 MarkReferencedDecls Marker(*this, Loc);
19868 Marker.TraverseType(T);
19869}
19870
19871namespace {
19872/// Helper class that marks all of the declarations referenced by
19873/// potentially-evaluated subexpressions as "referenced".
19874class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19875public:
19876 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19877 bool SkipLocalVariables;
19879
19880 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
19882 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
19883
19884 void visitUsedDecl(SourceLocation Loc, Decl *D) {
19885 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
19886 }
19887
19888 void Visit(Expr *E) {
19889 if (llvm::is_contained(StopAt, E))
19890 return;
19891 Inherited::Visit(E);
19892 }
19893
19894 void VisitConstantExpr(ConstantExpr *E) {
19895 // Don't mark declarations within a ConstantExpression, as this expression
19896 // will be evaluated and folded to a value.
19897 }
19898
19899 void VisitDeclRefExpr(DeclRefExpr *E) {
19900 // If we were asked not to visit local variables, don't.
19901 if (SkipLocalVariables) {
19902 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
19903 if (VD->hasLocalStorage())
19904 return;
19905 }
19906
19907 // FIXME: This can trigger the instantiation of the initializer of a
19908 // variable, which can cause the expression to become value-dependent
19909 // or error-dependent. Do we need to propagate the new dependence bits?
19911 }
19912
19913 void VisitMemberExpr(MemberExpr *E) {
19915 Visit(E->getBase());
19916 }
19917};
19918} // namespace
19919
19921 bool SkipLocalVariables,
19922 ArrayRef<const Expr*> StopAt) {
19923 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
19924}
19925
19926/// Emit a diagnostic when statements are reachable.
19927/// FIXME: check for reachability even in expressions for which we don't build a
19928/// CFG (eg, in the initializer of a global or in a constant expression).
19929/// For example,
19930/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
19932 const PartialDiagnostic &PD) {
19933 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
19934 if (!FunctionScopes.empty())
19935 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
19937 return true;
19938 }
19939
19940 // The initializer of a constexpr variable or of the first declaration of a
19941 // static data member is not syntactically a constant evaluated constant,
19942 // but nonetheless is always required to be a constant expression, so we
19943 // can skip diagnosing.
19944 // FIXME: Using the mangling context here is a hack.
19945 if (auto *VD = dyn_cast_or_null<VarDecl>(
19946 ExprEvalContexts.back().ManglingContextDecl)) {
19947 if (VD->isConstexpr() ||
19948 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19949 return false;
19950 // FIXME: For any other kind of variable, we should build a CFG for its
19951 // initializer and check whether the context in question is reachable.
19952 }
19953
19954 Diag(Loc, PD);
19955 return true;
19956}
19957
19958/// Emit a diagnostic that describes an effect on the run-time behavior
19959/// of the program being compiled.
19960///
19961/// This routine emits the given diagnostic when the code currently being
19962/// type-checked is "potentially evaluated", meaning that there is a
19963/// possibility that the code will actually be executable. Code in sizeof()
19964/// expressions, code used only during overload resolution, etc., are not
19965/// potentially evaluated. This routine will suppress such diagnostics or,
19966/// in the absolutely nutty case of potentially potentially evaluated
19967/// expressions (C++ typeid), queue the diagnostic to potentially emit it
19968/// later.
19969///
19970/// This routine should be used for all diagnostics that describe the run-time
19971/// behavior of a program, such as passing a non-POD value through an ellipsis.
19972/// Failure to do so will likely result in spurious diagnostics or failures
19973/// during overload resolution or within sizeof/alignof/typeof/typeid.
19975 const PartialDiagnostic &PD) {
19976
19977 if (ExprEvalContexts.back().isDiscardedStatementContext())
19978 return false;
19979
19980 switch (ExprEvalContexts.back().Context) {
19985 // The argument will never be evaluated, so don't complain.
19986 break;
19987
19990 // Relevant diagnostics should be produced by constant evaluation.
19991 break;
19992
19995 return DiagIfReachable(Loc, Stmts, PD);
19996 }
19997
19998 return false;
19999}
20000
20002 const PartialDiagnostic &PD) {
20003 return DiagRuntimeBehavior(
20004 Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
20005}
20006
20008 CallExpr *CE, FunctionDecl *FD) {
20009 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20010 return false;
20011
20012 // If we're inside a decltype's expression, don't check for a valid return
20013 // type or construct temporaries until we know whether this is the last call.
20014 if (ExprEvalContexts.back().ExprContext ==
20016 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20017 return false;
20018 }
20019
20020 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20021 FunctionDecl *FD;
20022 CallExpr *CE;
20023
20024 public:
20025 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20026 : FD(FD), CE(CE) { }
20027
20028 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20029 if (!FD) {
20030 S.Diag(Loc, diag::err_call_incomplete_return)
20031 << T << CE->getSourceRange();
20032 return;
20033 }
20034
20035 S.Diag(Loc, diag::err_call_function_incomplete_return)
20036 << CE->getSourceRange() << FD << T;
20037 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20038 << FD->getDeclName();
20039 }
20040 } Diagnoser(FD, CE);
20041
20042 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20043 return true;
20044
20045 return false;
20046}
20047
20048// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20049// will prevent this condition from triggering, which is what we want.
20052
20053 unsigned diagnostic = diag::warn_condition_is_assignment;
20054 bool IsOrAssign = false;
20055
20056 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20057 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20058 return;
20059
20060 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20061
20062 // Greylist some idioms by putting them into a warning subcategory.
20063 if (ObjCMessageExpr *ME
20064 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20065 Selector Sel = ME->getSelector();
20066
20067 // self = [<foo> init...]
20068 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20069 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20070
20071 // <foo> = [<bar> nextObject]
20072 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20073 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20074 }
20075
20076 Loc = Op->getOperatorLoc();
20077 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20078 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20079 return;
20080
20081 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20082 Loc = Op->getOperatorLoc();
20083 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20084 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20085 else {
20086 // Not an assignment.
20087 return;
20088 }
20089
20090 Diag(Loc, diagnostic) << E->getSourceRange();
20091
20094 Diag(Loc, diag::note_condition_assign_silence)
20096 << FixItHint::CreateInsertion(Close, ")");
20097
20098 if (IsOrAssign)
20099 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20101 else
20102 Diag(Loc, diag::note_condition_assign_to_comparison)
20104}
20105
20107 // Don't warn if the parens came from a macro.
20108 SourceLocation parenLoc = ParenE->getBeginLoc();
20109 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20110 return;
20111 // Don't warn for dependent expressions.
20112 if (ParenE->isTypeDependent())
20113 return;
20114
20115 Expr *E = ParenE->IgnoreParens();
20116
20117 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20118 if (opE->getOpcode() == BO_EQ &&
20119 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20120 == Expr::MLV_Valid) {
20121 SourceLocation Loc = opE->getOperatorLoc();
20122
20123 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20124 SourceRange ParenERange = ParenE->getSourceRange();
20125 Diag(Loc, diag::note_equality_comparison_silence)
20126 << FixItHint::CreateRemoval(ParenERange.getBegin())
20127 << FixItHint::CreateRemoval(ParenERange.getEnd());
20128 Diag(Loc, diag::note_equality_comparison_to_assign)
20130 }
20131}
20132
20134 bool IsConstexpr) {
20136 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20138
20140 if (result.isInvalid()) return ExprError();
20141 E = result.get();
20142
20143 if (!E->isTypeDependent()) {
20144 if (getLangOpts().CPlusPlus)
20145 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20146
20148 if (ERes.isInvalid())
20149 return ExprError();
20150 E = ERes.get();
20151
20152 QualType T = E->getType();
20153 if (!T->isScalarType()) { // C99 6.8.4.1p1
20154 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20155 << T << E->getSourceRange();
20156 return ExprError();
20157 }
20158 CheckBoolLikeConversion(E, Loc);
20159 }
20160
20161 return E;
20162}
20163
20165 Expr *SubExpr, ConditionKind CK,
20166 bool MissingOK) {
20167 // MissingOK indicates whether having no condition expression is valid
20168 // (for loop) or invalid (e.g. while loop).
20169 if (!SubExpr)
20170 return MissingOK ? ConditionResult() : ConditionError();
20171
20172 ExprResult Cond;
20173 switch (CK) {
20175 Cond = CheckBooleanCondition(Loc, SubExpr);
20176 break;
20177
20179 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20180 break;
20181
20183 Cond = CheckSwitchCondition(Loc, SubExpr);
20184 break;
20185 }
20186 if (Cond.isInvalid()) {
20187 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20188 {SubExpr}, PreferredConditionType(CK));
20189 if (!Cond.get())
20190 return ConditionError();
20191 }
20192 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20194 if (!FullExpr.get())
20195 return ConditionError();
20196
20197 return ConditionResult(*this, nullptr, FullExpr,
20199}
20200
20201namespace {
20202 /// A visitor for rebuilding a call to an __unknown_any expression
20203 /// to have an appropriate type.
20204 struct RebuildUnknownAnyFunction
20205 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20206
20207 Sema &S;
20208
20209 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20210
20211 ExprResult VisitStmt(Stmt *S) {
20212 llvm_unreachable("unexpected statement!");
20213 }
20214
20215 ExprResult VisitExpr(Expr *E) {
20216 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20217 << E->getSourceRange();
20218 return ExprError();
20219 }
20220
20221 /// Rebuild an expression which simply semantically wraps another
20222 /// expression which it shares the type and value kind of.
20223 template <class T> ExprResult rebuildSugarExpr(T *E) {
20224 ExprResult SubResult = Visit(E->getSubExpr());
20225 if (SubResult.isInvalid()) return ExprError();
20226
20227 Expr *SubExpr = SubResult.get();
20228 E->setSubExpr(SubExpr);
20229 E->setType(SubExpr->getType());
20230 E->setValueKind(SubExpr->getValueKind());
20231 assert(E->getObjectKind() == OK_Ordinary);
20232 return E;
20233 }
20234
20235 ExprResult VisitParenExpr(ParenExpr *E) {
20236 return rebuildSugarExpr(E);
20237 }
20238
20239 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20240 return rebuildSugarExpr(E);
20241 }
20242
20243 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20244 ExprResult SubResult = Visit(E->getSubExpr());
20245 if (SubResult.isInvalid()) return ExprError();
20246
20247 Expr *SubExpr = SubResult.get();
20248 E->setSubExpr(SubExpr);
20249 E->setType(S.Context.getPointerType(SubExpr->getType()));
20250 assert(E->isPRValue());
20251 assert(E->getObjectKind() == OK_Ordinary);
20252 return E;
20253 }
20254
20255 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20256 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20257
20258 E->setType(VD->getType());
20259
20260 assert(E->isPRValue());
20261 if (S.getLangOpts().CPlusPlus &&
20262 !(isa<CXXMethodDecl>(VD) &&
20263 cast<CXXMethodDecl>(VD)->isInstance()))
20265
20266 return E;
20267 }
20268
20269 ExprResult VisitMemberExpr(MemberExpr *E) {
20270 return resolveDecl(E, E->getMemberDecl());
20271 }
20272
20273 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20274 return resolveDecl(E, E->getDecl());
20275 }
20276 };
20277}
20278
20279/// Given a function expression of unknown-any type, try to rebuild it
20280/// to have a function type.
20282 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20283 if (Result.isInvalid()) return ExprError();
20284 return S.DefaultFunctionArrayConversion(Result.get());
20285}
20286
20287namespace {
20288 /// A visitor for rebuilding an expression of type __unknown_anytype
20289 /// into one which resolves the type directly on the referring
20290 /// expression. Strict preservation of the original source
20291 /// structure is not a goal.
20292 struct RebuildUnknownAnyExpr
20293 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20294
20295 Sema &S;
20296
20297 /// The current destination type.
20298 QualType DestType;
20299
20300 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20301 : S(S), DestType(CastType) {}
20302
20303 ExprResult VisitStmt(Stmt *S) {
20304 llvm_unreachable("unexpected statement!");
20305 }
20306
20307 ExprResult VisitExpr(Expr *E) {
20308 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20309 << E->getSourceRange();
20310 return ExprError();
20311 }
20312
20313 ExprResult VisitCallExpr(CallExpr *E);
20314 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20315
20316 /// Rebuild an expression which simply semantically wraps another
20317 /// expression which it shares the type and value kind of.
20318 template <class T> ExprResult rebuildSugarExpr(T *E) {
20319 ExprResult SubResult = Visit(E->getSubExpr());
20320 if (SubResult.isInvalid()) return ExprError();
20321 Expr *SubExpr = SubResult.get();
20322 E->setSubExpr(SubExpr);
20323 E->setType(SubExpr->getType());
20324 E->setValueKind(SubExpr->getValueKind());
20325 assert(E->getObjectKind() == OK_Ordinary);
20326 return E;
20327 }
20328
20329 ExprResult VisitParenExpr(ParenExpr *E) {
20330 return rebuildSugarExpr(E);
20331 }
20332
20333 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20334 return rebuildSugarExpr(E);
20335 }
20336
20337 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20338 const PointerType *Ptr = DestType->getAs<PointerType>();
20339 if (!Ptr) {
20340 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20341 << E->getSourceRange();
20342 return ExprError();
20343 }
20344
20345 if (isa<CallExpr>(E->getSubExpr())) {
20346 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20347 << E->getSourceRange();
20348 return ExprError();
20349 }
20350
20351 assert(E->isPRValue());
20352 assert(E->getObjectKind() == OK_Ordinary);
20353 E->setType(DestType);
20354
20355 // Build the sub-expression as if it were an object of the pointee type.
20356 DestType = Ptr->getPointeeType();
20357 ExprResult SubResult = Visit(E->getSubExpr());
20358 if (SubResult.isInvalid()) return ExprError();
20359 E->setSubExpr(SubResult.get());
20360 return E;
20361 }
20362
20363 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20364
20365 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20366
20367 ExprResult VisitMemberExpr(MemberExpr *E) {
20368 return resolveDecl(E, E->getMemberDecl());
20369 }
20370
20371 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20372 return resolveDecl(E, E->getDecl());
20373 }
20374 };
20375}
20376
20377/// Rebuilds a call expression which yielded __unknown_anytype.
20378ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20379 Expr *CalleeExpr = E->getCallee();
20380
20381 enum FnKind {
20382 FK_MemberFunction,
20383 FK_FunctionPointer,
20384 FK_BlockPointer
20385 };
20386
20387 FnKind Kind;
20388 QualType CalleeType = CalleeExpr->getType();
20389 if (CalleeType == S.Context.BoundMemberTy) {
20390 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20391 Kind = FK_MemberFunction;
20392 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20393 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20394 CalleeType = Ptr->getPointeeType();
20395 Kind = FK_FunctionPointer;
20396 } else {
20397 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20398 Kind = FK_BlockPointer;
20399 }
20400 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20401
20402 // Verify that this is a legal result type of a function.
20403 if (DestType->isArrayType() || DestType->isFunctionType()) {
20404 unsigned diagID = diag::err_func_returning_array_function;
20405 if (Kind == FK_BlockPointer)
20406 diagID = diag::err_block_returning_array_function;
20407
20408 S.Diag(E->getExprLoc(), diagID)
20409 << DestType->isFunctionType() << DestType;
20410 return ExprError();
20411 }
20412
20413 // Otherwise, go ahead and set DestType as the call's result.
20414 E->setType(DestType.getNonLValueExprType(S.Context));
20416 assert(E->getObjectKind() == OK_Ordinary);
20417
20418 // Rebuild the function type, replacing the result type with DestType.
20419 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20420 if (Proto) {
20421 // __unknown_anytype(...) is a special case used by the debugger when
20422 // it has no idea what a function's signature is.
20423 //
20424 // We want to build this call essentially under the K&R
20425 // unprototyped rules, but making a FunctionNoProtoType in C++
20426 // would foul up all sorts of assumptions. However, we cannot
20427 // simply pass all arguments as variadic arguments, nor can we
20428 // portably just call the function under a non-variadic type; see
20429 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20430 // However, it turns out that in practice it is generally safe to
20431 // call a function declared as "A foo(B,C,D);" under the prototype
20432 // "A foo(B,C,D,...);". The only known exception is with the
20433 // Windows ABI, where any variadic function is implicitly cdecl
20434 // regardless of its normal CC. Therefore we change the parameter
20435 // types to match the types of the arguments.
20436 //
20437 // This is a hack, but it is far superior to moving the
20438 // corresponding target-specific code from IR-gen to Sema/AST.
20439
20440 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20441 SmallVector<QualType, 8> ArgTypes;
20442 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20443 ArgTypes.reserve(E->getNumArgs());
20444 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20445 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20446 }
20447 ParamTypes = ArgTypes;
20448 }
20449 DestType = S.Context.getFunctionType(DestType, ParamTypes,
20450 Proto->getExtProtoInfo());
20451 } else {
20452 DestType = S.Context.getFunctionNoProtoType(DestType,
20453 FnType->getExtInfo());
20454 }
20455
20456 // Rebuild the appropriate pointer-to-function type.
20457 switch (Kind) {
20458 case FK_MemberFunction:
20459 // Nothing to do.
20460 break;
20461
20462 case FK_FunctionPointer:
20463 DestType = S.Context.getPointerType(DestType);
20464 break;
20465
20466 case FK_BlockPointer:
20467 DestType = S.Context.getBlockPointerType(DestType);
20468 break;
20469 }
20470
20471 // Finally, we can recurse.
20472 ExprResult CalleeResult = Visit(CalleeExpr);
20473 if (!CalleeResult.isUsable()) return ExprError();
20474 E->setCallee(CalleeResult.get());
20475
20476 // Bind a temporary if necessary.
20477 return S.MaybeBindToTemporary(E);
20478}
20479
20480ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20481 // Verify that this is a legal result type of a call.
20482 if (DestType->isArrayType() || DestType->isFunctionType()) {
20483 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20484 << DestType->isFunctionType() << DestType;
20485 return ExprError();
20486 }
20487
20488 // Rewrite the method result type if available.
20489 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20490 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20491 Method->setReturnType(DestType);
20492 }
20493
20494 // Change the type of the message.
20495 E->setType(DestType.getNonReferenceType());
20497
20498 return S.MaybeBindToTemporary(E);
20499}
20500
20501ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20502 // The only case we should ever see here is a function-to-pointer decay.
20503 if (E->getCastKind() == CK_FunctionToPointerDecay) {
20504 assert(E->isPRValue());
20505 assert(E->getObjectKind() == OK_Ordinary);
20506
20507 E->setType(DestType);
20508
20509 // Rebuild the sub-expression as the pointee (function) type.
20510 DestType = DestType->castAs<PointerType>()->getPointeeType();
20511
20512 ExprResult Result = Visit(E->getSubExpr());
20513 if (!Result.isUsable()) return ExprError();
20514
20515 E->setSubExpr(Result.get());
20516 return E;
20517 } else if (E->getCastKind() == CK_LValueToRValue) {
20518 assert(E->isPRValue());
20519 assert(E->getObjectKind() == OK_Ordinary);
20520
20521 assert(isa<BlockPointerType>(E->getType()));
20522
20523 E->setType(DestType);
20524
20525 // The sub-expression has to be a lvalue reference, so rebuild it as such.
20526 DestType = S.Context.getLValueReferenceType(DestType);
20527
20528 ExprResult Result = Visit(E->getSubExpr());
20529 if (!Result.isUsable()) return ExprError();
20530
20531 E->setSubExpr(Result.get());
20532 return E;
20533 } else {
20534 llvm_unreachable("Unhandled cast type!");
20535 }
20536}
20537
20538ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20539 ExprValueKind ValueKind = VK_LValue;
20540 QualType Type = DestType;
20541
20542 // We know how to make this work for certain kinds of decls:
20543
20544 // - functions
20545 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20546 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20547 DestType = Ptr->getPointeeType();
20548 ExprResult Result = resolveDecl(E, VD);
20549 if (Result.isInvalid()) return ExprError();
20550 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20551 VK_PRValue);
20552 }
20553
20554 if (!Type->isFunctionType()) {
20555 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20556 << VD << E->getSourceRange();
20557 return ExprError();
20558 }
20559 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20560 // We must match the FunctionDecl's type to the hack introduced in
20561 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20562 // type. See the lengthy commentary in that routine.
20563 QualType FDT = FD->getType();
20564 const FunctionType *FnType = FDT->castAs<FunctionType>();
20565 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20566 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20567 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20568 SourceLocation Loc = FD->getLocation();
20570 S.Context, FD->getDeclContext(), Loc, Loc,
20571 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20573 false /*isInlineSpecified*/, FD->hasPrototype(),
20574 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20575
20576 if (FD->getQualifier())
20577 NewFD->setQualifierInfo(FD->getQualifierLoc());
20578
20580 for (const auto &AI : FT->param_types()) {
20581 ParmVarDecl *Param =
20583 Param->setScopeInfo(0, Params.size());
20584 Params.push_back(Param);
20585 }
20586 NewFD->setParams(Params);
20587 DRE->setDecl(NewFD);
20588 VD = DRE->getDecl();
20589 }
20590 }
20591
20592 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20593 if (MD->isInstance()) {
20594 ValueKind = VK_PRValue;
20596 }
20597
20598 // Function references aren't l-values in C.
20599 if (!S.getLangOpts().CPlusPlus)
20600 ValueKind = VK_PRValue;
20601
20602 // - variables
20603 } else if (isa<VarDecl>(VD)) {
20604 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20605 Type = RefTy->getPointeeType();
20606 } else if (Type->isFunctionType()) {
20607 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20608 << VD << E->getSourceRange();
20609 return ExprError();
20610 }
20611
20612 // - nothing else
20613 } else {
20614 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20615 << VD << E->getSourceRange();
20616 return ExprError();
20617 }
20618
20619 // Modifying the declaration like this is friendly to IR-gen but
20620 // also really dangerous.
20621 VD->setType(DestType);
20622 E->setType(Type);
20623 E->setValueKind(ValueKind);
20624 return E;
20625}
20626
20630 // The type we're casting to must be either void or complete.
20631 if (!CastType->isVoidType() &&
20633 diag::err_typecheck_cast_to_incomplete))
20634 return ExprError();
20635
20636 // Rewrite the casted expression from scratch.
20637 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20638 if (!result.isUsable()) return ExprError();
20639
20640 CastExpr = result.get();
20641 VK = CastExpr->getValueKind();
20642 CastKind = CK_NoOp;
20643
20644 return CastExpr;
20645}
20646
20648 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20649}
20650
20652 Expr *arg, QualType &paramType) {
20653 // If the syntactic form of the argument is not an explicit cast of
20654 // any sort, just do default argument promotion.
20655 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20656 if (!castArg) {
20658 if (result.isInvalid()) return ExprError();
20659 paramType = result.get()->getType();
20660 return result;
20661 }
20662
20663 // Otherwise, use the type that was written in the explicit cast.
20664 assert(!arg->hasPlaceholderType());
20665 paramType = castArg->getTypeAsWritten();
20666
20667 // Copy-initialize a parameter of that type.
20668 InitializedEntity entity =
20670 /*consumed*/ false);
20671 return PerformCopyInitialization(entity, callLoc, arg);
20672}
20673
20675 Expr *orig = E;
20676 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20677 while (true) {
20678 E = E->IgnoreParenImpCasts();
20679 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20680 E = call->getCallee();
20681 diagID = diag::err_uncasted_call_of_unknown_any;
20682 } else {
20683 break;
20684 }
20685 }
20686
20687 SourceLocation loc;
20688 NamedDecl *d;
20689 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20690 loc = ref->getLocation();
20691 d = ref->getDecl();
20692 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20693 loc = mem->getMemberLoc();
20694 d = mem->getMemberDecl();
20695 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20696 diagID = diag::err_uncasted_call_of_unknown_any;
20697 loc = msg->getSelectorStartLoc();
20698 d = msg->getMethodDecl();
20699 if (!d) {
20700 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20701 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20702 << orig->getSourceRange();
20703 return ExprError();
20704 }
20705 } else {
20706 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20707 << E->getSourceRange();
20708 return ExprError();
20709 }
20710
20711 S.Diag(loc, diagID) << d << orig->getSourceRange();
20712
20713 // Never recoverable.
20714 return ExprError();
20715}
20716
20719 // C cannot handle TypoExpr nodes on either side of a binop because it
20720 // doesn't handle dependent types properly, so make sure any TypoExprs have
20721 // been dealt with before checking the operands.
20723 if (!Result.isUsable()) return ExprError();
20724 E = Result.get();
20725 }
20726
20727 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20728 if (!placeholderType) return E;
20729
20730 switch (placeholderType->getKind()) {
20731 case BuiltinType::UnresolvedTemplate: {
20732 auto *ULE = cast<UnresolvedLookupExpr>(E);
20733 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
20734 // There's only one FoundDecl for UnresolvedTemplate type. See
20735 // BuildTemplateIdExpr.
20736 NamedDecl *Temp = *ULE->decls_begin();
20737 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
20738
20739 if (NestedNameSpecifierLoc Loc = ULE->getQualifierLoc(); Loc.hasQualifier())
20740 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
20741 << Loc.getNestedNameSpecifier() << NameInfo.getName().getAsString()
20742 << Loc.getSourceRange() << IsTypeAliasTemplateDecl;
20743 else
20744 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
20745 << "" << NameInfo.getName().getAsString() << ULE->getSourceRange()
20746 << IsTypeAliasTemplateDecl;
20747 Diag(Temp->getLocation(), diag::note_referenced_type_template)
20748 << IsTypeAliasTemplateDecl;
20749
20750 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
20751 }
20752
20753 // Overloaded expressions.
20754 case BuiltinType::Overload: {
20755 // Try to resolve a single function template specialization.
20756 // This is obligatory.
20759 return Result;
20760
20761 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20762 // leaves Result unchanged on failure.
20763 Result = E;
20765 return Result;
20766
20767 // If that failed, try to recover with a call.
20768 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20769 /*complain*/ true);
20770 return Result;
20771 }
20772
20773 // Bound member functions.
20774 case BuiltinType::BoundMember: {
20775 ExprResult result = E;
20776 const Expr *BME = E->IgnoreParens();
20777 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20778 // Try to give a nicer diagnostic if it is a bound member that we recognize.
20779 if (isa<CXXPseudoDestructorExpr>(BME)) {
20780 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20781 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20782 if (ME->getMemberNameInfo().getName().getNameKind() ==
20784 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20785 }
20786 tryToRecoverWithCall(result, PD,
20787 /*complain*/ true);
20788 return result;
20789 }
20790
20791 // ARC unbridged casts.
20792 case BuiltinType::ARCUnbridgedCast: {
20793 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
20794 ObjC().diagnoseARCUnbridgedCast(realCast);
20795 return realCast;
20796 }
20797
20798 // Expressions of unknown type.
20799 case BuiltinType::UnknownAny:
20800 return diagnoseUnknownAnyExpr(*this, E);
20801
20802 // Pseudo-objects.
20803 case BuiltinType::PseudoObject:
20804 return PseudoObject().checkRValue(E);
20805
20806 case BuiltinType::BuiltinFn: {
20807 // Accept __noop without parens by implicitly converting it to a call expr.
20808 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20809 if (DRE) {
20810 auto *FD = cast<FunctionDecl>(DRE->getDecl());
20811 unsigned BuiltinID = FD->getBuiltinID();
20812 if (BuiltinID == Builtin::BI__noop) {
20813 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20814 CK_BuiltinFnToFnPtr)
20815 .get();
20816 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20819 }
20820
20821 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
20822 // Any use of these other than a direct call is ill-formed as of C++20,
20823 // because they are not addressable functions. In earlier language
20824 // modes, warn and force an instantiation of the real body.
20825 Diag(E->getBeginLoc(),
20827 ? diag::err_use_of_unaddressable_function
20828 : diag::warn_cxx20_compat_use_of_unaddressable_function);
20829 if (FD->isImplicitlyInstantiable()) {
20830 // Require a definition here because a normal attempt at
20831 // instantiation for a builtin will be ignored, and we won't try
20832 // again later. We assume that the definition of the template
20833 // precedes this use.
20835 /*Recursive=*/false,
20836 /*DefinitionRequired=*/true,
20837 /*AtEndOfTU=*/false);
20838 }
20839 // Produce a properly-typed reference to the function.
20840 CXXScopeSpec SS;
20841 SS.Adopt(DRE->getQualifierLoc());
20842 TemplateArgumentListInfo TemplateArgs;
20843 DRE->copyTemplateArgumentsInto(TemplateArgs);
20844 return BuildDeclRefExpr(
20845 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
20846 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
20847 DRE->getTemplateKeywordLoc(),
20848 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
20849 }
20850 }
20851
20852 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
20853 return ExprError();
20854 }
20855
20856 case BuiltinType::IncompleteMatrixIdx:
20857 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
20858 ->getRowIdx()
20859 ->getBeginLoc(),
20860 diag::err_matrix_incomplete_index);
20861 return ExprError();
20862
20863 // Expressions of unknown type.
20864 case BuiltinType::ArraySection:
20865 Diag(E->getBeginLoc(), diag::err_array_section_use)
20866 << cast<ArraySectionExpr>(E)->isOMPArraySection();
20867 return ExprError();
20868
20869 // Expressions of unknown type.
20870 case BuiltinType::OMPArrayShaping:
20871 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
20872
20873 case BuiltinType::OMPIterator:
20874 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
20875
20876 // Everything else should be impossible.
20877#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
20878 case BuiltinType::Id:
20879#include "clang/Basic/OpenCLImageTypes.def"
20880#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
20881 case BuiltinType::Id:
20882#include "clang/Basic/OpenCLExtensionTypes.def"
20883#define SVE_TYPE(Name, Id, SingletonId) \
20884 case BuiltinType::Id:
20885#include "clang/Basic/AArch64SVEACLETypes.def"
20886#define PPC_VECTOR_TYPE(Name, Id, Size) \
20887 case BuiltinType::Id:
20888#include "clang/Basic/PPCTypes.def"
20889#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20890#include "clang/Basic/RISCVVTypes.def"
20891#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20892#include "clang/Basic/WebAssemblyReferenceTypes.def"
20893#define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20894#include "clang/Basic/AMDGPUTypes.def"
20895#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20896#include "clang/Basic/HLSLIntangibleTypes.def"
20897#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
20898#define PLACEHOLDER_TYPE(Id, SingletonId)
20899#include "clang/AST/BuiltinTypes.def"
20900 break;
20901 }
20902
20903 llvm_unreachable("invalid placeholder type!");
20904}
20905
20907 if (E->isTypeDependent())
20908 return true;
20911 return false;
20912}
20913
20915 ArrayRef<Expr *> SubExprs, QualType T) {
20916 if (!Context.getLangOpts().RecoveryAST)
20917 return ExprError();
20918
20919 if (isSFINAEContext())
20920 return ExprError();
20921
20922 if (T.isNull() || T->isUndeducedType() ||
20923 !Context.getLangOpts().RecoveryASTType)
20924 // We don't know the concrete type, fallback to dependent type.
20926
20927 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
20928}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3341
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
static bool isObjCPointer(const MemRegion *R)
Defines enum values for all the target-independent builtin functions.
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the C++ template declaration subclasses.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
unsigned Iter
Definition: HTMLLogger.cpp:154
LangStandard::Kind Std
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition: MachO.h:51
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
uint32_t Id
Definition: SemaARM.cpp:1144
This file declares semantic analysis for CUDA constructs.
CastType
Definition: SemaCast.cpp:49
static Sema::AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
Definition: SemaExpr.cpp:9049
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
Definition: SemaExpr.cpp:17514
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, ArrayRef< Expr * > Args, SourceLocation LitEndLoc)
BuildCookedLiteralOperatorCall - A user-defined literal was found.
Definition: SemaExpr.cpp:1934
static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHS, Expr *RHS)
Build an overloaded binary operator expression in the given scope.
Definition: SemaExpr.cpp:15099
static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, QualType FloatTy)
Test if a (constant) integer Int can be casted to floating point type FloatTy without losing precisio...
Definition: SemaExpr.cpp:9928
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the captured region.
Definition: SemaExpr.cpp:18452
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:10679
static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison operators are mixed in a way t...
Definition: SemaExpr.cpp:14890
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
Definition: SemaExpr.cpp:6065
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:10598
static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, Expr *Condition, const Expr *LHSExpr, const Expr *RHSExpr)
DiagnoseConditionalPrecedence - Emit a warning when a conditional operator and binary operator are mi...
Definition: SemaExpr.cpp:8619
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, bool AcceptInvalid)
Diagnoses obvious problems with the use of the given declaration as an expression.
Definition: SemaExpr.cpp:3143
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
Definition: SemaExpr.cpp:8073
static QualType OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Return the resulting type for the conditional operator in OpenCL (aka "ternary selection operator",...
Definition: SemaExpr.cpp:8279
static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
Definition: SemaExpr.cpp:11644
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:10643
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:11594
static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn)
Definition: SemaExpr.cpp:5735
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
Definition: SemaExpr.cpp:2219
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:14366
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:17852
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:13129
@ NCCK_Block
Definition: SemaExpr.cpp:13129
@ NCCK_None
Definition: SemaExpr.cpp:13129
@ NCCK_Lambda
Definition: SemaExpr.cpp:13129
static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, QualType scalarTy, QualType vectorEltTy, QualType vectorTy, unsigned &DiagID)
Try to convert a value of non-vector type to a vector type by converting the type to the element type...
Definition: SemaExpr.cpp:9822
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
Definition: SemaExpr.cpp:9098
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:5997
static Expr * recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, DeclarationNameInfo &NameInfo, SourceLocation TemplateKWLoc, const TemplateArgumentListInfo *TemplateArgs)
In Microsoft mode, if we are inside a template class whose parent class has dependent base classes,...
Definition: SemaExpr.cpp:2621
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
Definition: SemaExpr.cpp:19671
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18304
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:16588
static void SuggestParentheses(Sema &Self, SourceLocation Loc, const PartialDiagnostic &Note, SourceRange ParenRange)
SuggestParentheses - Emit a note with a fixit hint that wraps ParenRange in parentheses.
Definition: SemaExpr.cpp:8523
static Decl * getPredefinedExprDecl(DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
Definition: SemaExpr.cpp:1918
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:16471
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
Definition: SemaExpr.cpp:13691
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4702
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:11996
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
Definition: SemaExpr.cpp:14266
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
Definition: SemaExpr.cpp:4318
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
Definition: SemaExpr.cpp:8598
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
Definition: SemaExpr.cpp:17701
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, SourceLocation OpLoc, bool IsBuiltin)
DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
Definition: SemaExpr.cpp:14422
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
diagnoseStringPlusInt - Emit a warning when adding an integer to a string literal.
Definition: SemaExpr.cpp:10764
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:7916
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19471
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:3168
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:7882
static bool checkForArray(const Expr *E)
Definition: SemaExpr.cpp:11686
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
Definition: SemaExpr.cpp:6340
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:13313
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19717
static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S)
Convert vector E to a vector with the same number of elements but different element type.
Definition: SemaExpr.cpp:9869
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
Definition: SemaExpr.cpp:19439
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:14248
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
Definition: SemaExpr.cpp:17375
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:11871
static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, const Expr **RHSExprs)
IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary expression, either using a built-i...
Definition: SemaExpr.cpp:8553
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, BinaryOperatorKind Opc, QualType ResultTy, ExprValueKind VK, ExprObjectKind OK, bool IsCompAssign, SourceLocation OpLoc, FPOptionsOverride FPFeatures)
Definition: SemaExpr.cpp:14520
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1304
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:6230
static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult, QualType UnionType, FieldDecl *Field)
Constructs a transparent union from an expression that is used to initialize the transparent union.
Definition: SemaExpr.cpp:9486
static QualType OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType CondTy, SourceLocation QuestionLoc)
Convert scalar operands to a vector that matches the condition in length.
Definition: SemaExpr.cpp:8197
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:7903
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
Definition: SemaExpr.cpp:10610
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:14505
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:4759
static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8825
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
Definition: SemaExpr.cpp:17417
static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *SubExpr)
Look for bitwise op in the left or right hand of a bitwise op with lower precedence and emit a diagno...
Definition: SemaExpr.cpp:14981
static void emitEmptyLookupTypoDiagnostic(const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, DeclarationName Typo, SourceLocation TypoLoc, ArrayRef< Expr * > Args, unsigned DiagnosticID, unsigned DiagnosticSuggestID)
Definition: SemaExpr.cpp:2354
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation OpLoc, bool IsInc, bool IsPrefix)
CheckIncrementDecrementOperand - unlike most "Check" methods, this routine doesn't need to call Usual...
Definition: SemaExpr.cpp:13796
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:8142
static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, SourceLocation QuestionLoc)
Return false if the vector condition type and the vector result type are compatible.
Definition: SemaExpr.cpp:8251
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10437
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:11700
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, const Expr *E)
Check whether E is a pointer from a decayed array type (the decayed pointer type is equal to T) and e...
Definition: SemaExpr.cpp:4195
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:10485
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3466
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
Definition: SemaExpr.cpp:5694
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition: SemaExpr.cpp:145
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
Definition: SemaExpr.cpp:11133
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4102
static Sema::AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
Definition: SemaExpr.cpp:8998
static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, QualType RHSType)
Diagnose attempts to convert between __float128, __ibm128 and long double if there is no support for ...
Definition: SemaExpr.cpp:1261
static void MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
Definition: SemaExpr.cpp:18135
static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Emit a warning when adding a char literal to a string.
Definition: SemaExpr.cpp:10794
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:13377
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:13898
static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, const NamedDecl *D, SourceLocation Loc)
Check whether we're in an extern inline function and referring to a variable or function with interna...
Definition: SemaExpr.cpp:161
static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD)
Return true if this function has a calling convention that requires mangling in the size of the param...
Definition: SemaExpr.cpp:17732
static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Returns false if the pointers are converted to a composite type, true otherwise.
Definition: SemaExpr.cpp:11495
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:15038
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:13958
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle conversions with GCC complex int extension.
Definition: SemaExpr.cpp:1354
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:4773
static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, ExprResult *Vector)
Attempt to convert and splat Scalar into a vector whose types matches Vector following GCC conversion...
Definition: SemaExpr.cpp:9972
static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, const Sema::TryCaptureKind Kind, SourceLocation EllipsisLoc, const bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the lambda.
Definition: SemaExpr.cpp:18492
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
Definition: SemaExpr.cpp:14945
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:558
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
Definition: SemaExpr.cpp:8653
static OdrUseContext isOdrUseContext(Sema &SemaRef)
Are we within a context in which references to resolved functions or to variables result in odr-use?
Definition: SemaExpr.cpp:17820
static void DiagnoseConstAssignment(Sema &S, const Expr *E, SourceLocation Loc)
Emit the "read-only variable not assignable" error and print notes to give more information about why...
Definition: SemaExpr.cpp:13188
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3596
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:13166
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:18252
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:10657
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4147
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:11328
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:11914
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:20674
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, unsigned Offset)
getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the location of the token and the off...
Definition: SemaExpr.cpp:1926
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:8317
OriginalExprKind
Definition: SemaExpr.cpp:13307
@ OEK_Variable
Definition: SemaExpr.cpp:13308
@ OEK_LValue
Definition: SemaExpr.cpp:13310
@ OEK_Member
Definition: SemaExpr.cpp:13309
static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S, bool Invalid)
Definition: SemaExpr.cpp:18384
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
Definition: SemaExpr.cpp:1211
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:10585
static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Return the resulting type when a vector is shifted by a scalar or vector shift amount.
Definition: SemaExpr.cpp:11234
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
Definition: SemaExpr.cpp:18211
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1286
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:10401
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:13116
static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, ValueDecl *Var)
Create up to 4 fix-its for explicit reference and value capture of Var or default capture.
Definition: SemaExpr.cpp:18620
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:6299
static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4132
static Sema::AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, SourceLocation Loc)
Definition: SemaExpr.cpp:8846
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4120
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
Definition: SemaExpr.cpp:14966
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
Definition: SemaExpr.cpp:4792
static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc, Sema::ArithConvKind ACK)
Check that the usual arithmetic conversions can be performed on this pair of expressions that might b...
Definition: SemaExpr.cpp:1486
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:10845
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:6257
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
Definition: SemaExpr.cpp:1400
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4177
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:10627
static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, Expr *PointerExpr, SourceLocation Loc, bool IsIntFirstExpr)
Return false if the first expression is not an integer and the second expression is not a pointer,...
Definition: SemaExpr.cpp:8112
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:11832
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
Definition: SemaExpr.cpp:12695
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:8231
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:8538
@ ConstMethod
Definition: SemaExpr.cpp:13179
@ ConstUnknown
Definition: SemaExpr.cpp:13181
@ ConstVariable
Definition: SemaExpr.cpp:13177
@ NestedConstMember
Definition: SemaExpr.cpp:13180
@ ConstMember
Definition: SemaExpr.cpp:13178
@ ConstFunction
Definition: SemaExpr.cpp:13176
static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr, ExprResult &ComplexExpr, QualType IntTy, QualType ComplexTy, bool SkipCast)
Convert complex integers to complex floats and real integers to real floats as required for complex a...
Definition: SemaExpr.cpp:1105
static std::pair< ExprResult, ExprResult > CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:14553
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, SourceLocation OpLoc)
Check if a bitwise-& is performed on an Objective-C pointer.
Definition: SemaExpr.cpp:14464
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition: SemaExpr.cpp:583
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn)
Given a function expression of unknown-any type, try to rebuild it to have a function type.
Definition: SemaExpr.cpp:20281
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, ExprResult &IntExpr, QualType FloatTy, QualType IntTy, bool ConvertFloat, bool ConvertInt)
Handle arithmetic conversion from integer to float.
Definition: SemaExpr.cpp:1180
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:11547
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
Definition: SemaExpr.cpp:1133
static FunctionDecl * rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, FunctionDecl *FDecl, MultiExprArg ArgExprs)
If a builtin function has a pointer argument with no explicit address space, then it should be able t...
Definition: SemaExpr.cpp:6157
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
Definition: SemaExpr.cpp:19642
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind)
Definition: SemaExpr.cpp:1894
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition: SemaExpr.cpp:107
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, QualType RHSTy)
handleFixedPointConversion - Fixed point operations between fixed point types and integers or other f...
Definition: SemaExpr.cpp:1447
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
Definition: SemaExpr.cpp:1156
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:13760
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
Definition: SemaExpr.cpp:18594
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:10575
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:11484
static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, Expr *E0, Expr *E1=nullptr)
Returns true if conversion between vectors of halfs and vectors of floats is needed.
Definition: SemaExpr.cpp:14576
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:11534
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:13130
static QualType checkConditionalBlockPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both block pointers.
Definition: SemaExpr.cpp:8047
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15010
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:14996
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:11524
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
Definition: SemaExpr.cpp:14933
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
Definition: SemaExpr.cpp:4384
static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, QualType OtherIntTy)
Test if a (constant) integer Int can be casted to another integer type IntTy without losing precision...
Definition: SemaExpr.cpp:9890
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18285
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:15278
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:13505
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12925
static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, NonOdrUseReason NOUR)
Walk the set of potential results of an expression and mark them all as non-odr-uses if they satisfy ...
Definition: SemaExpr.cpp:19056
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
Definition: SemaExpr.cpp:17766
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:11127
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Check the validity of a binary arithmetic operation w.r.t.
Definition: SemaExpr.cpp:10711
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:7427
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis for expressions involving.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
SourceLocation Begin
@ Open
The standard open() call: int open(const char *path, int oflag, ...);.
__device__ int
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APSInt & getInt()
Definition: APValue.h:423
bool hasValue() const
Definition: APValue.h:399
bool isInt() const
Definition: APValue.h:401
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
virtual void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D)
Invoked when a function is implicitly instantiated.
Definition: ASTConsumer.h:83
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
CanQualType AccumTy
Definition: ASTContext.h:1132
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1101
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2825
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1150
CanQualType LongTy
Definition: ASTContext.h:1128
unsigned getIntWidth(QualType T) const
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
CanQualType Int128Ty
Definition: ASTContext.h:1128
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:2172
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:664
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
QualType getRecordType(const RecordDecl *Decl) const
QualType getScalableVectorType(QualType EltTy, unsigned NumElts, unsigned NumFields=1) const
Return the unique reference to a scalable vector type of the specified element type and scalable numb...
QualType getBuiltinMSVaListType() const
Retrieve the type of the __builtin_ms_va_list type.
Definition: ASTContext.h:2186
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1132
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
Definition: ASTContext.h:1131
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2628
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2644
CanQualType DoubleTy
Definition: ASTContext.h:1131
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
CanQualType LongDoubleTy
Definition: ASTContext.h:1131
CanQualType Char16Ty
Definition: ASTContext.h:1126
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1146
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1147
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1637
CanQualType WideCharTy
Definition: ASTContext.h:1123
IdentifierTable & Idents
Definition: ASTContext.h:660
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:662
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:797
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
bool typesAreBlockPointerCompatible(QualType, QualType)
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
llvm::SetVector< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
Definition: ASTContext.h:1199
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
Definition: ASTContext.h:1120
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CanQualType Float128Ty
Definition: ASTContext.h:1131
CanQualType UnsignedLongTy
Definition: ASTContext.h:1129
llvm::DenseSet< const FunctionDecl * > CUDAImplicitHostDeviceFunUsedByDevice
Keep track of CUDA/HIP implicit host device functions used on device side in device compilation.
Definition: ASTContext.h:1203
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
Definition: ASTContext.h:1135
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
CanQualType BoundMemberTy
Definition: ASTContext.h:1147
CanQualType CharTy
Definition: ASTContext.h:1121
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
Definition: ASTContext.h:1128
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1195
CanQualType PseudoObjectTy
Definition: ASTContext.h:1150
CanQualType Float16Ty
Definition: ASTContext.h:1145
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2210
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1147
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2374
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2675
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2394
CanQualType BuiltinFnTy
Definition: ASTContext.h:1149
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1119
CanQualType UnsignedCharTy
Definition: ASTContext.h:1129
CanQualType UnsignedIntTy
Definition: ASTContext.h:1129
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getObjCClassRedefinitionType() const
Retrieve the type that Class has been defined to, which may be different from the built-in Class if C...
Definition: ASTContext.h:1931
CanQualType UnknownAnyTy
Definition: ASTContext.h:1148
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1130
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1615
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType ShortTy
Definition: ASTContext.h:1128
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Definition: ASTContext.h:1135
CanQualType LongAccumTy
Definition: ASTContext.h:1133
CanQualType Char32Ty
Definition: ASTContext.h:1127
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
CanQualType LongFractTy
Definition: ASTContext.h:1135
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1158
std::optional< CharUnits > getTypeSizeInCharsIfKnown(QualType Ty) const
Definition: ASTContext.h:2413
QualType getCorrespondingUnsignedType(QualType T) const
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
Definition: ASTContext.h:1128
QualType getCorrespondingSignedType(QualType T) const
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1847
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
CanQualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
QualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
Definition: ASTContext.h:2053
unsigned char getFixedPointScale(QualType Ty) const
QualType adjustStringLiteralBaseType(QualType StrLTy) const
CanQualType Char8Ty
Definition: ASTContext.h:1125
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
CanQualType HalfTy
Definition: ASTContext.h:1143
bool isDependenceAllowed() const
Definition: ASTContext.h:803
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2398
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:4372
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2674
Wrapper for source info for arrays.
Definition: TypeLoc.h:1561
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3566
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3580
QualType getElementType() const
Definition: Type.h:3578
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition: Expr.h:6426
Attr - This represents one attribute.
Definition: Attr.h:42
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:6075
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6375
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4275
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
Expr * getLHS() const
Definition: Expr.h:3910
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2181
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3960
bool isComparisonOp() const
Definition: Expr.h:3961
StringRef getOpcodeStr() const
Definition: Expr.h:3926
bool isRelationalOp() const
Definition: Expr.h:3955
SourceLocation getOperatorLoc() const
Definition: Expr.h:3902
bool isCompoundAssignmentOp() const
Definition: Expr.h:4004
bool isMultiplicativeOp() const
Definition: Expr.h:3945
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:2134
bool isShiftOp() const
Definition: Expr.h:3949
Expr * getRHS() const
Definition: Expr.h:3912
bool isEqualityOp() const
Definition: Expr.h:3958
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4859
bool isBitwiseOp() const
Definition: Expr.h:3952
bool isAdditiveOp() const
Definition: Expr.h:3947
static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc, const Expr *LHS, const Expr *RHS)
Return true if a binary operator using the specified opcode and operands would match the 'p = (i8*)nu...
Definition: Expr.cpp:2206
Opcode getOpcode() const
Definition: Expr.h:3905
bool isAssignmentOp() const
Definition: Expr.h:3999
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2143
static bool isBitwiseOp(Opcode Opc)
Definition: Expr.h:3951
A binding in a decomposition declaration.
Definition: DeclCXX.h:4111
A class which contains all the information about a particular captured value.
Definition: Decl.h:4477
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4471
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.cpp:5228
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition: Decl.h:4553
void setBlockMissingReturnType(bool val=true)
Definition: Decl.h:4610
void setIsVariadic(bool value)
Definition: Decl.h:4547
SourceLocation getCaretLocation() const
Definition: Decl.h:4544
void setBody(CompoundStmt *B)
Definition: Decl.h:4551
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:4557
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition: Decl.cpp:5239
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5415
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6365
Pointer to a block type.
Definition: Type.h:3397
This class is used for builtin types like 'int'.
Definition: Type.h:3023
bool isSVEBool() const
Definition: Type.h:3100
Kind getKind() const
Definition: Type.h:3071
bool hasPtrArgsOrResult(unsigned ID) const
Determines whether this builtin has a result or any arguments which are pointer types.
Definition: Builtins.h:209
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
bool isImmediate(unsigned ID) const
Returns true if this is an immediate (consteval) function.
Definition: Builtins.h:284
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:196
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:182
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:188
static CUDAKernelCallExpr * Create(const ASTContext &Ctx, Expr *Fn, CallExpr *Config, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition: ExprCXX.cpp:1907
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2539
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2866
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition: DeclCXX.cpp:2942
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2304
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1268
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition: ExprCXX.cpp:1019
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1375
static CXXDefaultInitExpr * Create(const ASTContext &Ctx, SourceLocation Loc, FieldDecl *Field, DeclContext *UsedContext, Expr *RewrittenInitExpr)
Field is the non-static data member whose default initializer is used by this expression.
Definition: ExprCXX.cpp:1073
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:1534
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2803
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
bool isVirtual() const
Definition: DeclCXX.h:2119
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2190
CXXMethodDecl * getDevirtualizedMethod(const Expr *Base, bool IsAppleKext)
If it's possible to devirtualize a call to this method, return the called function.
Definition: DeclCXX.cpp:2331
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition: ExprCXX.h:149
SourceRange getSourceRange() const
Definition: ExprCXX.h:161
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition: DeclCXX.h:1230
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:605
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1969
bool hasDefinition() const
Definition: DeclCXX.h:572
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceRange getRange() const
Definition: DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
Represents the this expression in C++.
Definition: ExprCXX.h:1152
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3021
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3034
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition: Expr.cpp:1494
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3000
void computeDependence()
Compute and set dependence bits.
Definition: Expr.h:3040
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:3008
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:3011
void setNumArgsUnsafe(unsigned NewNumArgs)
Bluntly set a new number of arguments without doing any checks whatsoever.
Definition: Expr.h:3062
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition: Expr.h:3053
QualType withConst() const
Retrieves a version of this type with const applied.
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3498
const char * getCastKindName() const
Definition: Expr.h:3546
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
unsigned getValue() const
Definition: Expr.h:1615
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4592
void mergeFrom(CleanupInfo Rhs)
Definition: CleanupInfo.h:38
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
bool cleanupsHaveSideEffects() const
Definition: CleanupInfo.h:26
bool exprNeedsCleanups() const
Definition: CleanupInfo.h:24
Complex values, per C99 6.2.5p11.
Definition: Type.h:3134
QualType getElementType() const
Definition: Type.h:3144
static CompoundAssignOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, QualType CompLHSType=QualType(), QualType CompResultType=QualType())
Definition: Expr.cpp:4881
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3428
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1611
bool body_empty() const
Definition: Stmt.h:1655
Stmt * getStmtExprResult()
Definition: Stmt.h:1733
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4213
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3604
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3660
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3680
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1077
static ConstantResultStorageKind getStorageKind(const APValue &Value)
Definition: Expr.cpp:302
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition: Expr.cpp:378
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1127
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4219
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4240
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4237
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4533
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
void setTypoName(const IdentifierInfo *II)
void setTypoNNS(NestedNameSpecifier *NNS)
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1262
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2219
bool isRequiresExprBody() const
Definition: DeclBase.h:2175
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1333
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1852
bool isRecord() const
Definition: DeclBase.h:2170
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1988
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1766
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1635
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:2014
bool isFunctionOrMethod() const
Definition: DeclBase.h:2142
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1284
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1403
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition: Expr.h:1370
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition: Expr.h:1414
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1463
void setDecl(ValueDecl *NewD)
Definition: Expr.cpp:544
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition: Expr.h:1418
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
DeclarationNameInfo getNameInfo() const
Definition: Expr.h:1337
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: Expr.h:1386
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:488
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition: Expr.h:1348
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition: Expr.h:1352
ValueDecl * getDecl()
Definition: Expr.h:1333
SourceLocation getLocation() const
Definition: Expr.h:1341
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1360
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
T * getAttr() const
Definition: DeclBase.h:580
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:600
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:748
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:567
bool isInvalidDecl() const
Definition: DeclBase.h:595
SourceLocation getLocation() const
Definition: DeclBase.h:446
void setReferenced(bool R=true)
Definition: DeclBase.h:630
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1039
DeclContext * getDeclContext()
Definition: DeclBase.h:455
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
bool hasAttr() const
Definition: DeclBase.h:584
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
Kind getKind() const
Definition: DeclBase.h:449
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:783
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1982
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:797
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:760
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
DeclaratorContext getContext() const
Definition: DeclSpec.h:2075
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2086
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2333
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:532
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:690
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
Represents a reference to #emded data.
Definition: Expr.h:4867
RAII object that enters a new expression evaluation context.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5991
EnumDecl * getDecl() const
Definition: Type.h:5998
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3750
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:3777
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1447
This represents one expression.
Definition: Expr.h:110
LValueClassification
Definition: Expr.h:282
@ LV_ArrayTemporary
Definition: Expr.h:292
@ LV_ClassTemporary
Definition: Expr.h:291
@ LV_MemberFunction
Definition: Expr.h:289
@ LV_IncompleteVoidType
Definition: Expr.h:285
@ LV_Valid
Definition: Expr.h:283
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isGLValue() const
Definition: Expr.h:280
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition: Expr.cpp:3097
isModifiableLvalueResult isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type, does not have an incomplet...
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition: Expr.cpp:3026
llvm::APSInt EvaluateKnownConstIntCheckOverflow(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition: Expr.cpp:3075
void setType(QualType t)
Definition: Expr.h:143
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition: Expr.h:239
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3070
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3058
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition: Expr.cpp:3079
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3066
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3290
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:822
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:830
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3567
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3050
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition: Expr.h:797
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:806
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:809
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition: Expr.h:812
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:799
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition: Expr.cpp:3941
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition: Expr.cpp:266
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:454
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
static bool isSameComparisonOperand(const Expr *E1, const Expr *E2)
Checks that the two Expr's will refer to the same value as a comparison operand.
Definition: Expr.cpp:4193
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition: Expr.h:457
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:469
isModifiableLvalueResult
Definition: Expr.h:297
@ MLV_DuplicateVectorComponents
Definition: Expr.h:301
@ MLV_LValueCast
Definition: Expr.h:303
@ MLV_InvalidMessageExpression
Definition: Expr.h:312
@ MLV_ConstQualifiedField
Definition: Expr.h:306
@ MLV_InvalidExpression
Definition: Expr.h:302
@ MLV_IncompleteType
Definition: Expr.h:304
@ MLV_Valid
Definition: Expr.h:298
@ MLV_ConstQualified
Definition: Expr.h:305
@ MLV_NoSetterProperty
Definition: Expr.h:309
@ MLV_ArrayTemporary
Definition: Expr.h:314
@ MLV_SubObjCPropertySetting
Definition: Expr.h:311
@ MLV_ConstAddrSpace
Definition: Expr.h:307
@ MLV_MemberFunction
Definition: Expr.h:310
@ MLV_NotObjectType
Definition: Expr.h:299
@ MLV_ArrayType
Definition: Expr.h:308
@ MLV_ClassTemporary
Definition: Expr.h:313
@ MLV_IncompleteVoidType
Definition: Expr.h:300
QualType getType() const
Definition: Expr.h:142
bool isOrdinaryOrBitFieldObject() const
Definition: Expr.h:448
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition: Expr.cpp:136
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:6305
ExtVectorType - Extended vector type.
Definition: Type.h:4113
Represents difference between two FPOptions values.
Definition: LangOptions.h:947
bool isFPConstrained() const
Definition: LangOptions.h:875
RoundingMode getRoundingMode() const
Definition: LangOptions.h:881
Represents a member of a struct/union/class.
Definition: Decl.h:3030
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3121
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3191
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3247
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:999
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1078
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:1044
const Expr * getSubExpr() const
Definition: Expr.h:1057
bool ValidateCandidate(const TypoCorrection &candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
Represents a function declaration or definition.
Definition: Decl.h:1932
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3699
bool isImmediateFunction() const
Definition: Decl.cpp:3276
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3859
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3618
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3717
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2793
QualType getReturnType() const
Definition: Decl.h:2717
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2368
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3478
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2121
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2805
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3965
bool isConsteval() const
Definition: Decl.h:2407
size_t param_size() const
Definition: Decl.h:2662
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3144
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition: Decl.cpp:3875
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition: Decl.h:2753
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4647
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5002
QualType desugar() const
Definition: Type.h:5546
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5468
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5282
bool isParamConsumed(unsigned I) const
Definition: Type.h:5482
unsigned getNumParams() const
Definition: Type.h:5255
QualType getParamType(unsigned i) const
Definition: Type.h:5257
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5379
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5266
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5262
ArrayRef< QualType > param_types() const
Definition: Type.h:5411
Declaration of a template function.
Definition: DeclTemplate.h:957
unsigned getNumParams() const
Definition: TypeLoc.h:1500
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1506
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1452
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1509
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1444
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4419
bool getCmseNSCall() const
Definition: Type.h:4469
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4493
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4308
ExtInfo getExtInfo() const
Definition: Type.h:4642
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4638
QualType getReturnType() const
Definition: Type.h:4630
bool getCmseNSCallAttr() const
Definition: Type.h:4640
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4654
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4667
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo * > AssocTypes, ArrayRef< Expr * > AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression accepting an expression predicate.
Definition: Expr.cpp:4493
One of these records is kept for each identifier that is lexed.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1717
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3675
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:567
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3318
Describes an C or C++ initializer list.
Definition: Expr.h:5039
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
static InitializationKind CreateCStyleCast(SourceLocation StartLoc, SourceRange TypeRange, bool InitList)
Create a direct initialization for a C-style cast.
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:7521
Describes an entity that is being initialized.
static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc, QualType Type)
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type)
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI)
Create the entity for a compound literal initializer.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:977
Represents the declaration of a label.
Definition: Decl.h:499
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
FPEvalMethodKind
Possible float expression evaluation method choices.
Definition: LangOptions.h:288
@ FEM_Extended
Use extended type for fp arithmetic.
Definition: LangOptions.h:297
@ FEM_Double
Use the type double for fp arithmetic.
Definition: LangOptions.h:295
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
Definition: LangOptions.h:302
@ FEM_Source
Use the declared type for fp arithmetic.
Definition: LangOptions.h:293
@ None
Permit no implicit vector bitcasts.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:476
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:511
bool isSubscriptPointerArithmetic() const
Definition: LangOptions.h:644
bool isSignedOverflowDefined() const
Definition: LangOptions.h:640
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition: Lexer.cpp:1024
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token,...
Definition: Lexer.h:399
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping '\' and " characters and ii) ...
Definition: Lexer.cpp:310
Represents the results of name lookup.
Definition: Lookup.h:46
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition: Lookup.h:495
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:485
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
bool isAmbiguous() const
Definition: Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition: Lookup.h:452
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
void setNamingClass(CXXRecordDecl *Record)
Sets the 'naming class' for this lookup.
Definition: Lookup.h:457
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:575
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
A global _GUID constant.
Definition: DeclCXX.h:4293
MS property subscript expression.
Definition: ExprCXX.h:1004
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition: Expr.h:2752
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:4183
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4197
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3187
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3376
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3270
static MemberExpr * Create(const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, DeclAccessPair FoundDecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR)
Definition: Expr.cpp:1754
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3405
Expr * getBase() const
Definition: Expr.h:3264
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:637
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1668
bool isExternallyVisible() const
Definition: Decl.h:408
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:372
Represent a C++ namespace.
Definition: Decl.h:547
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
NumericLiteralParser - This performs strict semantic analysis of the content of a ppnumber,...
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1527
ivar_iterator ivar_begin() const
Definition: DeclObjC.h:1452
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:352
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7343
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition: ExprObjC.h:1491
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:549
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprObjC.h:595
SourceLocation getLocation() const
Definition: ExprObjC.h:592
SourceLocation getOpLoc() const
Definition: ExprObjC.h:600
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:579
bool isArrow() const
Definition: ExprObjC.h:587
SourceLocation getEndLoc() const LLVM_READONLY
Definition: ExprObjC.h:598
const Expr * getBase() const
Definition: ExprObjC.h:583
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:945
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:418
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
QualType getReturnType() const
Definition: DeclObjC.h:329
bool isClassMethod() const
Definition: DeclObjC.h:434
Represents a pointer to an Objective C object.
Definition: Type.h:7399
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1799
qual_range quals() const
Definition: Type.h:7518
Represents a class type in Objective C.
Definition: Type.h:7145
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:179
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2083
bool allowsSizeofAlignof() const
Does this runtime allow sizeof or alignof on object types?
Definition: ObjCRuntime.h:332
bool allowsPointerArithmetic() const
Does this runtime allow pointer arithmetic on objects?
Definition: ObjCRuntime.h:340
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr * > exprs, SourceLocation RParenLoc)
Definition: Expr.cpp:1657
Helper class for OffsetOfExpr.
Definition: Expr.h:2369
void * getAsOpaquePtr() const
Definition: Ownership.h:90
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:91
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1008
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:2982
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3043
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2135
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2154
const Expr * getSubExpr() const
Definition: Expr.h:2150
Expr * getExpr(unsigned Init)
Definition: Expr.h:5847
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4746
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5845
Represents a parameter to a function.
Definition: Decl.h:1722
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1851
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1755
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1855
QualType getOriginalType() const
Definition: Decl.cpp:2912
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2903
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3004
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3187
QualType getPointeeType() const
Definition: Type.h:3197
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition: Expr.cpp:638
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition: Expr.cpp:678
SourceLocation getLastFPEvalPragmaLocation() const
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token's location and length to ...
LangOptions::FPEvalMethodKind getCurrentFPEvalMethod() const
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
uint8_t getSpellingOfSingleCharacterNumericConstant(const Token &Tok, bool *Invalid=nullptr) const
Given a Token Tok that is a numeric constant with length 1, return the value of constant as an unsign...
SourceManager & getSourceManager() const
bool isMacroDefined(StringRef Id)
const TargetInfo & getTargetInfo() const
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
IdentifierTable & getIdentifierTable()
const LangOptions & getLangOpts() const
DiagnosticsEngine & getDiagnostics() const
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6497
A (possibly-)qualified type.
Definition: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7834
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7839
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition: Type.h:7897
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3476
@ DK_nontrivial_c_struct
Definition: Type.h:1535
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2822
QualType withConst() const
Definition: Type.h:1166
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1163
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:7932
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7750
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7876
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition: Type.h:7891
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7790
bool isAddressSpaceOverlapping(QualType T) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition: Type.h:1423
bool isCXX98PODType(const ASTContext &Context) const
Return true if this is a POD type according to the rules of the C++98 standard, regardless of the cur...
Definition: Type.cpp:2604
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1444
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7951
QualType getCanonicalType() const
Definition: Type.h:7802
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7844
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2840
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:1186
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C.
Definition: Type.h:7958
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7823
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7871
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition: Type.cpp:1629
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1542
bool isCanonical() const
Definition: Type.h:7807
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1316
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1339
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2596
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7782
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition: Type.h:7885
The collection of all-type qualifiers we support.
Definition: Type.h:319
unsigned getCVRQualifiers() const
Definition: Type.h:475
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:482
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:348
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:351
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:354
void removeObjCLifetime()
Definition: Type.h:538
void removeAddressSpace()
Definition: Type.h:583
void addConst()
Definition: Type.h:447
void setAddressSpace(LangAS space)
Definition: Type.h:578
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:695
ObjCLifetime getObjCLifetime() const
Definition: Type.h:532
Qualifiers withoutObjCLifetime() const
Definition: Type.h:520
Qualifiers withoutObjCGCAttr() const
Definition: Type.h:515
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:732
LangAS getAddressSpace() const
Definition: Type.h:558
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:755
Represents a struct/union/class.
Definition: Decl.h:4145
field_range fields() const
Definition: Decl.h:4351
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5965
RecordDecl * getDecl() const
Definition: Type.h:5975
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition: Expr.cpp:5182
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:217
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3428
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:262
@ ContinueScope
This is a while, do, for, which can have continue statements embedded into it.
Definition: Scope.h:59
@ ControlScope
The controlling scope in a if/switch/while/for statement.
Definition: Scope.h:66
@ BreakScope
This is a while, do, switch, for, etc that can have break statements embedded into it.
Definition: Scope.h:55
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isUnarySelector() const
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
Sema & SemaRef
Definition: SemaBase.h:40
void RecordImplicitHostDeviceFuncUsedByDevice(const FunctionDecl *FD)
Record FD if it is a CUDA/HIP implicit host device function used on device side in device compilation...
Definition: SemaCUDA.cpp:706
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:136
bool CheckCall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition: SemaCUDA.cpp:882
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition: SemaCUDA.h:120
ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose=true, bool DiagnoseCFAudited=false, BinaryOperatorKind Opc=BO_PtrMemD)
Checks for invalid conversions and casts between retainable pointers and other pointer kinds for ARC ...
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures.
Definition: SemaObjC.h:864
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr)
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr)
const DeclContext * getCurObjCLexicalContext() const
Definition: SemaObjC.cpp:1260
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
Definition: SemaObjC.cpp:1161
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
void diagnoseARCUnbridgedCast(Expr *e)
Given that we saw an expression with the ARCUnbridgedCastTy placeholder type, complain bitterly.
ObjCMethodDecl * LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance)
LookupMethodInQualifiedType - Lookups up a method in protocol qualifier list of a qualified objective...
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod)
Build an ObjC subscript pseudo-object expression, given that that's supported by the runtime.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: SemaObjC.h:601
ExprResult ActOnArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, Expr *Length, SourceLocation RBLoc)
Checks and creates an Array Section used in an OpenACC construct/clause.
ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig)
Given the potential call expression Call, determine if there is a specialization via the OpenMP decla...
void tryCaptureOpenMPLambdas(ValueDecl *V)
Function tries to capture lambda's captured variables in the OpenMP region before the original lambda...
OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const
Check if the specified variable is used in 'private' clause.
VarDecl * isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo=false, unsigned StopAt=0)
Check if the specified variable is used in one of the private clauses (private, firstprivate,...
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc)
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const
Return true if the provided declaration VD should be captured by reference.
bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified variable is captured by 'target' directive.
bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified global variable must be captured by outer capture regions.
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition: SemaOpenMP.h:371
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
const ValueDecl * getOpenMPDeclareMapperVarName() const
ExprResult checkAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS)
ExprResult checkIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op)
Check an increment or decrement of a pseudo-object expression.
ExprResult checkRValue(Expr *E)
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8073
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:12138
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7249
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T)
Definition: SemaExpr.cpp:16929
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:16935
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:493
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
Definition: SemaExpr.cpp:14387
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6329
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition: Sema.h:7818
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:13139
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:763
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args=std::nullopt, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2446
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
Definition: SemaExpr.cpp:15611
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:7880
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3590
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15288
bool isAlwaysConstantEvaluatedContext() const
Definition: Sema.h:7788
bool isExternalWithNoLinkageType(const ValueDecl *VD) const
Determine if VD, which must be a variable or function, is an external symbol that nonetheless can't b...
Definition: Sema.cpp:871
bool isAttrContext() const
Definition: Sema.h:6476
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:15054
ExprResult IgnoredValueConversions(Expr *E)
IgnoredValueConversions - Given that an expression's result is syntactically ignored,...
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:7873
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9015
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition: Sema.h:9054
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9023
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition: SemaExpr.cpp:412
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19401
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13003
VariadicCallType
Definition: Sema.h:2346
@ VariadicDoesNotApply
Definition: Sema.h:2351
@ VariadicFunction
Definition: Sema.h:2347
@ VariadicMethod
Definition: Sema.h:2349
@ VariadicConstructor
Definition: Sema.h:2350
@ VariadicBlock
Definition: Sema.h:2348
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:6968
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
@ NTCUC_CompoundLiteral
Definition: Sema.h:3649
@ NTCUC_Assignment
Definition: Sema.h:3647
@ NTCUC_FunctionReturn
Definition: Sema.h:3639
@ NTCUC_LValueToRValueVolatile
Definition: Sema.h:3653
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool areVectorTypesSameSize(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7472
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
Definition: SemaExpr.cpp:2332
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition: Sema.h:1179
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:15630
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec)
Emit a warning for all pending noderef expressions that we recorded.
Definition: SemaExpr.cpp:17247
void ActOnStmtExprError()
Definition: SemaExpr.cpp:15636
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
Definition: SemaExpr.cpp:1551
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
Definition: SemaExpr.cpp:12023
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
Definition: SemaDecl.cpp:16274
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition: Sema.h:907
SemaCUDA & CUDA()
Definition: Sema.h:1124
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17182
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
Definition: SemaExpr.cpp:20133
ConditionKind
Definition: Sema.h:7371
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
@ Switch
An integral condition for a 'switch' statement.
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2662
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:900
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2296
Preprocessor & getPreprocessor() const
Definition: Sema.h:559
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition: Sema.h:6454
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2165
QualType GetSignedSizelessVectorType(QualType V)
Definition: SemaExpr.cpp:12581
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of 'this' is actually available in the current context, if it is a potentially ev...
llvm::SmallPtrSet< ConstantExpr *, 4 > FailedImmediateInvocations
Definition: Sema.h:7949
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3530
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition: Sema.h:7861
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex)
Definition: SemaExpr.cpp:18205
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:16940
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
Definition: SemaExpr.cpp:6609
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
Definition: SemaExpr.cpp:10064
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef< QualType > ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit=nullptr)
LookupLiteralOperator - Determine which literal operator should be used for a user-defined literal,...
FPOptionsOverride CurFPFeatureOverrides()
Definition: Sema.h:1710
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types? I.e.
Definition: SemaExpr.cpp:7446
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false, ArrayRef< const Expr * > StopAt=std::nullopt)
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
Definition: SemaExpr.cpp:19920
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth)
Definition: SemaExpr.cpp:15649
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
bool CheckConceptUseInDefinition(ConceptDecl *Concept, SourceLocation Loc)
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16297
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition: Sema.h:6466
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition: Sema.cpp:1567
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition: SemaExpr.cpp:784
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
ExprResult CheckUnevaluatedOperand(Expr *E)
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
Definition: SemaExpr.cpp:1036
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Look for instances where it is likely the comma operator is confused with another operator.
Definition: SemaExpr.cpp:13711
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:4979
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
Definition: SemaExpr.cpp:1993
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
Definition: SemaExpr.cpp:7556
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:13991
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15041
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1058
ASTContext & Context
Definition: Sema.h:962
static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading=false)
To be used for checking whether the arguments being passed to function exceeds the number of paramete...
Definition: Sema.h:7775
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
Definition: SemaCast.cpp:2691
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
Definition: SemaExpr.cpp:9762
bool DiagIfReachable(SourceLocation Loc, ArrayRef< const Stmt * > Stmts, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the statements's reachability analysis.
Definition: SemaExpr.cpp:19931
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:11420
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:557
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
Definition: SemaExpr.cpp:7821
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool CheckCaseExpression(Expr *E)
Definition: SemaExpr.cpp:20906
SemaObjC & ObjC()
Definition: Sema.h:1164
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
Definition: SemaExpr.cpp:12842
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain=false, bool(*IsPlausibleResult)(QualType)=nullptr)
Try to recover by turning the given expression into a call.
Definition: Sema.cpp:2673
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
AllowFoldKind
Definition: Sema.h:7263
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1496
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19414
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:752
bool isImmediateFunctionContext() const
Definition: Sema.h:7800
ASTContext & getASTContext() const
Definition: Sema.h:560
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition: SemaExpr.cpp:762
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15567
bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
Definition: SemaExpr.cpp:18696
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:19662
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
Definition: SemaExpr.cpp:15085
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17603
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9505
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition: Sema.cpp:702
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition: SemaExpr.cpp:867
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
Definition: SemaExpr.cpp:3478
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
Definition: SemaExpr.cpp:6132
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3087
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr)
Definition: SemaExpr.cpp:6982
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:15617
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:5616
@ None
This is not a defaultable comparison operator.
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:7837
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:12888
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1572
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2198
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
Definition: SemaExpr.cpp:15905
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< TypeSourceInfo * > Types, ArrayRef< Expr * > Exprs)
ControllingExprOrType is either a TypeSourceInfo * or an Expr *.
Definition: SemaExpr.cpp:1665
AssumedTemplateKind
Definition: Sema.h:11129
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
Definition: SemaExpr.cpp:1963
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
SourceRange getExprRange(Expr *E) const
Definition: SemaExpr.cpp:507
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition: Sema.h:703
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
std::optional< ExpressionEvaluationContextRecord::InitializationContext > OutermostDeclarationWithDelayedImmediateInvocations() const
Definition: Sema.h:7833
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition: SemaStmt.cpp:225
FPOptions & getCurFPFeatures()
Definition: Sema.h:555
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition: Sema.h:7943
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20164
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:84
@ UPPC_Block
Block expression.
Definition: Sema.h:13950
const LangOptions & getLangOpts() const
Definition: Sema.h:553
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
void DiagnoseInvalidJumps(Stmt *Body)
TypoExpr * CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12050
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
Definition: SemaExpr.cpp:7220
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12817
SemaOpenACC & OpenACC()
Definition: Sema.h:1169
ReuseLambdaContextDecl_t
Definition: Sema.h:6551
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
Definition: SemaDecl.cpp:6562
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void MarkExpressionAsImmediateEscalating(Expr *E)
Definition: SemaExpr.cpp:17278
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
Definition: SemaExpr.cpp:2246
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc)
Produce diagnostics if FD is an aligned allocation or deallocation function that is unavailable.
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E)
Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
Definition: SemaExpr.cpp:19803
Preprocessor & PP
Definition: Sema.h:961
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:10855
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5650
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6408
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
Definition: SemaExpr.cpp:13963
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
Definition: SemaExpr.cpp:16571
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
Definition: SemaExpr.cpp:4694
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition: Sema.cpp:1984
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
Definition: SemaExpr.cpp:7461
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
const LangOptions & LangOpts
Definition: Sema.h:960
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
Definition: SemaExpr.cpp:15719
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2409
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
Definition: SemaExpr.cpp:6659
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17299
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7484
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:6046
SemaHLSL & HLSL()
Definition: Sema.h:1129
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand,...
Definition: SemaExpr.cpp:17263
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:205
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:73
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:19813
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Diagnose cases where a scalar was implicitly converted to a vector and diagnose the underlying types.
Definition: SemaExpr.cpp:9786
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any ArgDependent DiagnoseIfAttr...
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6487
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:6072
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1579
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9370
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
SmallVector< std::deque< PendingImplicitInstantiation >, 8 > SavedPendingInstantiations
Definition: Sema.h:13527
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:936
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
Definition: SemaExpr.cpp:15530
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:785
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
Definition: SemaCast.cpp:3341
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:993
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
Definition: SemaExpr.cpp:3629
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
Definition: SemaExpr.cpp:10323
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
Definition: SemaExpr.cpp:9557
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr)
DiagnoseAssignmentEnum - Warn if assignment to enum is a constant integer not in the range of enum va...
Definition: SemaStmt.cpp:1664
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6484
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition: Sema.cpp:2148
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:640
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3175
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:7804
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
Definition: SemaExpr.cpp:7207
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr * > ArgExprs)
ControllingExprOrType is either an opaque pointer coming out of a ParsedType or an Expr *.
Definition: SemaExpr.cpp:1633
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
Definition: SemaExpr.cpp:16091
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7597
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2365
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1097
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:7465
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
Definition: SemaExpr.cpp:20627
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition: Sema.h:12162
@ VAK_Invalid
Definition: Sema.h:7559
@ VAK_Valid
Definition: Sema.h:7555
@ VAK_ValidInCXX11
Definition: Sema.h:7556
@ VAK_MSVCUndefined
Definition: Sema.h:7558
@ VAK_Undefined
Definition: Sema.h:7557
SemaOpenCL & OpenCL()
Definition: Sema.h:1174
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5776
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:13536
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:16453
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
Definition: SemaExpr.cpp:7843
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
Definition: SemaExpr.cpp:19866
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:7796
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1547
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:7599
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition: Sema.h:7643
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition: Sema.h:7609
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition: Sema.h:7667
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition: Sema.h:7672
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition: Sema.h:7659
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:7638
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:7617
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition: Sema.h:7676
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:7601
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition: Sema.h:7628
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:7680
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition: Sema.h:7613
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition: Sema.h:7622
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:7634
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition: Sema.h:7655
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition: Sema.h:7649
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition: Sema.h:7605
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition: Sema.h:7663
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
Definition: SemaDecl.cpp:8355
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition: Sema.h:7418
@ ACK_Arithmetic
An arithmetic operation.
Definition: Sema.h:7420
@ ACK_CompAssign
A compound assignment expression.
Definition: Sema.h:7428
@ ACK_BitwiseOp
A bitwise operation.
Definition: Sema.h:7422
@ ACK_Conditional
A conditional (?:) operator.
Definition: Sema.h:7426
@ ACK_Comparison
A comparison.
Definition: Sema.h:7424
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:19762
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
Definition: SemaExpr.cpp:2882
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4093
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16538
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition: Sema.h:6299
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20717
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17162
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef< Expr * > Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13490
SourceManager & getSourceManager() const
Definition: Sema.h:558
TryCaptureKind
Definition: Sema.h:6613
@ TryCapture_Implicit
Definition: Sema.h:6614
@ TryCapture_ExplicitByRef
Definition: Sema.h:6616
AssignmentAction
Definition: Sema.h:6495
@ AA_Returning
Definition: Sema.h:6498
@ AA_Passing_CFAudited
Definition: Sema.h:6503
@ AA_Initializing
Definition: Sema.h:6500
@ AA_Converting
Definition: Sema.h:6499
@ AA_Assigning
Definition: Sema.h:6496
@ AA_Passing
Definition: Sema.h:6497
@ AA_Casting
Definition: Sema.h:6502
@ AA_Sending
Definition: Sema.h:6501
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
Definition: SemaExpr.cpp:6637
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:4374
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?: operation.
Definition: SemaExpr.cpp:8705
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckVectorCompareOperands - vector comparisons are a clang extension that operates on extended vecto...
Definition: SemaExpr.cpp:12593
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:10498
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
Definition: SemaExpr.cpp:19378
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13550
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
@ NTCUK_Destruct
Definition: Sema.h:3665
@ NTCUK_Copy
Definition: Sema.h:3666
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20001
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5453
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7491
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
Definition: SemaExpr.cpp:7528
void keepInLifetimeExtendingContext()
keepInLifetimeExtendingContext - Pull down InLifetimeExtendingContext flag from previous context.
Definition: Sema.h:7851
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:2196
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
QualType CXXCheckConditionalOperands(ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc)
Check the operands of ?: under C++ semantics.
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
MaybeODRUseExprSet MaybeODRUseExprs
Definition: Sema.h:6297
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:216
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:8198
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e....
Definition: SemaExpr.cpp:2042
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14938
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
Definition: SemaExpr.cpp:15072
void checkUnusedDeclAttributes(Declarator &D)
checkUnusedDeclAttributes - Given a declarator which is not being used to build a declaration,...
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind)
Definition: SemaExpr.cpp:7630
@ CTK_ErrorRecovery
Definition: Sema.h:9409
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2350
bool isConstantEvaluatedContext() const
Definition: Sema.h:2182
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3078
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12458
ASTConsumer & Consumer
Definition: Sema.h:963
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:4238
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:6491
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:121
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:998
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:13519
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5102
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3526
ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, StringLiteral *BinaryData)
Definition: SemaExpr.cpp:16579
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
Definition: SemaExpr.cpp:12538
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
Definition: SemaExpr.cpp:8331
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition: Sema.h:6241
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ DiscardedStatement
The current expression occurs within a discarded statement.
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range)
Definition: SemaCast.cpp:2043
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Parse a __builtin_astype expression.
Definition: SemaExpr.cpp:6630
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
Definition: SemaExpr.cpp:4600
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5653
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
Definition: SemaExpr.cpp:20007
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
Definition: SemaExpr.cpp:4211
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16290
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
Definition: SemaType.cpp:5766
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8907
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:923
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20647
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope.
Definition: SemaExpr.cpp:19012
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:7665
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition: Sema.h:7786
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr)
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17681
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:19004
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7946
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1307
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
Definition: SemaExpr.cpp:7577
SourceManager & SourceMgr
Definition: Sema.h:965
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
Definition: SemaExpr.cpp:4686
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:7738
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const
Determine whether FD is an aligned allocation or deallocation function that is unavailable.
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
Definition: SemaExpr.cpp:2387
DiagnosticsEngine & Diags
Definition: Sema.h:964
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:554
FPOptions CurFPFeatures
Definition: Sema.h:958
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:516
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
Definition: SemaLambda.cpp:691
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types? That is, given that one of them is a vector,...
Definition: SemaExpr.cpp:7514
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9655
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5527
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
Definition: SemaExpr.cpp:20050
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
void PopDeclContext()
Definition: SemaDecl.cpp:1314
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12939
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:6076
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:15644
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
Definition: SemaExpr.cpp:991
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
Definition: SemaExpr.cpp:6007
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12654
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8808
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
Definition: SemaDecl.cpp:13004
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
Definition: SemaExpr.cpp:16101
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD)
Produce notes explaining why a defaulted function was defined as deleted.
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:574
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
Definition: SemaExpr.cpp:19784
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
Definition: SemaExpr.cpp:16607
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:17862
ExprResult ActOnStmtExprResult(ExprResult E)
Definition: SemaExpr.cpp:15688
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4739
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:5893
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:282
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
Definition: SemaExpr.cpp:20106
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1967
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:20914
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15135
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3663
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Definition: SemaExpr.cpp:2955
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7182
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:15943
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
Definition: SemaExpr.cpp:4812
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
Definition: SemaExpr.cpp:14600
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9083
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6370
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
Definition: SemaExpr.cpp:4669
QualType PreferredConditionType(ConditionKind K) const
Definition: Sema.h:7516
void clearDelayedTypo(TypoExpr *TE)
Clears the state of the given TypoExpr.
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition: Sema.h:9068
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition: Sema.h:9074
@ LOLR_Error
The lookup resulted in an error.
Definition: Sema.h:9066
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition: Sema.h:9071
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition: Sema.h:9082
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition: Sema.h:9078
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:15972
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:10537
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition: Sema.h:13515
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2731
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
Definition: SemaDecl.cpp:15682
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
Definition: SemaDecl.cpp:13256
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:10978
static ConditionResult ConditionError()
Definition: Sema.h:7358
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ActOnConvertVectorExpr - create a new convert-vector expression from the provided arguments.
Definition: SemaExpr.cpp:6651
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
const TypoExprState & getTypoExprState(TypoExpr *TE) const
ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType)
Type-check an expression that's being passed to an __unknown_anytype parameter.
Definition: SemaExpr.cpp:20651
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
Definition: SemaExpr.cpp:5753
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:15886
SemaPseudoObject & PseudoObject()
Definition: Sema.h:1189
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2341
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:7314
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy)
Definition: SemaCast.cpp:2704
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:17689
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7114
bool isCheckingDefaultArgumentOrInitializer() const
Definition: Sema.h:7810
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:5314
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8293
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc)
Definition: SemaExpr.cpp:4987
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4761
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.
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.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition: Overload.h:292
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:303
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:383
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4417
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:185
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
StmtClass getStmtClass() const
Definition: Stmt.h:1363
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
unsigned getLength() const
Definition: Expr.h:1895
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1870
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1191
StringRef getString() const
Definition: Expr.h:1855
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3664
bool isUnion() const
Definition: Decl.h:3767
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3785
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Exposes information about the current target.
Definition: TargetInfo.h:218
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:321
virtual size_t getMaxBitIntWidth() const
Definition: TargetInfo.h:672
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
Definition: TargetInfo.h:992
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:270
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:472
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:509
IntType getSizeType() const
Definition: TargetInfo.h:371
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:519
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1576
virtual bool supportsExtendIntArgs() const
Whether the option -fextend-arguments={32,64} is supported on the target.
Definition: TargetInfo.h:1669
virtual BuiltinVaListKind getBuiltinVaListKind() const =0
Returns the kind of __builtin_va_list type that should be used with this target.
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
Definition: TargetInfo.h:1033
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
Definition: TargetInfo.h:869
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:514
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1487
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:394
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:132
unsigned getLength() const
Definition: Token.h:135
void setKind(tok::TokenKind K)
Definition: Token.h:95
tok::TokenKind getKind() const
Definition: Token.h:94
void setLocation(SourceLocation L)
Definition: Token.h:140
void startToken()
Reset all flags to cleared.
Definition: Token.h:177
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:196
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents a declaration of a type.
Definition: Decl.h:3367
const Type * getTypeForDecl() const
Definition: Decl.h:3391
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3394
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:89
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:206
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:159
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2684
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7721
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7732
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1829
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2434
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition: Type.h:8380
bool isBlockPointerType() const
Definition: Type.h:8017
bool isVoidType() const
Definition: Type.h:8319
bool isBooleanType() const
Definition: Type.h:8447
bool isFunctionReferenceType() const
Definition: Type.h:8050
bool isObjCBuiltinType() const
Definition: Type.h:8196
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition: Type.cpp:1899
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8497
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:740
bool isIncompleteArrayType() const
Definition: Type.h:8083
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:8295
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:677
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2071
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8477
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition: Type.cpp:2021
bool isVoidPointerType() const
Definition: Type.cpp:665
const ComplexType * getAsComplexIntegerType() const
Definition: Type.cpp:698
bool isArrayType() const
Definition: Type.h:8075
bool isCharType() const
Definition: Type.cpp:2089
bool isFunctionPointerType() const
Definition: Type.h:8043
bool isArithmeticType() const
Definition: Type.cpp:2281
bool isConstantMatrixType() const
Definition: Type.h:8137
bool isPointerType() const
Definition: Type.h:8003
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8359
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2483
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8607
bool isReferenceType() const
Definition: Type.h:8021
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8400
bool isEnumeralType() const
Definition: Type.h:8107
bool isScalarType() const
Definition: Type.h:8418
bool isVariableArrayType() const
Definition: Type.h:8087
bool isSizelessBuiltinType() const
Definition: Type.cpp:2441
bool isClkEventT() const
Definition: Type.h:8218
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2510
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2058
bool isObjCQualifiedIdType() const
Definition: Type.h:8166
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8434
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2236
bool isExtVectorType() const
Definition: Type.h:8119
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2125
bool isExtVectorBoolType() const
Definition: Type.h:8123
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2548
bool isImageType() const
Definition: Type.h:8230
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:8313
bool isPipeType() const
Definition: Type.h:8237
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2703
bool isBitIntType() const
Definition: Type.h:8241
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8288
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8099
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2695
bool isAnyComplexType() const
Definition: Type.h:8111
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8372
bool isHalfType() const
Definition: Type.h:8323
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8388
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2354
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:2296
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:8301
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2186
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2467
bool isQueueT() const
Definition: Type.h:8222
bool isMemberPointerType() const
Definition: Type.h:8057
bool isAtomicType() const
Definition: Type.h:8158
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:8460
bool isObjCIdType() const
Definition: Type.h:8178
bool isMatrixType() const
Definition: Type.h:8133
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2713
bool isComplexIntegerType() const
Definition: Type.cpp:683
bool isUnscopedEnumerationType() const
Definition: Type.cpp:2082
bool isObjCObjectType() const
Definition: Type.h:8149
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:4880
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8593
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4970
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8453
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
bool isFunctionType() const
Definition: Type.h:7999
bool isObjCObjectPointerType() const
Definition: Type.h:8145
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2258
bool isMemberFunctionPointerType() const
Definition: Type.h:8061
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8414
bool isVectorType() const
Definition: Type.h:8115
bool isObjCQualifiedClassType() const
Definition: Type.h:8172
bool isObjCClassType() const
Definition: Type.h:8184
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2266
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2497
ScalarTypeKind
Definition: Type.h:2668
@ STK_FloatingComplex
Definition: Type.h:2677
@ STK_Floating
Definition: Type.h:2675
@ STK_BlockPointer
Definition: Type.h:2670
@ STK_Bool
Definition: Type.h:2673
@ STK_ObjCObjectPointer
Definition: Type.h:2671
@ STK_FixedPoint
Definition: Type.h:2678
@ STK_IntegralComplex
Definition: Type.h:2676
@ STK_CPointer
Definition: Type.h:2669
@ STK_Integral
Definition: Type.h:2674
@ STK_MemberPointer
Definition: Type.h:2672
bool isFloatingType() const
Definition: Type.cpp:2249
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition: Type.cpp:2196
bool isAnyPointerType() const
Definition: Type.h:8011
bool isRealType() const
Definition: Type.cpp:2272
TypeClass getTypeClass() const
Definition: Type.h:2334
bool isSubscriptableVectorType() const
Definition: Type.h:8129
bool isSamplerT() const
Definition: Type.h:8210
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
bool isNullPtrType() const
Definition: Type.h:8352
bool isRecordType() const
Definition: Type.h:8103
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4693
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2479
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
std::string getAsString(const LangOptions &LO) const
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
DeclClass * getCorrectionDeclAs() const
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
bool isOverloaded() const
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
TypoExpr - Internal placeholder for expressions where typo correction still needs to be performed and...
Definition: Expr.h:6777
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2578
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2188
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition: Expr.h:2237
Expr * getSubExpr() const
Definition: Expr.h:2233
Opcode getOpcode() const
Definition: Expr.h:2228
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1429
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4916
bool isIncrementDecrementOp() const
Definition: Expr.h:2289
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4350
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3202
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition: ExprCXX.cpp:420
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3942
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition: ExprCXX.cpp:1667
bool isImplicitAccess() const
True if this is an implicit access, i.e., one in which the member being accessed was not written in t...
Definition: ExprCXX.cpp:1629
A set of unresolved declarations.
Definition: UnresolvedSet.h:62
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition: ExprCXX.h:637
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4701
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
void setType(QualType newType)
Definition: Decl.h:679
QualType getType() const
Definition: Decl.h:678
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3339
QualType getType() const
Definition: Value.cpp:234
Represents a variable declaration or definition.
Definition: Decl.h:879
bool hasInit() const
Definition: Decl.cpp:2380
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2239
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1231
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1174
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2451
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition: Decl.cpp:2864
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1492
const Expr * getInit() const
Definition: Decl.h:1316
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1165
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1132
@ TLS_None
Not a TLS variable.
Definition: Decl.h:899
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1243
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2357
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2493
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2765
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1210
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2744
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2855
Declaration of a variable template.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3795
Expr * getSizeExpr() const
Definition: Type.h:3814
Represents a GCC generic vector type.
Definition: Type.h:4021
unsigned getNumElements() const
Definition: Type.h:4036
VectorKind getVectorKind() const
Definition: Type.h:4041
QualType getElementType() const
Definition: Type.h:4035
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:784
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition: ScopeInfo.h:790
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition: ScopeInfo.h:794
ValueDecl * getVariable() const
Definition: ScopeInfo.h:675
bool isBlockCapture() const
Definition: ScopeInfo.h:656
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:686
void markUsed(bool IsODRUse)
Definition: ScopeInfo.h:668
bool isInvalid() const
Definition: ScopeInfo.h:661
bool isThisCapture() const
Definition: ScopeInfo.h:649
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition: ScopeInfo.h:695
bool isCopyCapture() const
Definition: ScopeInfo.h:654
bool isNested() const
Definition: ScopeInfo.h:659
Retains information about a captured region.
Definition: ScopeInfo.h:810
unsigned short CapRegionKind
The kind of captured region.
Definition: ScopeInfo.h:825
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:739
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:729
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of 'this'; zero if 'this' is not captured.
Definition: ScopeInfo.h:718
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition: ScopeInfo.h:752
llvm::DenseMap< ValueDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition: ScopeInfo.h:714
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:749
bool isVLATypeCaptured(const VariableArrayType *VAT) const
Determine whether the given variable-array type has been captured.
Definition: ScopeInfo.cpp:229
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:731
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition: ScopeInfo.h:765
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
void recordUseOfWeak(const ExprT *E, bool IsRead=true)
Record that a weak object was accessed.
Definition: ScopeInfo.h:1087
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
Definition: ScopeInfo.cpp:161
void addBlock(const BlockDecl *BD)
Definition: ScopeInfo.h:493
llvm::SmallVector< AddrLabelExpr *, 4 > AddrLabels
The set of GNU address of label extension "&&label".
Definition: ScopeInfo.h:246
bool HasOMPDeclareReductionCombiner
True if current scope is for OpenMP declare reduction combiner.
Definition: ScopeInfo.h:135
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:878
bool lambdaCaptureShouldBeConst() const
Definition: ScopeInfo.cpp:252
void addPotentialCapture(Expr *VarExpr)
Add a variable that might potentially be captured by the lambda and therefore the enclosing lambdas.
Definition: ScopeInfo.h:989
void addPotentialThisCapture(SourceLocation Loc)
Definition: ScopeInfo.h:995
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:865
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition: ScopeInfo.h:886
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:873
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:868
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
void checkExprLifetime(Sema &SemaRef, const InitializedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for initializing the ent...
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition: TokenKinds.h:89
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
bool isa(CodeGen::Address addr)
Definition: Address.h:328
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:212
@ CPlusPlus23
Definition: LangStandard.h:61
@ CPlusPlus20
Definition: LangStandard.h:60
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus11
Definition: LangStandard.h:57
@ CPlusPlus14
Definition: LangStandard.h:58
@ CPlusPlus17
Definition: LangStandard.h:59
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ GVA_StrongExternal
Definition: Linkage.h:76
bool isTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:77
CUDAFunctionTarget
Definition: Cuda.h:140
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:336
@ Nullable
Values of this type can be null.
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
@ NonNull
Values of this type can never be null.
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:149
@ OK_VectorComponent
A vector component is an element or range of elements on a vector.
Definition: Specifiers.h:157
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:161
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:154
@ OK_MatrixComponent
A matrix component is a single element of a matrix.
Definition: Specifiers.h:169
BinaryOperatorKind
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition: OpenMPKinds.h:27
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
@ CR_OpenMP
Definition: CapturedStmt.h:19
@ SC_Extern
Definition: Specifiers.h:251
@ SC_Register
Definition: Specifiers.h:257
@ SC_None
Definition: Specifiers.h:250
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:51
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:81
ExprResult ExprEmpty()
Definition: Ownership.h:271
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition: Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:139
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition: Overload.h:202
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:112
@ ICK_Identity
Identity conversion (no conversion)
Definition: Overload.h:106
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:109
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition: Overload.h:136
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:115
UnaryOperatorKind
bool isFunctionLocalStringLiteralMacro(tok::TokenKind K, const LangOptions &LO)
Return true if the token corresponds to a function local predefined macro, which expands to a string ...
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
ExprResult ExprError()
Definition: Ownership.h:264
@ AR_Unavailable
Definition: DeclBase.h:76
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.
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:91
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 char * getTraitSpelling(ExpressionTrait T) LLVM_READONLY
Return the spelling of the type trait TT. Never null.
const FunctionProtoType * T
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:270
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:276
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:284
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:273
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:280
StringLiteralKind
Definition: Expr.h:1749
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_X86VectorCall
Definition: Specifiers.h:283
@ CC_X86StdCall
Definition: Specifiers.h:280
@ CC_X86FastCall
Definition: Specifiers.h:281
@ AltiVecBool
is AltiVec 'vector bool ...'
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ AltiVecVector
is AltiVec vector
@ AltiVecPixel
is AltiVec 'vector Pixel'
@ Neon
is ARM Neon vector
@ Generic
not a target-specific vector type
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
SourceLocIdentKind
Definition: Expr.h:4748
@ None
No keyword precedes the qualified type name.
@ Other
Other implicit parameter.
PredefinedIdentKind
Definition: Expr.h:1975
@ Implicit
An implicit conversion.
CharacterLiteralKind
Definition: Expr.h:1589
@ AS_none
Definition: Specifiers.h:127
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition: Specifiers.h:173
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition: Specifiers.h:183
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:177
@ NOUR_None
This is an odr-use.
Definition: Specifiers.h:175
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition: Specifiers.h:180
#define false
Definition: stdbool.h:26
#define bool
Definition: stdbool.h:24
ExprResult TransformSourceLocExpr(SourceLocExpr *E)
Definition: SemaExpr.cpp:5444
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
Definition: SemaExpr.cpp:5441
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
Definition: SemaExpr.cpp:5428
ExprResult TransformBlockExpr(BlockExpr *E)
Definition: SemaExpr.cpp:5436
ExprResult TransformLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5435
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E)
Definition: SemaExpr.cpp:5421
bool VisitCallExpr(CallExpr *E)
Definition: SemaExpr.cpp:5386
bool VisitCXXConstructExpr(CXXConstructExpr *E)
Definition: SemaExpr.cpp:5392
const ASTContext & Context
Definition: SemaExpr.cpp:5380
bool VisitLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5413
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E)
Definition: SemaExpr.cpp:5417
bool VisitSourceLocExpr(SourceLocExpr *E)
Definition: SemaExpr.cpp:5402
bool shouldVisitImplicitCode() const
Definition: SemaExpr.cpp:5384
ImmediateCallVisitor(const ASTContext &Ctx)
Definition: SemaExpr.cpp:5381
Represents an element in a path from a derived class to a base class.
The class facilities generation and storage of conversion FixIts.
OverloadFixItKind Kind
The type of fix applied.
bool tryToFixConversion(const Expr *FromExpr, const QualType FromQTy, const QualType ToQTy, Sema &S)
If possible, generates and stores a fix for the given conversion.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
Stores data related to a single #embed directive.
Definition: Expr.h:4837
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition: Expr.h:630
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition: Expr.h:614
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:609
Extra information about a function prototype.
Definition: Type.h:5087
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5088
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:12690
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:6303
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition: Sema.h:6337
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition: Sema.h:6383
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition: Sema.h:6342
llvm::SmallPtrSet< DeclRefExpr *, 4 > ReferenceToConsteval
Set of DeclRefExprs referencing a consteval function when used in a context not already known to be i...
Definition: Sema.h:6350
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition: Sema.h:6346
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition: Sema.h:6356
enum clang::Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext
SmallVector< LambdaExpr *, 2 > Lambdas
The lambdas that are present within this context, if it is indeed an unevaluated context.
Definition: Sema.h:6322
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:6360
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:6308
unsigned NumTypos
The number of typos encountered during this expression evaluation context (i.e.
Definition: Sema.h:6316
ExpressionEvaluationContext Context
The expression evaluation context.
Definition: Sema.h:6305
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:6312
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7887
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
uint64_t Width
Definition: ASTContext.h:158
Describes an entity that is being assigned.