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 = IndexExpr;
5037 assert(!ConvExpr.isInvalid() &&
5038 "should be able to convert any integer type to size type");
5039 return ConvExpr.get();
5040 };
5041
5042 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5043 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5044 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5045 if (!RowIdx || !ColumnIdx)
5046 return ExprError();
5047
5048 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5049 MTy->getElementType(), RBLoc);
5050}
5051
5052void Sema::CheckAddressOfNoDeref(const Expr *E) {
5053 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5054 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5055
5056 // For expressions like `&(*s).b`, the base is recorded and what should be
5057 // checked.
5058 const MemberExpr *Member = nullptr;
5059 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5060 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5061
5062 LastRecord.PossibleDerefs.erase(StrippedExpr);
5063}
5064
5065void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5067 return;
5068
5069 QualType ResultTy = E->getType();
5070 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5071
5072 // Bail if the element is an array since it is not memory access.
5073 if (isa<ArrayType>(ResultTy))
5074 return;
5075
5076 if (ResultTy->hasAttr(attr::NoDeref)) {
5077 LastRecord.PossibleDerefs.insert(E);
5078 return;
5079 }
5080
5081 // Check if the base type is a pointer to a member access of a struct
5082 // marked with noderef.
5083 const Expr *Base = E->getBase();
5084 QualType BaseTy = Base->getType();
5085 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5086 // Not a pointer access
5087 return;
5088
5089 const MemberExpr *Member = nullptr;
5090 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5091 Member->isArrow())
5092 Base = Member->getBase();
5093
5094 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5095 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5096 LastRecord.PossibleDerefs.insert(E);
5097 }
5098}
5099
5102 Expr *Idx, SourceLocation RLoc) {
5103 Expr *LHSExp = Base;
5104 Expr *RHSExp = Idx;
5105
5108
5109 // Per C++ core issue 1213, the result is an xvalue if either operand is
5110 // a non-lvalue array, and an lvalue otherwise.
5111 if (getLangOpts().CPlusPlus11) {
5112 for (auto *Op : {LHSExp, RHSExp}) {
5113 Op = Op->IgnoreImplicit();
5114 if (Op->getType()->isArrayType() && !Op->isLValue())
5115 VK = VK_XValue;
5116 }
5117 }
5118
5119 // Perform default conversions.
5120 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5122 if (Result.isInvalid())
5123 return ExprError();
5124 LHSExp = Result.get();
5125 }
5127 if (Result.isInvalid())
5128 return ExprError();
5129 RHSExp = Result.get();
5130
5131 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5132
5133 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5134 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5135 // in the subscript position. As a result, we need to derive the array base
5136 // and index from the expression types.
5137 Expr *BaseExpr, *IndexExpr;
5138 QualType ResultType;
5139 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5140 BaseExpr = LHSExp;
5141 IndexExpr = RHSExp;
5142 ResultType =
5144 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5145 BaseExpr = LHSExp;
5146 IndexExpr = RHSExp;
5147 ResultType = PTy->getPointeeType();
5148 } else if (const ObjCObjectPointerType *PTy =
5149 LHSTy->getAs<ObjCObjectPointerType>()) {
5150 BaseExpr = LHSExp;
5151 IndexExpr = RHSExp;
5152
5153 // Use custom logic if this should be the pseudo-object subscript
5154 // expression.
5156 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5157 nullptr, nullptr);
5158
5159 ResultType = PTy->getPointeeType();
5160 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5161 // Handle the uncommon case of "123[Ptr]".
5162 BaseExpr = RHSExp;
5163 IndexExpr = LHSExp;
5164 ResultType = PTy->getPointeeType();
5165 } else if (const ObjCObjectPointerType *PTy =
5166 RHSTy->getAs<ObjCObjectPointerType>()) {
5167 // Handle the uncommon case of "123[Ptr]".
5168 BaseExpr = RHSExp;
5169 IndexExpr = LHSExp;
5170 ResultType = PTy->getPointeeType();
5172 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5173 << ResultType << BaseExpr->getSourceRange();
5174 return ExprError();
5175 }
5176 } else if (LHSTy->isSubscriptableVectorType()) {
5177 if (LHSTy->isBuiltinType() &&
5178 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5179 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5180 if (BTy->isSVEBool())
5181 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5182 << LHSExp->getSourceRange()
5183 << RHSExp->getSourceRange());
5184 ResultType = BTy->getSveEltType(Context);
5185 } else {
5186 const VectorType *VTy = LHSTy->getAs<VectorType>();
5187 ResultType = VTy->getElementType();
5188 }
5189 BaseExpr = LHSExp; // vectors: V[123]
5190 IndexExpr = RHSExp;
5191 // We apply C++ DR1213 to vector subscripting too.
5192 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5193 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5194 if (Materialized.isInvalid())
5195 return ExprError();
5196 LHSExp = Materialized.get();
5197 }
5198 VK = LHSExp->getValueKind();
5199 if (VK != VK_PRValue)
5200 OK = OK_VectorComponent;
5201
5202 QualType BaseType = BaseExpr->getType();
5203 Qualifiers BaseQuals = BaseType.getQualifiers();
5204 Qualifiers MemberQuals = ResultType.getQualifiers();
5205 Qualifiers Combined = BaseQuals + MemberQuals;
5206 if (Combined != MemberQuals)
5207 ResultType = Context.getQualifiedType(ResultType, Combined);
5208 } else if (LHSTy->isArrayType()) {
5209 // If we see an array that wasn't promoted by
5210 // DefaultFunctionArrayLvalueConversion, it must be an array that
5211 // wasn't promoted because of the C90 rule that doesn't
5212 // allow promoting non-lvalue arrays. Warn, then
5213 // force the promotion here.
5214 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5215 << LHSExp->getSourceRange();
5216 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5217 CK_ArrayToPointerDecay).get();
5218 LHSTy = LHSExp->getType();
5219
5220 BaseExpr = LHSExp;
5221 IndexExpr = RHSExp;
5222 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5223 } else if (RHSTy->isArrayType()) {
5224 // Same as previous, except for 123[f().a] case
5225 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5226 << RHSExp->getSourceRange();
5227 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5228 CK_ArrayToPointerDecay).get();
5229 RHSTy = RHSExp->getType();
5230
5231 BaseExpr = RHSExp;
5232 IndexExpr = LHSExp;
5233 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5234 } else {
5235 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5236 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5237 }
5238 // C99 6.5.2.1p1
5239 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5240 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5241 << IndexExpr->getSourceRange());
5242
5243 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5244 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5245 !IndexExpr->isTypeDependent()) {
5246 std::optional<llvm::APSInt> IntegerContantExpr =
5248 if (!IntegerContantExpr.has_value() ||
5249 IntegerContantExpr.value().isNegative())
5250 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5251 }
5252
5253 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5254 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5255 // type. Note that Functions are not objects, and that (in C99 parlance)
5256 // incomplete types are not object types.
5257 if (ResultType->isFunctionType()) {
5258 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5259 << ResultType << BaseExpr->getSourceRange();
5260 return ExprError();
5261 }
5262
5263 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5264 // GNU extension: subscripting on pointer to void
5265 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5266 << BaseExpr->getSourceRange();
5267
5268 // C forbids expressions of unqualified void type from being l-values.
5269 // See IsCForbiddenLValueType.
5270 if (!ResultType.hasQualifiers())
5271 VK = VK_PRValue;
5272 } else if (!ResultType->isDependentType() &&
5273 !ResultType.isWebAssemblyReferenceType() &&
5275 LLoc, ResultType,
5276 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5277 return ExprError();
5278
5279 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5280 !ResultType.isCForbiddenLValueType());
5281
5283 FunctionScopes.size() > 1) {
5284 if (auto *TT =
5285 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5286 for (auto I = FunctionScopes.rbegin(),
5287 E = std::prev(FunctionScopes.rend());
5288 I != E; ++I) {
5289 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5290 if (CSI == nullptr)
5291 break;
5292 DeclContext *DC = nullptr;
5293 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5294 DC = LSI->CallOperator;
5295 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5296 DC = CRSI->TheCapturedDecl;
5297 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5298 DC = BSI->TheDecl;
5299 if (DC) {
5300 if (DC->containsDecl(TT->getDecl()))
5301 break;
5303 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5304 }
5305 }
5306 }
5307 }
5308
5309 return new (Context)
5310 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5311}
5312
5314 ParmVarDecl *Param, Expr *RewrittenInit,
5315 bool SkipImmediateInvocations) {
5316 if (Param->hasUnparsedDefaultArg()) {
5317 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5318 // If we've already cleared out the location for the default argument,
5319 // that means we're parsing it right now.
5320 if (!UnparsedDefaultArgLocs.count(Param)) {
5321 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5322 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5323 Param->setInvalidDecl();
5324 return true;
5325 }
5326
5327 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5328 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5330 diag::note_default_argument_declared_here);
5331 return true;
5332 }
5333
5334 if (Param->hasUninstantiatedDefaultArg()) {
5335 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5336 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5337 return true;
5338 }
5339
5340 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5341 assert(Init && "default argument but no initializer?");
5342
5343 // If the default expression creates temporaries, we need to
5344 // push them to the current stack of expression temporaries so they'll
5345 // be properly destroyed.
5346 // FIXME: We should really be rebuilding the default argument with new
5347 // bound temporaries; see the comment in PR5810.
5348 // We don't need to do that with block decls, though, because
5349 // blocks in default argument expression can never capture anything.
5350 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5351 // Set the "needs cleanups" bit regardless of whether there are
5352 // any explicit objects.
5353 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5354 // Append all the objects to the cleanup list. Right now, this
5355 // should always be a no-op, because blocks in default argument
5356 // expressions should never be able to capture anything.
5357 assert(!InitWithCleanup->getNumObjects() &&
5358 "default argument expression has capturing blocks?");
5359 }
5360 // C++ [expr.const]p15.1:
5361 // An expression or conversion is in an immediate function context if it is
5362 // potentially evaluated and [...] its innermost enclosing non-block scope
5363 // is a function parameter scope of an immediate function.
5365 *this,
5369 Param);
5370 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5371 SkipImmediateInvocations;
5372 runWithSufficientStackSpace(CallLoc, [&] {
5373 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5374 });
5375 return false;
5376}
5377
5378struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
5380 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {}
5381
5382 bool HasImmediateCalls = false;
5383 bool shouldVisitImplicitCode() const { return true; }
5384
5386 if (const FunctionDecl *FD = E->getDirectCallee())
5387 HasImmediateCalls |= FD->isImmediateFunction();
5389 }
5390
5392 if (const FunctionDecl *FD = E->getConstructor())
5393 HasImmediateCalls |= FD->isImmediateFunction();
5395 }
5396
5397 // SourceLocExpr are not immediate invocations
5398 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5399 // need to be rebuilt so that they refer to the correct SourceLocation and
5400 // DeclContext.
5402 HasImmediateCalls = true;
5404 }
5405
5406 // A nested lambda might have parameters with immediate invocations
5407 // in their default arguments.
5408 // The compound statement is not visited (as it does not constitute a
5409 // subexpression).
5410 // FIXME: We should consider visiting and transforming captures
5411 // with init expressions.
5413 return VisitCXXMethodDecl(E->getCallOperator());
5414 }
5415
5417 return TraverseStmt(E->getExpr());
5418 }
5419
5421 return TraverseStmt(E->getExpr());
5422 }
5423};
5424
5426 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5428 : TreeTransform(SemaRef) {}
5429
5430 // Lambda can only have immediate invocations in the default
5431 // args of their parameters, which is transformed upon calling the closure.
5432 // The body is not a subexpression, so we have nothing to do.
5433 // FIXME: Immediate calls in capture initializers should be transformed.
5436
5437 // Make sure we don't rebuild the this pointer as it would
5438 // cause it to incorrectly point it to the outermost class
5439 // in the case of nested struct initialization.
5441
5442 // Rewrite to source location to refer to the context in which they are used.
5444 if (E->getParentContext() == SemaRef.CurContext)
5445 return E;
5446 return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getType(),
5447 E->getBeginLoc(), E->getEndLoc(),
5448 SemaRef.CurContext);
5449 }
5450};
5451
5453 FunctionDecl *FD, ParmVarDecl *Param,
5454 Expr *Init) {
5455 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5456
5457 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5458 bool InLifetimeExtendingContext = isInLifetimeExtendingContext();
5459 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5460 InitializationContext =
5462 if (!InitializationContext.has_value())
5463 InitializationContext.emplace(CallLoc, Param, CurContext);
5464
5465 if (!Init && !Param->hasUnparsedDefaultArg()) {
5466 // Mark that we are replacing a default argument first.
5467 // If we are instantiating a template we won't have to
5468 // retransform immediate calls.
5469 // C++ [expr.const]p15.1:
5470 // An expression or conversion is in an immediate function context if it
5471 // is potentially evaluated and [...] its innermost enclosing non-block
5472 // scope is a function parameter scope of an immediate function.
5474 *this,
5478 Param);
5479
5480 if (Param->hasUninstantiatedDefaultArg()) {
5481 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5482 return ExprError();
5483 }
5484 // CWG2631
5485 // An immediate invocation that is not evaluated where it appears is
5486 // evaluated and checked for whether it is a constant expression at the
5487 // point where the enclosing initializer is used in a function call.
5489 if (!NestedDefaultChecking)
5490 V.TraverseDecl(Param);
5491
5492 // Rewrite the call argument that was created from the corresponding
5493 // parameter's default argument.
5494 if (V.HasImmediateCalls || InLifetimeExtendingContext) {
5495 if (V.HasImmediateCalls)
5496 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5497 CallLoc, Param, CurContext};
5498 // Pass down lifetime extending flag, and collect temporaries in
5499 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5502 ExprResult Res;
5503 runWithSufficientStackSpace(CallLoc, [&] {
5504 Res = Immediate.TransformInitializer(Param->getInit(),
5505 /*NotCopy=*/false);
5506 });
5507 if (Res.isInvalid())
5508 return ExprError();
5509 Res = ConvertParamDefaultArgument(Param, Res.get(),
5510 Res.get()->getBeginLoc());
5511 if (Res.isInvalid())
5512 return ExprError();
5513 Init = Res.get();
5514 }
5515 }
5516
5518 CallLoc, FD, Param, Init,
5519 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5520 return ExprError();
5521
5522 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5523 Init, InitializationContext->Context);
5524}
5525
5527 assert(Field->hasInClassInitializer());
5528
5529 // If we might have already tried and failed to instantiate, don't try again.
5530 if (Field->isInvalidDecl())
5531 return ExprError();
5532
5533 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5534
5535 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5536
5537 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5538 InitializationContext =
5540 if (!InitializationContext.has_value())
5541 InitializationContext.emplace(Loc, Field, CurContext);
5542
5543 Expr *Init = nullptr;
5544
5545 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5546
5549
5550 if (!Field->getInClassInitializer()) {
5551 // Maybe we haven't instantiated the in-class initializer. Go check the
5552 // pattern FieldDecl to see if it has one.
5553 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5554 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5556 ClassPattern->lookup(Field->getDeclName());
5557
5558 FieldDecl *Pattern = nullptr;
5559 for (auto *L : Lookup) {
5560 if ((Pattern = dyn_cast<FieldDecl>(L)))
5561 break;
5562 }
5563 assert(Pattern && "We must have set the Pattern!");
5564 if (!Pattern->hasInClassInitializer() ||
5565 InstantiateInClassInitializer(Loc, Field, Pattern,
5567 Field->setInvalidDecl();
5568 return ExprError();
5569 }
5570 }
5571 }
5572
5573 // CWG2631
5574 // An immediate invocation that is not evaluated where it appears is
5575 // evaluated and checked for whether it is a constant expression at the
5576 // point where the enclosing initializer is used in a [...] a constructor
5577 // definition, or an aggregate initialization.
5579 if (!NestedDefaultChecking)
5580 V.TraverseDecl(Field);
5581 if (V.HasImmediateCalls) {
5582 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5583 CurContext};
5584 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5585 NestedDefaultChecking;
5586
5588 ExprResult Res;
5590 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5591 /*CXXDirectInit=*/false);
5592 });
5593 if (!Res.isInvalid())
5594 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5595 if (Res.isInvalid()) {
5596 Field->setInvalidDecl();
5597 return ExprError();
5598 }
5599 Init = Res.get();
5600 }
5601
5602 if (Field->getInClassInitializer()) {
5603 Expr *E = Init ? Init : Field->getInClassInitializer();
5604 if (!NestedDefaultChecking)
5606 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5607 });
5608 // C++11 [class.base.init]p7:
5609 // The initialization of each base and member constitutes a
5610 // full-expression.
5611 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5612 if (Res.isInvalid()) {
5613 Field->setInvalidDecl();
5614 return ExprError();
5615 }
5616 Init = Res.get();
5617
5618 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5619 Field, InitializationContext->Context,
5620 Init);
5621 }
5622
5623 // DR1351:
5624 // If the brace-or-equal-initializer of a non-static data member
5625 // invokes a defaulted default constructor of its class or of an
5626 // enclosing class in a potentially evaluated subexpression, the
5627 // program is ill-formed.
5628 //
5629 // This resolution is unworkable: the exception specification of the
5630 // default constructor can be needed in an unevaluated context, in
5631 // particular, in the operand of a noexcept-expression, and we can be
5632 // unable to compute an exception specification for an enclosed class.
5633 //
5634 // Any attempt to resolve the exception specification of a defaulted default
5635 // constructor before the initializer is lexically complete will ultimately
5636 // come here at which point we can diagnose it.
5637 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5638 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5639 << OutermostClass << Field;
5640 Diag(Field->getEndLoc(),
5641 diag::note_default_member_initializer_not_yet_parsed);
5642 // Recover by marking the field invalid, unless we're in a SFINAE context.
5643 if (!isSFINAEContext())
5644 Field->setInvalidDecl();
5645 return ExprError();
5646}
5647
5650 Expr *Fn) {
5651 if (Proto && Proto->isVariadic()) {
5652 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5653 return VariadicConstructor;
5654 else if (Fn && Fn->getType()->isBlockPointerType())
5655 return VariadicBlock;
5656 else if (FDecl) {
5657 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5658 if (Method->isInstance())
5659 return VariadicMethod;
5660 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5661 return VariadicMethod;
5662 return VariadicFunction;
5663 }
5664 return VariadicDoesNotApply;
5665}
5666
5667namespace {
5668class FunctionCallCCC final : public FunctionCallFilterCCC {
5669public:
5670 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5671 unsigned NumArgs, MemberExpr *ME)
5672 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5673 FunctionName(FuncName) {}
5674
5675 bool ValidateCandidate(const TypoCorrection &candidate) override {
5676 if (!candidate.getCorrectionSpecifier() ||
5677 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5678 return false;
5679 }
5680
5682 }
5683
5684 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5685 return std::make_unique<FunctionCallCCC>(*this);
5686 }
5687
5688private:
5689 const IdentifierInfo *const FunctionName;
5690};
5691}
5692
5694 FunctionDecl *FDecl,
5695 ArrayRef<Expr *> Args) {
5696 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5697 DeclarationName FuncName = FDecl->getDeclName();
5698 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5699
5700 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5701 if (TypoCorrection Corrected = S.CorrectTypo(
5703 S.getScopeForContext(S.CurContext), nullptr, CCC,
5705 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5706 if (Corrected.isOverloaded()) {
5709 for (NamedDecl *CD : Corrected) {
5710 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5712 OCS);
5713 }
5714 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5715 case OR_Success:
5716 ND = Best->FoundDecl;
5717 Corrected.setCorrectionDecl(ND);
5718 break;
5719 default:
5720 break;
5721 }
5722 }
5723 ND = ND->getUnderlyingDecl();
5724 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5725 return Corrected;
5726 }
5727 }
5728 return TypoCorrection();
5729}
5730
5731// [C++26][[expr.unary.op]/p4
5732// A pointer to member is only formed when an explicit &
5733// is used and its operand is a qualified-id not enclosed in parentheses.
5735 if (!isa<ParenExpr>(Fn))
5736 return false;
5737
5738 Fn = Fn->IgnoreParens();
5739
5740 auto *UO = dyn_cast<UnaryOperator>(Fn);
5741 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
5742 return false;
5743 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
5744 return DRE->hasQualifier();
5745 }
5746 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
5747 return OVL->getQualifier();
5748 return false;
5749}
5750
5751bool
5753 FunctionDecl *FDecl,
5754 const FunctionProtoType *Proto,
5755 ArrayRef<Expr *> Args,
5756 SourceLocation RParenLoc,
5757 bool IsExecConfig) {
5758 // Bail out early if calling a builtin with custom typechecking.
5759 if (FDecl)
5760 if (unsigned ID = FDecl->getBuiltinID())
5762 return false;
5763
5764 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5765 // assignment, to the types of the corresponding parameter, ...
5766
5767 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
5768 bool HasExplicitObjectParameter =
5769 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
5770 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
5771 unsigned NumParams = Proto->getNumParams();
5772 bool Invalid = false;
5773 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5774 unsigned FnKind = Fn->getType()->isBlockPointerType()
5775 ? 1 /* block */
5776 : (IsExecConfig ? 3 /* kernel function (exec config) */
5777 : 0 /* function */);
5778
5779 // If too few arguments are available (and we don't have default
5780 // arguments for the remaining parameters), don't make the call.
5781 if (Args.size() < NumParams) {
5782 if (Args.size() < MinArgs) {
5783 TypoCorrection TC;
5784 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5785 unsigned diag_id =
5786 MinArgs == NumParams && !Proto->isVariadic()
5787 ? diag::err_typecheck_call_too_few_args_suggest
5788 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5790 TC, PDiag(diag_id)
5791 << FnKind << MinArgs - ExplicitObjectParameterOffset
5792 << static_cast<unsigned>(Args.size()) -
5793 ExplicitObjectParameterOffset
5794 << HasExplicitObjectParameter << TC.getCorrectionRange());
5795 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
5796 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5797 ->getDeclName())
5798 Diag(RParenLoc,
5799 MinArgs == NumParams && !Proto->isVariadic()
5800 ? diag::err_typecheck_call_too_few_args_one
5801 : diag::err_typecheck_call_too_few_args_at_least_one)
5802 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5803 << HasExplicitObjectParameter << Fn->getSourceRange();
5804 else
5805 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5806 ? diag::err_typecheck_call_too_few_args
5807 : diag::err_typecheck_call_too_few_args_at_least)
5808 << FnKind << MinArgs - ExplicitObjectParameterOffset
5809 << static_cast<unsigned>(Args.size()) -
5810 ExplicitObjectParameterOffset
5811 << HasExplicitObjectParameter << Fn->getSourceRange();
5812
5813 // Emit the location of the prototype.
5814 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5815 Diag(FDecl->getLocation(), diag::note_callee_decl)
5816 << FDecl << FDecl->getParametersSourceRange();
5817
5818 return true;
5819 }
5820 // We reserve space for the default arguments when we create
5821 // the call expression, before calling ConvertArgumentsForCall.
5822 assert((Call->getNumArgs() == NumParams) &&
5823 "We should have reserved space for the default arguments before!");
5824 }
5825
5826 // If too many are passed and not variadic, error on the extras and drop
5827 // them.
5828 if (Args.size() > NumParams) {
5829 if (!Proto->isVariadic()) {
5830 TypoCorrection TC;
5831 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5832 unsigned diag_id =
5833 MinArgs == NumParams && !Proto->isVariadic()
5834 ? diag::err_typecheck_call_too_many_args_suggest
5835 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5837 TC, PDiag(diag_id)
5838 << FnKind << NumParams - ExplicitObjectParameterOffset
5839 << static_cast<unsigned>(Args.size()) -
5840 ExplicitObjectParameterOffset
5841 << HasExplicitObjectParameter << TC.getCorrectionRange());
5842 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
5843 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5844 ->getDeclName())
5845 Diag(Args[NumParams]->getBeginLoc(),
5846 MinArgs == NumParams
5847 ? diag::err_typecheck_call_too_many_args_one
5848 : diag::err_typecheck_call_too_many_args_at_most_one)
5849 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5850 << static_cast<unsigned>(Args.size()) -
5851 ExplicitObjectParameterOffset
5852 << HasExplicitObjectParameter << Fn->getSourceRange()
5853 << SourceRange(Args[NumParams]->getBeginLoc(),
5854 Args.back()->getEndLoc());
5855 else
5856 Diag(Args[NumParams]->getBeginLoc(),
5857 MinArgs == NumParams
5858 ? diag::err_typecheck_call_too_many_args
5859 : diag::err_typecheck_call_too_many_args_at_most)
5860 << FnKind << NumParams - ExplicitObjectParameterOffset
5861 << static_cast<unsigned>(Args.size()) -
5862 ExplicitObjectParameterOffset
5863 << HasExplicitObjectParameter << Fn->getSourceRange()
5864 << SourceRange(Args[NumParams]->getBeginLoc(),
5865 Args.back()->getEndLoc());
5866
5867 // Emit the location of the prototype.
5868 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5869 Diag(FDecl->getLocation(), diag::note_callee_decl)
5870 << FDecl << FDecl->getParametersSourceRange();
5871
5872 // This deletes the extra arguments.
5873 Call->shrinkNumArgs(NumParams);
5874 return true;
5875 }
5876 }
5877 SmallVector<Expr *, 8> AllArgs;
5878 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5879
5880 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5881 AllArgs, CallType);
5882 if (Invalid)
5883 return true;
5884 unsigned TotalNumArgs = AllArgs.size();
5885 for (unsigned i = 0; i < TotalNumArgs; ++i)
5886 Call->setArg(i, AllArgs[i]);
5887
5888 Call->computeDependence();
5889 return false;
5890}
5891
5893 const FunctionProtoType *Proto,
5894 unsigned FirstParam, ArrayRef<Expr *> Args,
5895 SmallVectorImpl<Expr *> &AllArgs,
5896 VariadicCallType CallType, bool AllowExplicit,
5897 bool IsListInitialization) {
5898 unsigned NumParams = Proto->getNumParams();
5899 bool Invalid = false;
5900 size_t ArgIx = 0;
5901 // Continue to check argument types (even if we have too few/many args).
5902 for (unsigned i = FirstParam; i < NumParams; i++) {
5903 QualType ProtoArgType = Proto->getParamType(i);
5904
5905 Expr *Arg;
5906 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5907 if (ArgIx < Args.size()) {
5908 Arg = Args[ArgIx++];
5909
5910 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5911 diag::err_call_incomplete_argument, Arg))
5912 return true;
5913
5914 // Strip the unbridged-cast placeholder expression off, if applicable.
5915 bool CFAudited = false;
5916 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5917 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5918 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5919 Arg = ObjC().stripARCUnbridgedCast(Arg);
5920 else if (getLangOpts().ObjCAutoRefCount &&
5921 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5922 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5923 CFAudited = true;
5924
5925 if (Proto->getExtParameterInfo(i).isNoEscape() &&
5926 ProtoArgType->isBlockPointerType())
5927 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5928 BE->getBlockDecl()->setDoesNotEscape();
5929
5930 InitializedEntity Entity =
5932 ProtoArgType)
5934 Context, ProtoArgType, Proto->isParamConsumed(i));
5935
5936 // Remember that parameter belongs to a CF audited API.
5937 if (CFAudited)
5938 Entity.setParameterCFAudited();
5939
5941 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5942 if (ArgE.isInvalid())
5943 return true;
5944
5945 Arg = ArgE.getAs<Expr>();
5946 } else {
5947 assert(Param && "can't use default arguments without a known callee");
5948
5949 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5950 if (ArgExpr.isInvalid())
5951 return true;
5952
5953 Arg = ArgExpr.getAs<Expr>();
5954 }
5955
5956 // Check for array bounds violations for each argument to the call. This
5957 // check only triggers warnings when the argument isn't a more complex Expr
5958 // with its own checking, such as a BinaryOperator.
5959 CheckArrayAccess(Arg);
5960
5961 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5962 CheckStaticArrayArgument(CallLoc, Param, Arg);
5963
5964 AllArgs.push_back(Arg);
5965 }
5966
5967 // If this is a variadic call, handle args passed through "...".
5968 if (CallType != VariadicDoesNotApply) {
5969 // Assume that extern "C" functions with variadic arguments that
5970 // return __unknown_anytype aren't *really* variadic.
5971 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5972 FDecl->isExternC()) {
5973 for (Expr *A : Args.slice(ArgIx)) {
5974 QualType paramType; // ignored
5975 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5976 Invalid |= arg.isInvalid();
5977 AllArgs.push_back(arg.get());
5978 }
5979
5980 // Otherwise do argument promotion, (C99 6.5.2.2p7).
5981 } else {
5982 for (Expr *A : Args.slice(ArgIx)) {
5983 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5984 Invalid |= Arg.isInvalid();
5985 AllArgs.push_back(Arg.get());
5986 }
5987 }
5988
5989 // Check for array bounds violations.
5990 for (Expr *A : Args.slice(ArgIx))
5991 CheckArrayAccess(A);
5992 }
5993 return Invalid;
5994}
5995
5997 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5998 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5999 TL = DTL.getOriginalLoc();
6000 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6001 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6002 << ATL.getLocalSourceRange();
6003}
6004
6005void
6007 ParmVarDecl *Param,
6008 const Expr *ArgExpr) {
6009 // Static array parameters are not supported in C++.
6010 if (!Param || getLangOpts().CPlusPlus)
6011 return;
6012
6013 QualType OrigTy = Param->getOriginalType();
6014
6015 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6016 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6017 return;
6018
6019 if (ArgExpr->isNullPointerConstant(Context,
6021 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6022 DiagnoseCalleeStaticArrayParam(*this, Param);
6023 return;
6024 }
6025
6026 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6027 if (!CAT)
6028 return;
6029
6030 const ConstantArrayType *ArgCAT =
6032 if (!ArgCAT)
6033 return;
6034
6035 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6036 ArgCAT->getElementType())) {
6037 if (ArgCAT->getSize().ult(CAT->getSize())) {
6038 Diag(CallLoc, diag::warn_static_array_too_small)
6039 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6040 << (unsigned)CAT->getZExtSize() << 0;
6041 DiagnoseCalleeStaticArrayParam(*this, Param);
6042 }
6043 return;
6044 }
6045
6046 std::optional<CharUnits> ArgSize =
6048 std::optional<CharUnits> ParmSize =
6050 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6051 Diag(CallLoc, diag::warn_static_array_too_small)
6052 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6053 << (unsigned)ParmSize->getQuantity() << 1;
6054 DiagnoseCalleeStaticArrayParam(*this, Param);
6055 }
6056}
6057
6058/// Given a function expression of unknown-any type, try to rebuild it
6059/// to have a function type.
6061
6062/// Is the given type a placeholder that we need to lower out
6063/// immediately during argument processing?
6065 // Placeholders are never sugared.
6066 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6067 if (!placeholder) return false;
6068
6069 switch (placeholder->getKind()) {
6070 // Ignore all the non-placeholder types.
6071#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6072 case BuiltinType::Id:
6073#include "clang/Basic/OpenCLImageTypes.def"
6074#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6075 case BuiltinType::Id:
6076#include "clang/Basic/OpenCLExtensionTypes.def"
6077 // In practice we'll never use this, since all SVE types are sugared
6078 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6079#define SVE_TYPE(Name, Id, SingletonId) \
6080 case BuiltinType::Id:
6081#include "clang/Basic/AArch64SVEACLETypes.def"
6082#define PPC_VECTOR_TYPE(Name, Id, Size) \
6083 case BuiltinType::Id:
6084#include "clang/Basic/PPCTypes.def"
6085#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6086#include "clang/Basic/RISCVVTypes.def"
6087#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6088#include "clang/Basic/WebAssemblyReferenceTypes.def"
6089#define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6090#include "clang/Basic/AMDGPUTypes.def"
6091#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6092#include "clang/Basic/HLSLIntangibleTypes.def"
6093#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6094#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6095#include "clang/AST/BuiltinTypes.def"
6096 return false;
6097
6098 case BuiltinType::UnresolvedTemplate:
6099 // We cannot lower out overload sets; they might validly be resolved
6100 // by the call machinery.
6101 case BuiltinType::Overload:
6102 return false;
6103
6104 // Unbridged casts in ARC can be handled in some call positions and
6105 // should be left in place.
6106 case BuiltinType::ARCUnbridgedCast:
6107 return false;
6108
6109 // Pseudo-objects should be converted as soon as possible.
6110 case BuiltinType::PseudoObject:
6111 return true;
6112
6113 // The debugger mode could theoretically but currently does not try
6114 // to resolve unknown-typed arguments based on known parameter types.
6115 case BuiltinType::UnknownAny:
6116 return true;
6117
6118 // These are always invalid as call arguments and should be reported.
6119 case BuiltinType::BoundMember:
6120 case BuiltinType::BuiltinFn:
6121 case BuiltinType::IncompleteMatrixIdx:
6122 case BuiltinType::ArraySection:
6123 case BuiltinType::OMPArrayShaping:
6124 case BuiltinType::OMPIterator:
6125 return true;
6126
6127 }
6128 llvm_unreachable("bad builtin type kind");
6129}
6130
6132 // Apply this processing to all the arguments at once instead of
6133 // dying at the first failure.
6134 bool hasInvalid = false;
6135 for (size_t i = 0, e = args.size(); i != e; i++) {
6136 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6137 ExprResult result = CheckPlaceholderExpr(args[i]);
6138 if (result.isInvalid()) hasInvalid = true;
6139 else args[i] = result.get();
6140 }
6141 }
6142 return hasInvalid;
6143}
6144
6145/// If a builtin function has a pointer argument with no explicit address
6146/// space, then it should be able to accept a pointer to any address
6147/// space as input. In order to do this, we need to replace the
6148/// standard builtin declaration with one that uses the same address space
6149/// as the call.
6150///
6151/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6152/// it does not contain any pointer arguments without
6153/// an address space qualifer. Otherwise the rewritten
6154/// FunctionDecl is returned.
6155/// TODO: Handle pointer return types.
6157 FunctionDecl *FDecl,
6158 MultiExprArg ArgExprs) {
6159
6160 QualType DeclType = FDecl->getType();
6161 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6162
6163 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6164 ArgExprs.size() < FT->getNumParams())
6165 return nullptr;
6166
6167 bool NeedsNewDecl = false;
6168 unsigned i = 0;
6169 SmallVector<QualType, 8> OverloadParams;
6170
6171 for (QualType ParamType : FT->param_types()) {
6172
6173 // Convert array arguments to pointer to simplify type lookup.
6174 ExprResult ArgRes =
6176 if (ArgRes.isInvalid())
6177 return nullptr;
6178 Expr *Arg = ArgRes.get();
6179 QualType ArgType = Arg->getType();
6180 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6181 !ArgType->isPointerType() ||
6182 !ArgType->getPointeeType().hasAddressSpace() ||
6184 OverloadParams.push_back(ParamType);
6185 continue;
6186 }
6187
6188 QualType PointeeType = ParamType->getPointeeType();
6189 if (PointeeType.hasAddressSpace())
6190 continue;
6191
6192 NeedsNewDecl = true;
6193 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6194
6195 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6196 OverloadParams.push_back(Context.getPointerType(PointeeType));
6197 }
6198
6199 if (!NeedsNewDecl)
6200 return nullptr;
6201
6203 EPI.Variadic = FT->isVariadic();
6204 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6205 OverloadParams, EPI);
6206 DeclContext *Parent = FDecl->getParent();
6207 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6208 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6209 FDecl->getIdentifier(), OverloadTy,
6210 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6211 false,
6212 /*hasPrototype=*/true);
6214 FT = cast<FunctionProtoType>(OverloadTy);
6215 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6216 QualType ParamType = FT->getParamType(i);
6217 ParmVarDecl *Parm =
6218 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6219 SourceLocation(), nullptr, ParamType,
6220 /*TInfo=*/nullptr, SC_None, nullptr);
6221 Parm->setScopeInfo(0, i);
6222 Params.push_back(Parm);
6223 }
6224 OverloadDecl->setParams(Params);
6225 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6226 return OverloadDecl;
6227}
6228
6229static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6230 FunctionDecl *Callee,
6231 MultiExprArg ArgExprs) {
6232 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6233 // similar attributes) really don't like it when functions are called with an
6234 // invalid number of args.
6235 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6236 /*PartialOverloading=*/false) &&
6237 !Callee->isVariadic())
6238 return;
6239 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6240 return;
6241
6242 if (const EnableIfAttr *Attr =
6243 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6244 S.Diag(Fn->getBeginLoc(),
6245 isa<CXXMethodDecl>(Callee)
6246 ? diag::err_ovl_no_viable_member_function_in_call
6247 : diag::err_ovl_no_viable_function_in_call)
6248 << Callee << Callee->getSourceRange();
6249 S.Diag(Callee->getLocation(),
6250 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6251 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6252 return;
6253 }
6254}
6255
6257 const UnresolvedMemberExpr *const UME, Sema &S) {
6258
6259 const auto GetFunctionLevelDCIfCXXClass =
6260 [](Sema &S) -> const CXXRecordDecl * {
6261 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6262 if (!DC || !DC->getParent())
6263 return nullptr;
6264
6265 // If the call to some member function was made from within a member
6266 // function body 'M' return return 'M's parent.
6267 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6268 return MD->getParent()->getCanonicalDecl();
6269 // else the call was made from within a default member initializer of a
6270 // class, so return the class.
6271 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6272 return RD->getCanonicalDecl();
6273 return nullptr;
6274 };
6275 // If our DeclContext is neither a member function nor a class (in the
6276 // case of a lambda in a default member initializer), we can't have an
6277 // enclosing 'this'.
6278
6279 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6280 if (!CurParentClass)
6281 return false;
6282
6283 // The naming class for implicit member functions call is the class in which
6284 // name lookup starts.
6285 const CXXRecordDecl *const NamingClass =
6287 assert(NamingClass && "Must have naming class even for implicit access");
6288
6289 // If the unresolved member functions were found in a 'naming class' that is
6290 // related (either the same or derived from) to the class that contains the
6291 // member function that itself contained the implicit member access.
6292
6293 return CurParentClass == NamingClass ||
6294 CurParentClass->isDerivedFrom(NamingClass);
6295}
6296
6297static void
6299 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6300
6301 if (!UME)
6302 return;
6303
6304 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6305 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6306 // already been captured, or if this is an implicit member function call (if
6307 // it isn't, an attempt to capture 'this' should already have been made).
6308 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6309 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6310 return;
6311
6312 // Check if the naming class in which the unresolved members were found is
6313 // related (same as or is a base of) to the enclosing class.
6314
6316 return;
6317
6318
6319 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6320 // If the enclosing function is not dependent, then this lambda is
6321 // capture ready, so if we can capture this, do so.
6322 if (!EnclosingFunctionCtx->isDependentContext()) {
6323 // If the current lambda and all enclosing lambdas can capture 'this' -
6324 // then go ahead and capture 'this' (since our unresolved overload set
6325 // contains at least one non-static member function).
6326 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6327 S.CheckCXXThisCapture(CallLoc);
6328 } else if (S.CurContext->isDependentContext()) {
6329 // ... since this is an implicit member reference, that might potentially
6330 // involve a 'this' capture, mark 'this' for potential capture in
6331 // enclosing lambdas.
6332 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6333 CurLSI->addPotentialThisCapture(CallLoc);
6334 }
6335}
6336
6337// Once a call is fully resolved, warn for unqualified calls to specific
6338// C++ standard functions, like move and forward.
6340 const CallExpr *Call) {
6341 // We are only checking unary move and forward so exit early here.
6342 if (Call->getNumArgs() != 1)
6343 return;
6344
6345 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6346 if (!E || isa<UnresolvedLookupExpr>(E))
6347 return;
6348 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6349 if (!DRE || !DRE->getLocation().isValid())
6350 return;
6351
6352 if (DRE->getQualifier())
6353 return;
6354
6355 const FunctionDecl *FD = Call->getDirectCallee();
6356 if (!FD)
6357 return;
6358
6359 // Only warn for some functions deemed more frequent or problematic.
6360 unsigned BuiltinID = FD->getBuiltinID();
6361 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6362 return;
6363
6364 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6366 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6367}
6368
6370 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6371 Expr *ExecConfig) {
6373 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6374 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6375 if (Call.isInvalid())
6376 return Call;
6377
6378 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6379 // language modes.
6380 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6381 ULE && ULE->hasExplicitTemplateArgs() &&
6382 ULE->decls_begin() == ULE->decls_end()) {
6383 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6384 ? diag::warn_cxx17_compat_adl_only_template_id
6385 : diag::ext_adl_only_template_id)
6386 << ULE->getName();
6387 }
6388
6389 if (LangOpts.OpenMP)
6390 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6391 ExecConfig);
6392 if (LangOpts.CPlusPlus) {
6393 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6395
6396 // If we previously found that the id-expression of this call refers to a
6397 // consteval function but the call is dependent, we should not treat is an
6398 // an invalid immediate call.
6399 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6400 DRE && Call.get()->isValueDependent()) {
6402 }
6403 }
6404 return Call;
6405}
6406
6408 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6409 Expr *ExecConfig, bool IsExecConfig,
6410 bool AllowRecovery) {
6411 // Since this might be a postfix expression, get rid of ParenListExprs.
6413 if (Result.isInvalid()) return ExprError();
6414 Fn = Result.get();
6415
6416 if (CheckArgsForPlaceholders(ArgExprs))
6417 return ExprError();
6418
6419 if (getLangOpts().CPlusPlus) {
6420 // If this is a pseudo-destructor expression, build the call immediately.
6421 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6422 if (!ArgExprs.empty()) {
6423 // Pseudo-destructor calls should not have any arguments.
6424 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6426 SourceRange(ArgExprs.front()->getBeginLoc(),
6427 ArgExprs.back()->getEndLoc()));
6428 }
6429
6430 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6431 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6432 }
6433 if (Fn->getType() == Context.PseudoObjectTy) {
6434 ExprResult result = CheckPlaceholderExpr(Fn);
6435 if (result.isInvalid()) return ExprError();
6436 Fn = result.get();
6437 }
6438
6439 // Determine whether this is a dependent call inside a C++ template,
6440 // in which case we won't do any semantic analysis now.
6441 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6442 if (ExecConfig) {
6444 cast<CallExpr>(ExecConfig), ArgExprs,
6446 RParenLoc, CurFPFeatureOverrides());
6447 } else {
6448
6450 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6451 Fn->getBeginLoc());
6452
6453 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6454 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6455 }
6456 }
6457
6458 // Determine whether this is a call to an object (C++ [over.call.object]).
6459 if (Fn->getType()->isRecordType())
6460 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6461 RParenLoc);
6462
6463 if (Fn->getType() == Context.UnknownAnyTy) {
6464 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6465 if (result.isInvalid()) return ExprError();
6466 Fn = result.get();
6467 }
6468
6469 if (Fn->getType() == Context.BoundMemberTy) {
6470 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6471 RParenLoc, ExecConfig, IsExecConfig,
6472 AllowRecovery);
6473 }
6474 }
6475
6476 // Check for overloaded calls. This can happen even in C due to extensions.
6477 if (Fn->getType() == Context.OverloadTy) {
6479
6480 // We aren't supposed to apply this logic if there's an '&' involved.
6483 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6484 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6485 OverloadExpr *ovl = find.Expression;
6486 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6488 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6489 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6490 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6491 RParenLoc, ExecConfig, IsExecConfig,
6492 AllowRecovery);
6493 }
6494 }
6495
6496 // If we're directly calling a function, get the appropriate declaration.
6497 if (Fn->getType() == Context.UnknownAnyTy) {
6498 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6499 if (result.isInvalid()) return ExprError();
6500 Fn = result.get();
6501 }
6502
6503 Expr *NakedFn = Fn->IgnoreParens();
6504
6505 bool CallingNDeclIndirectly = false;
6506 NamedDecl *NDecl = nullptr;
6507 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6508 if (UnOp->getOpcode() == UO_AddrOf) {
6509 CallingNDeclIndirectly = true;
6510 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6511 }
6512 }
6513
6514 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6515 NDecl = DRE->getDecl();
6516
6517 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6518 if (FDecl && FDecl->getBuiltinID()) {
6519 // Rewrite the function decl for this builtin by replacing parameters
6520 // with no explicit address space with the address space of the arguments
6521 // in ArgExprs.
6522 if ((FDecl =
6523 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6524 NDecl = FDecl;
6526 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6527 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6528 nullptr, DRE->isNonOdrUse());
6529 }
6530 }
6531 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6532 NDecl = ME->getMemberDecl();
6533
6534 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6535 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6536 FD, /*Complain=*/true, Fn->getBeginLoc()))
6537 return ExprError();
6538
6539 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6540
6541 // If this expression is a call to a builtin function in HIP device
6542 // compilation, allow a pointer-type argument to default address space to be
6543 // passed as a pointer-type parameter to a non-default address space.
6544 // If Arg is declared in the default address space and Param is declared
6545 // in a non-default address space, perform an implicit address space cast to
6546 // the parameter type.
6547 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6548 FD->getBuiltinID()) {
6549 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6550 ++Idx) {
6551 ParmVarDecl *Param = FD->getParamDecl(Idx);
6552 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6553 !ArgExprs[Idx]->getType()->isPointerType())
6554 continue;
6555
6556 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6557 auto ArgTy = ArgExprs[Idx]->getType();
6558 auto ArgPtTy = ArgTy->getPointeeType();
6559 auto ArgAS = ArgPtTy.getAddressSpace();
6560
6561 // Add address space cast if target address spaces are different
6562 bool NeedImplicitASC =
6563 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6564 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6565 // or from specific AS which has target AS matching that of Param.
6567 if (!NeedImplicitASC)
6568 continue;
6569
6570 // First, ensure that the Arg is an RValue.
6571 if (ArgExprs[Idx]->isGLValue()) {
6572 ArgExprs[Idx] = ImplicitCastExpr::Create(
6573 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6574 nullptr, VK_PRValue, FPOptionsOverride());
6575 }
6576
6577 // Construct a new arg type with address space of Param
6578 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6579 ArgPtQuals.setAddressSpace(ParamAS);
6580 auto NewArgPtTy =
6581 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6582 auto NewArgTy =
6584 ArgTy.getQualifiers());
6585
6586 // Finally perform an implicit address space cast
6587 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6588 CK_AddressSpaceConversion)
6589 .get();
6590 }
6591 }
6592 }
6593
6595 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6596 assert(!getLangOpts().CPlusPlus);
6597 assert((Fn->containsErrors() ||
6598 llvm::any_of(ArgExprs,
6599 [](clang::Expr *E) { return E->containsErrors(); })) &&
6600 "should only occur in error-recovery path.");
6601 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6602 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6603 }
6604 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6605 ExecConfig, IsExecConfig);
6606}
6607
6609 MultiExprArg CallArgs) {
6610 StringRef Name = Context.BuiltinInfo.getName(Id);
6611 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6613 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6614
6615 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6616 assert(BuiltInDecl && "failed to find builtin declaration");
6617
6618 ExprResult DeclRef =
6619 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6620 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6621
6623 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6624
6625 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6626 return Call.get();
6627}
6628
6630 SourceLocation BuiltinLoc,
6631 SourceLocation RParenLoc) {
6632 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6633 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6634}
6635
6637 SourceLocation BuiltinLoc,
6638 SourceLocation RParenLoc) {
6641 QualType SrcTy = E->getType();
6642 if (!SrcTy->isDependentType() &&
6643 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6644 return ExprError(
6645 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6646 << DestTy << SrcTy << E->getSourceRange());
6647 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6648}
6649
6651 SourceLocation BuiltinLoc,
6652 SourceLocation RParenLoc) {
6653 TypeSourceInfo *TInfo;
6654 GetTypeFromParser(ParsedDestTy, &TInfo);
6655 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6656}
6657
6659 SourceLocation LParenLoc,
6660 ArrayRef<Expr *> Args,
6661 SourceLocation RParenLoc, Expr *Config,
6662 bool IsExecConfig, ADLCallKind UsesADL) {
6663 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6664 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6665
6666 // Functions with 'interrupt' attribute cannot be called directly.
6667 if (FDecl) {
6668 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
6669 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6670 return ExprError();
6671 }
6672 if (FDecl->hasAttr<ARMInterruptAttr>()) {
6673 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
6674 return ExprError();
6675 }
6676 }
6677
6678 // X86 interrupt handlers may only call routines with attribute
6679 // no_caller_saved_registers since there is no efficient way to
6680 // save and restore the non-GPR state.
6681 if (auto *Caller = getCurFunctionDecl()) {
6682 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6683 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6684 const TargetInfo &TI = Context.getTargetInfo();
6685 bool HasNonGPRRegisters =
6686 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6687 if (HasNonGPRRegisters &&
6688 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6689 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6690 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6691 if (FDecl)
6692 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6693 }
6694 }
6695 }
6696
6697 // Promote the function operand.
6698 // We special-case function promotion here because we only allow promoting
6699 // builtin functions to function pointers in the callee of a call.
6701 QualType ResultTy;
6702 if (BuiltinID &&
6703 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6704 // Extract the return type from the (builtin) function pointer type.
6705 // FIXME Several builtins still have setType in
6706 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6707 // Builtins.td to ensure they are correct before removing setType calls.
6708 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6709 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6710 ResultTy = FDecl->getCallResultType();
6711 } else {
6713 ResultTy = Context.BoolTy;
6714 }
6715 if (Result.isInvalid())
6716 return ExprError();
6717 Fn = Result.get();
6718
6719 // Check for a valid function type, but only if it is not a builtin which
6720 // requires custom type checking. These will be handled by
6721 // CheckBuiltinFunctionCall below just after creation of the call expression.
6722 const FunctionType *FuncT = nullptr;
6723 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6724 retry:
6725 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6726 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6727 // have type pointer to function".
6728 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6729 if (!FuncT)
6730 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6731 << Fn->getType() << Fn->getSourceRange());
6732 } else if (const BlockPointerType *BPT =
6733 Fn->getType()->getAs<BlockPointerType>()) {
6734 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6735 } else {
6736 // Handle calls to expressions of unknown-any type.
6737 if (Fn->getType() == Context.UnknownAnyTy) {
6738 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6739 if (rewrite.isInvalid())
6740 return ExprError();
6741 Fn = rewrite.get();
6742 goto retry;
6743 }
6744
6745 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6746 << Fn->getType() << Fn->getSourceRange());
6747 }
6748 }
6749
6750 // Get the number of parameters in the function prototype, if any.
6751 // We will allocate space for max(Args.size(), NumParams) arguments
6752 // in the call expression.
6753 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6754 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6755
6756 CallExpr *TheCall;
6757 if (Config) {
6758 assert(UsesADL == ADLCallKind::NotADL &&
6759 "CUDAKernelCallExpr should not use ADL");
6760 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6761 Args, ResultTy, VK_PRValue, RParenLoc,
6762 CurFPFeatureOverrides(), NumParams);
6763 } else {
6764 TheCall =
6765 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6766 CurFPFeatureOverrides(), NumParams, UsesADL);
6767 }
6768
6770 // Forget about the nulled arguments since typo correction
6771 // do not handle them well.
6772 TheCall->shrinkNumArgs(Args.size());
6773 // C cannot always handle TypoExpr nodes in builtin calls and direct
6774 // function calls as their argument checking don't necessarily handle
6775 // dependent types properly, so make sure any TypoExprs have been
6776 // dealt with.
6778 if (!Result.isUsable()) return ExprError();
6779 CallExpr *TheOldCall = TheCall;
6780 TheCall = dyn_cast<CallExpr>(Result.get());
6781 bool CorrectedTypos = TheCall != TheOldCall;
6782 if (!TheCall) return Result;
6783 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6784
6785 // A new call expression node was created if some typos were corrected.
6786 // However it may not have been constructed with enough storage. In this
6787 // case, rebuild the node with enough storage. The waste of space is
6788 // immaterial since this only happens when some typos were corrected.
6789 if (CorrectedTypos && Args.size() < NumParams) {
6790 if (Config)
6792 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6793 RParenLoc, CurFPFeatureOverrides(), NumParams);
6794 else
6795 TheCall =
6796 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6797 CurFPFeatureOverrides(), NumParams, UsesADL);
6798 }
6799 // We can now handle the nulled arguments for the default arguments.
6800 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6801 }
6802
6803 // Bail out early if calling a builtin with custom type checking.
6804 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6805 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6806 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
6808 return E;
6809 }
6810
6811 if (getLangOpts().CUDA) {
6812 if (Config) {
6813 // CUDA: Kernel calls must be to global functions
6814 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6815 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6816 << FDecl << Fn->getSourceRange());
6817
6818 // CUDA: Kernel function must have 'void' return type
6819 if (!FuncT->getReturnType()->isVoidType() &&
6820 !FuncT->getReturnType()->getAs<AutoType>() &&
6822 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6823 << Fn->getType() << Fn->getSourceRange());
6824 } else {
6825 // CUDA: Calls to global functions must be configured
6826 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6827 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6828 << FDecl << Fn->getSourceRange());
6829 }
6830 }
6831
6832 // Check for a valid return type
6833 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6834 FDecl))
6835 return ExprError();
6836
6837 // We know the result type of the call, set it.
6838 TheCall->setType(FuncT->getCallResultType(Context));
6840
6841 // WebAssembly tables can't be used as arguments.
6842 if (Context.getTargetInfo().getTriple().isWasm()) {
6843 for (const Expr *Arg : Args) {
6844 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
6845 return ExprError(Diag(Arg->getExprLoc(),
6846 diag::err_wasm_table_as_function_parameter));
6847 }
6848 }
6849 }
6850
6851 if (Proto) {
6852 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6853 IsExecConfig))
6854 return ExprError();
6855 } else {
6856 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6857
6858 if (FDecl) {
6859 // Check if we have too few/too many template arguments, based
6860 // on our knowledge of the function definition.
6861 const FunctionDecl *Def = nullptr;
6862 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6863 Proto = Def->getType()->getAs<FunctionProtoType>();
6864 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6865 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6866 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6867 }
6868
6869 // If the function we're calling isn't a function prototype, but we have
6870 // a function prototype from a prior declaratiom, use that prototype.
6871 if (!FDecl->hasPrototype())
6872 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6873 }
6874
6875 // If we still haven't found a prototype to use but there are arguments to
6876 // the call, diagnose this as calling a function without a prototype.
6877 // However, if we found a function declaration, check to see if
6878 // -Wdeprecated-non-prototype was disabled where the function was declared.
6879 // If so, we will silence the diagnostic here on the assumption that this
6880 // interface is intentional and the user knows what they're doing. We will
6881 // also silence the diagnostic if there is a function declaration but it
6882 // was implicitly defined (the user already gets diagnostics about the
6883 // creation of the implicit function declaration, so the additional warning
6884 // is not helpful).
6885 if (!Proto && !Args.empty() &&
6886 (!FDecl || (!FDecl->isImplicit() &&
6887 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
6888 FDecl->getLocation()))))
6889 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
6890 << (FDecl != nullptr) << FDecl;
6891
6892 // Promote the arguments (C99 6.5.2.2p6).
6893 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6894 Expr *Arg = Args[i];
6895
6896 if (Proto && i < Proto->getNumParams()) {
6898 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6899 ExprResult ArgE =
6901 if (ArgE.isInvalid())
6902 return true;
6903
6904 Arg = ArgE.getAs<Expr>();
6905
6906 } else {
6908
6909 if (ArgE.isInvalid())
6910 return true;
6911
6912 Arg = ArgE.getAs<Expr>();
6913 }
6914
6915 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6916 diag::err_call_incomplete_argument, Arg))
6917 return ExprError();
6918
6919 TheCall->setArg(i, Arg);
6920 }
6921 TheCall->computeDependence();
6922 }
6923
6924 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6925 if (!isa<RequiresExprBodyDecl>(CurContext) &&
6926 Method->isImplicitObjectMemberFunction())
6927 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6928 << Fn->getSourceRange() << 0);
6929
6930 // Check for sentinels
6931 if (NDecl)
6932 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6933
6934 // Warn for unions passing across security boundary (CMSE).
6935 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6936 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6937 if (const auto *RT =
6938 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6939 if (RT->getDecl()->isOrContainsUnion())
6940 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6941 << 0 << i;
6942 }
6943 }
6944 }
6945
6946 // Do special checking on direct calls to functions.
6947 if (FDecl) {
6948 if (CheckFunctionCall(FDecl, TheCall, Proto))
6949 return ExprError();
6950
6951 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6952
6953 if (BuiltinID)
6954 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6955 } else if (NDecl) {
6956 if (CheckPointerCall(NDecl, TheCall, Proto))
6957 return ExprError();
6958 } else {
6959 if (CheckOtherCall(TheCall, Proto))
6960 return ExprError();
6961 }
6962
6963 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6964}
6965
6968 SourceLocation RParenLoc, Expr *InitExpr) {
6969 assert(Ty && "ActOnCompoundLiteral(): missing type");
6970 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6971
6972 TypeSourceInfo *TInfo;
6973 QualType literalType = GetTypeFromParser(Ty, &TInfo);
6974 if (!TInfo)
6975 TInfo = Context.getTrivialTypeSourceInfo(literalType);
6976
6977 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6978}
6979
6982 SourceLocation RParenLoc, Expr *LiteralExpr) {
6983 QualType literalType = TInfo->getType();
6984
6985 if (literalType->isArrayType()) {
6987 LParenLoc, Context.getBaseElementType(literalType),
6988 diag::err_array_incomplete_or_sizeless_type,
6989 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6990 return ExprError();
6991 if (literalType->isVariableArrayType()) {
6992 // C23 6.7.10p4: An entity of variable length array type shall not be
6993 // initialized except by an empty initializer.
6994 //
6995 // The C extension warnings are issued from ParseBraceInitializer() and
6996 // do not need to be issued here. However, we continue to issue an error
6997 // in the case there are initializers or we are compiling C++. We allow
6998 // use of VLAs in C++, but it's not clear we want to allow {} to zero
6999 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7000 // FIXME: should we allow this construct in C++ when it makes sense to do
7001 // so?
7002 //
7003 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7004 // shall specify an object type or an array of unknown size, but not a
7005 // variable length array type. This seems odd, as it allows 'int a[size] =
7006 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7007 // says, this is what's implemented here for C (except for the extension
7008 // that permits constant foldable size arrays)
7009
7010 auto diagID = LangOpts.CPlusPlus
7011 ? diag::err_variable_object_no_init
7012 : diag::err_compound_literal_with_vla_type;
7013 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7014 diagID))
7015 return ExprError();
7016 }
7017 } else if (!literalType->isDependentType() &&
7018 RequireCompleteType(LParenLoc, literalType,
7019 diag::err_typecheck_decl_incomplete_type,
7020 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7021 return ExprError();
7022
7023 InitializedEntity Entity
7027 SourceRange(LParenLoc, RParenLoc),
7028 /*InitList=*/true);
7029 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7030 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7031 &literalType);
7032 if (Result.isInvalid())
7033 return ExprError();
7034 LiteralExpr = Result.get();
7035
7036 bool isFileScope = !CurContext->isFunctionOrMethod();
7037
7038 // In C, compound literals are l-values for some reason.
7039 // For GCC compatibility, in C++, file-scope array compound literals with
7040 // constant initializers are also l-values, and compound literals are
7041 // otherwise prvalues.
7042 //
7043 // (GCC also treats C++ list-initialized file-scope array prvalues with
7044 // constant initializers as l-values, but that's non-conforming, so we don't
7045 // follow it there.)
7046 //
7047 // FIXME: It would be better to handle the lvalue cases as materializing and
7048 // lifetime-extending a temporary object, but our materialized temporaries
7049 // representation only supports lifetime extension from a variable, not "out
7050 // of thin air".
7051 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7052 // is bound to the result of applying array-to-pointer decay to the compound
7053 // literal.
7054 // FIXME: GCC supports compound literals of reference type, which should
7055 // obviously have a value kind derived from the kind of reference involved.
7056 ExprValueKind VK =
7057 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7058 ? VK_PRValue
7059 : VK_LValue;
7060
7061 if (isFileScope)
7062 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7063 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7064 Expr *Init = ILE->getInit(i);
7065 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7066 }
7067
7068 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7069 VK, LiteralExpr, isFileScope);
7070 if (isFileScope) {
7071 if (!LiteralExpr->isTypeDependent() &&
7072 !LiteralExpr->isValueDependent() &&
7073 !literalType->isDependentType()) // C99 6.5.2.5p3
7074 if (CheckForConstantInitializer(LiteralExpr))
7075 return ExprError();
7076 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7077 literalType.getAddressSpace() != LangAS::Default) {
7078 // Embedded-C extensions to C99 6.5.2.5:
7079 // "If the compound literal occurs inside the body of a function, the
7080 // type name shall not be qualified by an address-space qualifier."
7081 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7082 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7083 return ExprError();
7084 }
7085
7086 if (!isFileScope && !getLangOpts().CPlusPlus) {
7087 // Compound literals that have automatic storage duration are destroyed at
7088 // the end of the scope in C; in C++, they're just temporaries.
7089
7090 // Emit diagnostics if it is or contains a C union type that is non-trivial
7091 // to destruct.
7095
7096 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7097 if (literalType.isDestructedType()) {
7099 ExprCleanupObjects.push_back(E);
7101 }
7102 }
7103
7106 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7107 E->getInitializer()->getExprLoc());
7108
7109 return MaybeBindToTemporary(E);
7110}
7111
7114 SourceLocation RBraceLoc) {
7115 // Only produce each kind of designated initialization diagnostic once.
7116 SourceLocation FirstDesignator;
7117 bool DiagnosedArrayDesignator = false;
7118 bool DiagnosedNestedDesignator = false;
7119 bool DiagnosedMixedDesignator = false;
7120
7121 // Check that any designated initializers are syntactically valid in the
7122 // current language mode.
7123 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7124 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7125 if (FirstDesignator.isInvalid())
7126 FirstDesignator = DIE->getBeginLoc();
7127
7128 if (!getLangOpts().CPlusPlus)
7129 break;
7130
7131 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7132 DiagnosedNestedDesignator = true;
7133 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7134 << DIE->getDesignatorsSourceRange();
7135 }
7136
7137 for (auto &Desig : DIE->designators()) {
7138 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7139 DiagnosedArrayDesignator = true;
7140 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7141 << Desig.getSourceRange();
7142 }
7143 }
7144
7145 if (!DiagnosedMixedDesignator &&
7146 !isa<DesignatedInitExpr>(InitArgList[0])) {
7147 DiagnosedMixedDesignator = true;
7148 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7149 << DIE->getSourceRange();
7150 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7151 << InitArgList[0]->getSourceRange();
7152 }
7153 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7154 isa<DesignatedInitExpr>(InitArgList[0])) {
7155 DiagnosedMixedDesignator = true;
7156 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7157 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7158 << DIE->getSourceRange();
7159 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7160 << InitArgList[I]->getSourceRange();
7161 }
7162 }
7163
7164 if (FirstDesignator.isValid()) {
7165 // Only diagnose designated initiaization as a C++20 extension if we didn't
7166 // already diagnose use of (non-C++20) C99 designator syntax.
7167 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7168 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7169 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7170 ? diag::warn_cxx17_compat_designated_init
7171 : diag::ext_cxx_designated_init);
7172 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7173 Diag(FirstDesignator, diag::ext_designated_init);
7174 }
7175 }
7176
7177 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7178}
7179
7182 SourceLocation RBraceLoc) {
7183 // Semantic analysis for initializers is done by ActOnDeclarator() and
7184 // CheckInitializer() - it requires knowledge of the object being initialized.
7185
7186 // Immediately handle non-overload placeholders. Overloads can be
7187 // resolved contextually, but everything else here can't.
7188 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7189 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7190 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7191
7192 // Ignore failures; dropping the entire initializer list because
7193 // of one failure would be terrible for indexing/etc.
7194 if (result.isInvalid()) continue;
7195
7196 InitArgList[I] = result.get();
7197 }
7198 }
7199
7200 InitListExpr *E =
7201 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7202 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7203 return E;
7204}
7205
7207 assert(E.get()->getType()->isBlockPointerType());
7208 assert(E.get()->isPRValue());
7209
7210 // Only do this in an r-value context.
7211 if (!getLangOpts().ObjCAutoRefCount) return;
7212
7214 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7215 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7217}
7218
7220 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7221 // Also, callers should have filtered out the invalid cases with
7222 // pointers. Everything else should be possible.
7223
7224 QualType SrcTy = Src.get()->getType();
7225 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7226 return CK_NoOp;
7227
7228 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7230 llvm_unreachable("member pointer type in C");
7231
7232 case Type::STK_CPointer:
7235 switch (DestTy->getScalarTypeKind()) {
7236 case Type::STK_CPointer: {
7237 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7238 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7239 if (SrcAS != DestAS)
7240 return CK_AddressSpaceConversion;
7241 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7242 return CK_NoOp;
7243 return CK_BitCast;
7244 }
7246 return (SrcKind == Type::STK_BlockPointer
7247 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7249 if (SrcKind == Type::STK_ObjCObjectPointer)
7250 return CK_BitCast;
7251 if (SrcKind == Type::STK_CPointer)
7252 return CK_CPointerToObjCPointerCast;
7254 return CK_BlockPointerToObjCPointerCast;
7255 case Type::STK_Bool:
7256 return CK_PointerToBoolean;
7257 case Type::STK_Integral:
7258 return CK_PointerToIntegral;
7259 case Type::STK_Floating:
7264 llvm_unreachable("illegal cast from pointer");
7265 }
7266 llvm_unreachable("Should have returned before this");
7267
7269 switch (DestTy->getScalarTypeKind()) {
7271 return CK_FixedPointCast;
7272 case Type::STK_Bool:
7273 return CK_FixedPointToBoolean;
7274 case Type::STK_Integral:
7275 return CK_FixedPointToIntegral;
7276 case Type::STK_Floating:
7277 return CK_FixedPointToFloating;
7280 Diag(Src.get()->getExprLoc(),
7281 diag::err_unimplemented_conversion_with_fixed_point_type)
7282 << DestTy;
7283 return CK_IntegralCast;
7284 case Type::STK_CPointer:
7288 llvm_unreachable("illegal cast to pointer type");
7289 }
7290 llvm_unreachable("Should have returned before this");
7291
7292 case Type::STK_Bool: // casting from bool is like casting from an integer
7293 case Type::STK_Integral:
7294 switch (DestTy->getScalarTypeKind()) {
7295 case Type::STK_CPointer:
7300 return CK_NullToPointer;
7301 return CK_IntegralToPointer;
7302 case Type::STK_Bool:
7303 return CK_IntegralToBoolean;
7304 case Type::STK_Integral:
7305 return CK_IntegralCast;
7306 case Type::STK_Floating:
7307 return CK_IntegralToFloating;
7309 Src = ImpCastExprToType(Src.get(),
7310 DestTy->castAs<ComplexType>()->getElementType(),
7311 CK_IntegralCast);
7312 return CK_IntegralRealToComplex;
7314 Src = ImpCastExprToType(Src.get(),
7315 DestTy->castAs<ComplexType>()->getElementType(),
7316 CK_IntegralToFloating);
7317 return CK_FloatingRealToComplex;
7319 llvm_unreachable("member pointer type in C");
7321 return CK_IntegralToFixedPoint;
7322 }
7323 llvm_unreachable("Should have returned before this");
7324
7325 case Type::STK_Floating:
7326 switch (DestTy->getScalarTypeKind()) {
7327 case Type::STK_Floating:
7328 return CK_FloatingCast;
7329 case Type::STK_Bool:
7330 return CK_FloatingToBoolean;
7331 case Type::STK_Integral:
7332 return CK_FloatingToIntegral;
7334 Src = ImpCastExprToType(Src.get(),
7335 DestTy->castAs<ComplexType>()->getElementType(),
7336 CK_FloatingCast);
7337 return CK_FloatingRealToComplex;
7339 Src = ImpCastExprToType(Src.get(),
7340 DestTy->castAs<ComplexType>()->getElementType(),
7341 CK_FloatingToIntegral);
7342 return CK_IntegralRealToComplex;
7343 case Type::STK_CPointer:
7346 llvm_unreachable("valid float->pointer cast?");
7348 llvm_unreachable("member pointer type in C");
7350 return CK_FloatingToFixedPoint;
7351 }
7352 llvm_unreachable("Should have returned before this");
7353
7355 switch (DestTy->getScalarTypeKind()) {
7357 return CK_FloatingComplexCast;
7359 return CK_FloatingComplexToIntegralComplex;
7360 case Type::STK_Floating: {
7361 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7362 if (Context.hasSameType(ET, DestTy))
7363 return CK_FloatingComplexToReal;
7364 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7365 return CK_FloatingCast;
7366 }
7367 case Type::STK_Bool:
7368 return CK_FloatingComplexToBoolean;
7369 case Type::STK_Integral:
7370 Src = ImpCastExprToType(Src.get(),
7371 SrcTy->castAs<ComplexType>()->getElementType(),
7372 CK_FloatingComplexToReal);
7373 return CK_FloatingToIntegral;
7374 case Type::STK_CPointer:
7377 llvm_unreachable("valid complex float->pointer cast?");
7379 llvm_unreachable("member pointer type in C");
7381 Diag(Src.get()->getExprLoc(),
7382 diag::err_unimplemented_conversion_with_fixed_point_type)
7383 << SrcTy;
7384 return CK_IntegralCast;
7385 }
7386 llvm_unreachable("Should have returned before this");
7387
7389 switch (DestTy->getScalarTypeKind()) {
7391 return CK_IntegralComplexToFloatingComplex;
7393 return CK_IntegralComplexCast;
7394 case Type::STK_Integral: {
7395 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7396 if (Context.hasSameType(ET, DestTy))
7397 return CK_IntegralComplexToReal;
7398 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7399 return CK_IntegralCast;
7400 }
7401 case Type::STK_Bool:
7402 return CK_IntegralComplexToBoolean;
7403 case Type::STK_Floating:
7404 Src = ImpCastExprToType(Src.get(),
7405 SrcTy->castAs<ComplexType>()->getElementType(),
7406 CK_IntegralComplexToReal);
7407 return CK_IntegralToFloating;
7408 case Type::STK_CPointer:
7411 llvm_unreachable("valid complex int->pointer cast?");
7413 llvm_unreachable("member pointer type in C");
7415 Diag(Src.get()->getExprLoc(),
7416 diag::err_unimplemented_conversion_with_fixed_point_type)
7417 << SrcTy;
7418 return CK_IntegralCast;
7419 }
7420 llvm_unreachable("Should have returned before this");
7421 }
7422
7423 llvm_unreachable("Unhandled scalar cast");
7424}
7425
7426static bool breakDownVectorType(QualType type, uint64_t &len,
7427 QualType &eltType) {
7428 // Vectors are simple.
7429 if (const VectorType *vecType = type->getAs<VectorType>()) {
7430 len = vecType->getNumElements();
7431 eltType = vecType->getElementType();
7432 assert(eltType->isScalarType());
7433 return true;
7434 }
7435
7436 // We allow lax conversion to and from non-vector types, but only if
7437 // they're real types (i.e. non-complex, non-pointer scalar types).
7438 if (!type->isRealType()) return false;
7439
7440 len = 1;
7441 eltType = type;
7442 return true;
7443}
7444
7446 assert(srcTy->isVectorType() || destTy->isVectorType());
7447
7448 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7449 if (!FirstType->isSVESizelessBuiltinType())
7450 return false;
7451
7452 const auto *VecTy = SecondType->getAs<VectorType>();
7453 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7454 };
7455
7456 return ValidScalableConversion(srcTy, destTy) ||
7457 ValidScalableConversion(destTy, srcTy);
7458}
7459
7461 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7462 return false;
7463
7464 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7465 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7466
7467 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7468 matSrcType->getNumColumns() == matDestType->getNumColumns();
7469}
7470
7472 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7473
7474 uint64_t SrcLen, DestLen;
7475 QualType SrcEltTy, DestEltTy;
7476 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7477 return false;
7478 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7479 return false;
7480
7481 // ASTContext::getTypeSize will return the size rounded up to a
7482 // power of 2, so instead of using that, we need to use the raw
7483 // element size multiplied by the element count.
7484 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7485 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7486
7487 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7488}
7489
7491 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7492 "expected at least one type to be a vector here");
7493
7494 bool IsSrcTyAltivec =
7495 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7497 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7499 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7501
7502 bool IsDestTyAltivec = DestTy->isVectorType() &&
7503 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7505 (DestTy->castAs<VectorType>()->getVectorKind() ==
7507 (DestTy->castAs<VectorType>()->getVectorKind() ==
7509
7510 return (IsSrcTyAltivec || IsDestTyAltivec);
7511}
7512
7514 assert(destTy->isVectorType() || srcTy->isVectorType());
7515
7516 // Disallow lax conversions between scalars and ExtVectors (these
7517 // conversions are allowed for other vector types because common headers
7518 // depend on them). Most scalar OP ExtVector cases are handled by the
7519 // splat path anyway, which does what we want (convert, not bitcast).
7520 // What this rules out for ExtVectors is crazy things like char4*float.
7521 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7522 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7523
7524 return areVectorTypesSameSize(srcTy, destTy);
7525}
7526
7528 assert(destTy->isVectorType() || srcTy->isVectorType());
7529
7530 switch (Context.getLangOpts().getLaxVectorConversions()) {
7532 return false;
7533
7535 if (!srcTy->isIntegralOrEnumerationType()) {
7536 auto *Vec = srcTy->getAs<VectorType>();
7537 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7538 return false;
7539 }
7540 if (!destTy->isIntegralOrEnumerationType()) {
7541 auto *Vec = destTy->getAs<VectorType>();
7542 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7543 return false;
7544 }
7545 // OK, integer (vector) -> integer (vector) bitcast.
7546 break;
7547
7549 break;
7550 }
7551
7552 return areLaxCompatibleVectorTypes(srcTy, destTy);
7553}
7554
7556 CastKind &Kind) {
7557 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7558 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7559 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7560 << DestTy << SrcTy << R;
7561 }
7562 } else if (SrcTy->isMatrixType()) {
7563 return Diag(R.getBegin(),
7564 diag::err_invalid_conversion_between_matrix_and_type)
7565 << SrcTy << DestTy << R;
7566 } else if (DestTy->isMatrixType()) {
7567 return Diag(R.getBegin(),
7568 diag::err_invalid_conversion_between_matrix_and_type)
7569 << DestTy << SrcTy << R;
7570 }
7571
7572 Kind = CK_MatrixCast;
7573 return false;
7574}
7575
7577 CastKind &Kind) {
7578 assert(VectorTy->isVectorType() && "Not a vector type!");
7579
7580 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7581 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7582 return Diag(R.getBegin(),
7583 Ty->isVectorType() ?
7584 diag::err_invalid_conversion_between_vectors :
7585 diag::err_invalid_conversion_between_vector_and_integer)
7586 << VectorTy << Ty << R;
7587 } else
7588 return Diag(R.getBegin(),
7589 diag::err_invalid_conversion_between_vector_and_scalar)
7590 << VectorTy << Ty << R;
7591
7592 Kind = CK_BitCast;
7593 return false;
7594}
7595
7597 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7598
7599 if (DestElemTy == SplattedExpr->getType())
7600 return SplattedExpr;
7601
7602 assert(DestElemTy->isFloatingType() ||
7603 DestElemTy->isIntegralOrEnumerationType());
7604
7605 CastKind CK;
7606 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7607 // OpenCL requires that we convert `true` boolean expressions to -1, but
7608 // only when splatting vectors.
7609 if (DestElemTy->isFloatingType()) {
7610 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7611 // in two steps: boolean to signed integral, then to floating.
7612 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7613 CK_BooleanToSignedIntegral);
7614 SplattedExpr = CastExprRes.get();
7615 CK = CK_IntegralToFloating;
7616 } else {
7617 CK = CK_BooleanToSignedIntegral;
7618 }
7619 } else {
7620 ExprResult CastExprRes = SplattedExpr;
7621 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7622 if (CastExprRes.isInvalid())
7623 return ExprError();
7624 SplattedExpr = CastExprRes.get();
7625 }
7626 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7627}
7628
7630 Expr *CastExpr, CastKind &Kind) {
7631 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7632
7633 QualType SrcTy = CastExpr->getType();
7634
7635 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7636 // an ExtVectorType.
7637 // In OpenCL, casts between vectors of different types are not allowed.
7638 // (See OpenCL 6.2).
7639 if (SrcTy->isVectorType()) {
7640 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7641 (getLangOpts().OpenCL &&
7642 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7643 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7644 << DestTy << SrcTy << R;
7645 return ExprError();
7646 }
7647 Kind = CK_BitCast;
7648 return CastExpr;
7649 }
7650
7651 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7652 // conversion will take place first from scalar to elt type, and then
7653 // splat from elt type to vector.
7654 if (SrcTy->isPointerType())
7655 return Diag(R.getBegin(),
7656 diag::err_invalid_conversion_between_vector_and_scalar)
7657 << DestTy << SrcTy << R;
7658
7659 Kind = CK_VectorSplat;
7660 return prepareVectorSplat(DestTy, CastExpr);
7661}
7662
7665 Declarator &D, ParsedType &Ty,
7666 SourceLocation RParenLoc, Expr *CastExpr) {
7667 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7668 "ActOnCastExpr(): missing type or expr");
7669
7671 if (D.isInvalidType())
7672 return ExprError();
7673
7674 if (getLangOpts().CPlusPlus) {
7675 // Check that there are no default arguments (C++ only).
7677 } else {
7678 // Make sure any TypoExprs have been dealt with.
7680 if (!Res.isUsable())
7681 return ExprError();
7682 CastExpr = Res.get();
7683 }
7684
7686
7687 QualType castType = castTInfo->getType();
7688 Ty = CreateParsedType(castType, castTInfo);
7689
7690 bool isVectorLiteral = false;
7691
7692 // Check for an altivec or OpenCL literal,
7693 // i.e. all the elements are integer constants.
7694 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7695 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7696 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7697 && castType->isVectorType() && (PE || PLE)) {
7698 if (PLE && PLE->getNumExprs() == 0) {
7699 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7700 return ExprError();
7701 }
7702 if (PE || PLE->getNumExprs() == 1) {
7703 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7704 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7705 isVectorLiteral = true;
7706 }
7707 else
7708 isVectorLiteral = true;
7709 }
7710
7711 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7712 // then handle it as such.
7713 if (isVectorLiteral)
7714 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7715
7716 // If the Expr being casted is a ParenListExpr, handle it specially.
7717 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7718 // sequence of BinOp comma operators.
7719 if (isa<ParenListExpr>(CastExpr)) {
7721 if (Result.isInvalid()) return ExprError();
7722 CastExpr = Result.get();
7723 }
7724
7725 if (getLangOpts().CPlusPlus && !castType->isVoidType())
7726 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7727
7729
7731
7733
7734 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7735}
7736
7738 SourceLocation RParenLoc, Expr *E,
7739 TypeSourceInfo *TInfo) {
7740 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7741 "Expected paren or paren list expression");
7742
7743 Expr **exprs;
7744 unsigned numExprs;
7745 Expr *subExpr;
7746 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7747 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7748 LiteralLParenLoc = PE->getLParenLoc();
7749 LiteralRParenLoc = PE->getRParenLoc();
7750 exprs = PE->getExprs();
7751 numExprs = PE->getNumExprs();
7752 } else { // isa<ParenExpr> by assertion at function entrance
7753 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7754 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7755 subExpr = cast<ParenExpr>(E)->getSubExpr();
7756 exprs = &subExpr;
7757 numExprs = 1;
7758 }
7759
7760 QualType Ty = TInfo->getType();
7761 assert(Ty->isVectorType() && "Expected vector type");
7762
7763 SmallVector<Expr *, 8> initExprs;
7764 const VectorType *VTy = Ty->castAs<VectorType>();
7765 unsigned numElems = VTy->getNumElements();
7766
7767 // '(...)' form of vector initialization in AltiVec: the number of
7768 // initializers must be one or must match the size of the vector.
7769 // If a single value is specified in the initializer then it will be
7770 // replicated to all the components of the vector
7772 VTy->getElementType()))
7773 return ExprError();
7775 // The number of initializers must be one or must match the size of the
7776 // vector. If a single value is specified in the initializer then it will
7777 // be replicated to all the components of the vector
7778 if (numExprs == 1) {
7779 QualType ElemTy = VTy->getElementType();
7780 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7781 if (Literal.isInvalid())
7782 return ExprError();
7783 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7784 PrepareScalarCast(Literal, ElemTy));
7785 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7786 }
7787 else if (numExprs < numElems) {
7788 Diag(E->getExprLoc(),
7789 diag::err_incorrect_number_of_vector_initializers);
7790 return ExprError();
7791 }
7792 else
7793 initExprs.append(exprs, exprs + numExprs);
7794 }
7795 else {
7796 // For OpenCL, when the number of initializers is a single value,
7797 // it will be replicated to all components of the vector.
7799 numExprs == 1) {
7800 QualType ElemTy = VTy->getElementType();
7801 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7802 if (Literal.isInvalid())
7803 return ExprError();
7804 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7805 PrepareScalarCast(Literal, ElemTy));
7806 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7807 }
7808
7809 initExprs.append(exprs, exprs + numExprs);
7810 }
7811 // FIXME: This means that pretty-printing the final AST will produce curly
7812 // braces instead of the original commas.
7813 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7814 initExprs, LiteralRParenLoc);
7815 initE->setType(Ty);
7816 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7817}
7818
7821 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7822 if (!E)
7823 return OrigExpr;
7824
7825 ExprResult Result(E->getExpr(0));
7826
7827 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7828 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7829 E->getExpr(i));
7830
7831 if (Result.isInvalid()) return ExprError();
7832
7833 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7834}
7835
7838 MultiExprArg Val) {
7839 return ParenListExpr::Create(Context, L, Val, R);
7840}
7841
7842bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7843 SourceLocation QuestionLoc) {
7844 const Expr *NullExpr = LHSExpr;
7845 const Expr *NonPointerExpr = RHSExpr;
7849
7850 if (NullKind == Expr::NPCK_NotNull) {
7851 NullExpr = RHSExpr;
7852 NonPointerExpr = LHSExpr;
7853 NullKind =
7856 }
7857
7858 if (NullKind == Expr::NPCK_NotNull)
7859 return false;
7860
7861 if (NullKind == Expr::NPCK_ZeroExpression)
7862 return false;
7863
7864 if (NullKind == Expr::NPCK_ZeroLiteral) {
7865 // In this case, check to make sure that we got here from a "NULL"
7866 // string in the source code.
7867 NullExpr = NullExpr->IgnoreParenImpCasts();
7868 SourceLocation loc = NullExpr->getExprLoc();
7869 if (!findMacroSpelling(loc, "NULL"))
7870 return false;
7871 }
7872
7873 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7874 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7875 << NonPointerExpr->getType() << DiagType
7876 << NonPointerExpr->getSourceRange();
7877 return true;
7878}
7879
7880/// Return false if the condition expression is valid, true otherwise.
7881static bool checkCondition(Sema &S, const Expr *Cond,
7882 SourceLocation QuestionLoc) {
7883 QualType CondTy = Cond->getType();
7884
7885 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7886 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7887 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7888 << CondTy << Cond->getSourceRange();
7889 return true;
7890 }
7891
7892 // C99 6.5.15p2
7893 if (CondTy->isScalarType()) return false;
7894
7895 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7896 << CondTy << Cond->getSourceRange();
7897 return true;
7898}
7899
7900/// Return false if the NullExpr can be promoted to PointerTy,
7901/// true otherwise.
7903 QualType PointerTy) {
7904 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7905 !NullExpr.get()->isNullPointerConstant(S.Context,
7907 return true;
7908
7909 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7910 return false;
7911}
7912
7913/// Checks compatibility between two pointers and return the resulting
7914/// type.
7916 ExprResult &RHS,
7918 QualType LHSTy = LHS.get()->getType();
7919 QualType RHSTy = RHS.get()->getType();
7920
7921 if (S.Context.hasSameType(LHSTy, RHSTy)) {
7922 // Two identical pointers types are always compatible.
7923 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
7924 }
7925
7926 QualType lhptee, rhptee;
7927
7928 // Get the pointee types.
7929 bool IsBlockPointer = false;
7930 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7931 lhptee = LHSBTy->getPointeeType();
7932 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7933 IsBlockPointer = true;
7934 } else {
7935 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7936 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7937 }
7938
7939 // C99 6.5.15p6: If both operands are pointers to compatible types or to
7940 // differently qualified versions of compatible types, the result type is
7941 // a pointer to an appropriately qualified version of the composite
7942 // type.
7943
7944 // Only CVR-qualifiers exist in the standard, and the differently-qualified
7945 // clause doesn't make sense for our extensions. E.g. address space 2 should
7946 // be incompatible with address space 3: they may live on different devices or
7947 // anything.
7948 Qualifiers lhQual = lhptee.getQualifiers();
7949 Qualifiers rhQual = rhptee.getQualifiers();
7950
7951 LangAS ResultAddrSpace = LangAS::Default;
7952 LangAS LAddrSpace = lhQual.getAddressSpace();
7953 LangAS RAddrSpace = rhQual.getAddressSpace();
7954
7955 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7956 // spaces is disallowed.
7957 if (lhQual.isAddressSpaceSupersetOf(rhQual))
7958 ResultAddrSpace = LAddrSpace;
7959 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7960 ResultAddrSpace = RAddrSpace;
7961 else {
7962 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7963 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7964 << RHS.get()->getSourceRange();
7965 return QualType();
7966 }
7967
7968 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7969 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7970 lhQual.removeCVRQualifiers();
7971 rhQual.removeCVRQualifiers();
7972
7973 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7974 // (C99 6.7.3) for address spaces. We assume that the check should behave in
7975 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7976 // qual types are compatible iff
7977 // * corresponded types are compatible
7978 // * CVR qualifiers are equal
7979 // * address spaces are equal
7980 // Thus for conditional operator we merge CVR and address space unqualified
7981 // pointees and if there is a composite type we return a pointer to it with
7982 // merged qualifiers.
7983 LHSCastKind =
7984 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7985 RHSCastKind =
7986 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7987 lhQual.removeAddressSpace();
7988 rhQual.removeAddressSpace();
7989
7990 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7991 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7992
7993 QualType CompositeTy = S.Context.mergeTypes(
7994 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
7995 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
7996
7997 if (CompositeTy.isNull()) {
7998 // In this situation, we assume void* type. No especially good
7999 // reason, but this is what gcc does, and we do have to pick
8000 // to get a consistent AST.
8001 QualType incompatTy;
8002 incompatTy = S.Context.getPointerType(
8003 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8004 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8005 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8006
8007 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8008 // for casts between types with incompatible address space qualifiers.
8009 // For the following code the compiler produces casts between global and
8010 // local address spaces of the corresponded innermost pointees:
8011 // local int *global *a;
8012 // global int *global *b;
8013 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8014 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8015 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8016 << RHS.get()->getSourceRange();
8017
8018 return incompatTy;
8019 }
8020
8021 // The pointer types are compatible.
8022 // In case of OpenCL ResultTy should have the address space qualifier
8023 // which is a superset of address spaces of both the 2nd and the 3rd
8024 // operands of the conditional operator.
8025 QualType ResultTy = [&, ResultAddrSpace]() {
8026 if (S.getLangOpts().OpenCL) {
8027 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8028 CompositeQuals.setAddressSpace(ResultAddrSpace);
8029 return S.Context
8030 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8031 .withCVRQualifiers(MergedCVRQual);
8032 }
8033 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8034 }();
8035 if (IsBlockPointer)
8036 ResultTy = S.Context.getBlockPointerType(ResultTy);
8037 else
8038 ResultTy = S.Context.getPointerType(ResultTy);
8039
8040 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8041 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8042 return ResultTy;
8043}
8044
8045/// Return the resulting type when the operands are both block pointers.
8047 ExprResult &LHS,
8048 ExprResult &RHS,
8050 QualType LHSTy = LHS.get()->getType();
8051 QualType RHSTy = RHS.get()->getType();
8052
8053 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8054 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8056 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8057 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8058 return destType;
8059 }
8060 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8061 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8062 << RHS.get()->getSourceRange();
8063 return QualType();
8064 }
8065
8066 // We have 2 block pointer types.
8067 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8068}
8069
8070/// Return the resulting type when the operands are both pointers.
8071static QualType
8073 ExprResult &RHS,
8075 // get the pointer types
8076 QualType LHSTy = LHS.get()->getType();
8077 QualType RHSTy = RHS.get()->getType();
8078
8079 // get the "pointed to" types
8080 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8081 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8082
8083 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8084 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8085 // Figure out necessary qualifiers (C99 6.5.15p6)
8086 QualType destPointee
8087 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8088 QualType destType = S.Context.getPointerType(destPointee);
8089 // Add qualifiers if necessary.
8090 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8091 // Promote to void*.
8092 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8093 return destType;
8094 }
8095 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8096 QualType destPointee
8097 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8098 QualType destType = S.Context.getPointerType(destPointee);
8099 // Add qualifiers if necessary.
8100 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8101 // Promote to void*.
8102 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8103 return destType;
8104 }
8105
8106 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8107}
8108
8109/// Return false if the first expression is not an integer and the second
8110/// expression is not a pointer, true otherwise.
8112 Expr* PointerExpr, SourceLocation Loc,
8113 bool IsIntFirstExpr) {
8114 if (!PointerExpr->getType()->isPointerType() ||
8115 !Int.get()->getType()->isIntegerType())
8116 return false;
8117
8118 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8119 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8120
8121 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8122 << Expr1->getType() << Expr2->getType()
8123 << Expr1->getSourceRange() << Expr2->getSourceRange();
8124 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8125 CK_IntegralToPointer);
8126 return true;
8127}
8128
8129/// Simple conversion between integer and floating point types.
8130///
8131/// Used when handling the OpenCL conditional operator where the
8132/// condition is a vector while the other operands are scalar.
8133///
8134/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8135/// types are either integer or floating type. Between the two
8136/// operands, the type with the higher rank is defined as the "result
8137/// type". The other operand needs to be promoted to the same type. No
8138/// other type promotion is allowed. We cannot use
8139/// UsualArithmeticConversions() for this purpose, since it always
8140/// promotes promotable types.
8142 ExprResult &RHS,
8143 SourceLocation QuestionLoc) {
8145 if (LHS.isInvalid())
8146 return QualType();
8148 if (RHS.isInvalid())
8149 return QualType();
8150
8151 // For conversion purposes, we ignore any qualifiers.
8152 // For example, "const float" and "float" are equivalent.
8153 QualType LHSType =
8155 QualType RHSType =
8157
8158 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8159 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8160 << LHSType << LHS.get()->getSourceRange();
8161 return QualType();
8162 }
8163
8164 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8165 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8166 << RHSType << RHS.get()->getSourceRange();
8167 return QualType();
8168 }
8169
8170 // If both types are identical, no conversion is needed.
8171 if (LHSType == RHSType)
8172 return LHSType;
8173
8174 // Now handle "real" floating types (i.e. float, double, long double).
8175 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8176 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8177 /*IsCompAssign = */ false);
8178
8179 // Finally, we have two differing integer types.
8180 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8181 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8182}
8183
8184/// Convert scalar operands to a vector that matches the
8185/// condition in length.
8186///
8187/// Used when handling the OpenCL conditional operator where the
8188/// condition is a vector while the other operands are scalar.
8189///
8190/// We first compute the "result type" for the scalar operands
8191/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8192/// into a vector of that type where the length matches the condition
8193/// vector type. s6.11.6 requires that the element types of the result
8194/// and the condition must have the same number of bits.
8195static QualType
8197 QualType CondTy, SourceLocation QuestionLoc) {
8198 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8199 if (ResTy.isNull()) return QualType();
8200
8201 const VectorType *CV = CondTy->getAs<VectorType>();
8202 assert(CV);
8203
8204 // Determine the vector result type
8205 unsigned NumElements = CV->getNumElements();
8206 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8207
8208 // Ensure that all types have the same number of bits
8210 != S.Context.getTypeSize(ResTy)) {
8211 // Since VectorTy is created internally, it does not pretty print
8212 // with an OpenCL name. Instead, we just print a description.
8213 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8214 SmallString<64> Str;
8215 llvm::raw_svector_ostream OS(Str);
8216 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8217 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8218 << CondTy << OS.str();
8219 return QualType();
8220 }
8221
8222 // Convert operands to the vector result type
8223 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8224 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8225
8226 return VectorTy;
8227}
8228
8229/// Return false if this is a valid OpenCL condition vector
8231 SourceLocation QuestionLoc) {
8232 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8233 // integral type.
8234 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8235 assert(CondTy);
8236 QualType EleTy = CondTy->getElementType();
8237 if (EleTy->isIntegerType()) return false;
8238
8239 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8240 << Cond->getType() << Cond->getSourceRange();
8241 return true;
8242}
8243
8244/// Return false if the vector condition type and the vector
8245/// result type are compatible.
8246///
8247/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8248/// number of elements, and their element types have the same number
8249/// of bits.
8250static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8251 SourceLocation QuestionLoc) {
8252 const VectorType *CV = CondTy->getAs<VectorType>();
8253 const VectorType *RV = VecResTy->getAs<VectorType>();
8254 assert(CV && RV);
8255
8256 if (CV->getNumElements() != RV->getNumElements()) {
8257 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8258 << CondTy << VecResTy;
8259 return true;
8260 }
8261
8262 QualType CVE = CV->getElementType();
8263 QualType RVE = RV->getElementType();
8264
8265 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8266 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8267 << CondTy << VecResTy;
8268 return true;
8269 }
8270
8271 return false;
8272}
8273
8274/// Return the resulting type for the conditional operator in
8275/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8276/// s6.3.i) when the condition is a vector type.
8277static QualType
8279 ExprResult &LHS, ExprResult &RHS,
8280 SourceLocation QuestionLoc) {
8282 if (Cond.isInvalid())
8283 return QualType();
8284 QualType CondTy = Cond.get()->getType();
8285
8286 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8287 return QualType();
8288
8289 // If either operand is a vector then find the vector type of the
8290 // result as specified in OpenCL v1.1 s6.3.i.
8291 if (LHS.get()->getType()->isVectorType() ||
8292 RHS.get()->getType()->isVectorType()) {
8293 bool IsBoolVecLang =
8294 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8295 QualType VecResTy =
8296 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8297 /*isCompAssign*/ false,
8298 /*AllowBothBool*/ true,
8299 /*AllowBoolConversions*/ false,
8300 /*AllowBooleanOperation*/ IsBoolVecLang,
8301 /*ReportInvalid*/ true);
8302 if (VecResTy.isNull())
8303 return QualType();
8304 // The result type must match the condition type as specified in
8305 // OpenCL v1.1 s6.11.6.
8306 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8307 return QualType();
8308 return VecResTy;
8309 }
8310
8311 // Both operands are scalar.
8312 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8313}
8314
8315/// Return true if the Expr is block type
8316static bool checkBlockType(Sema &S, const Expr *E) {
8317 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8318 QualType Ty = CE->getCallee()->getType();
8319 if (Ty->isBlockPointerType()) {
8320 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8321 return true;
8322 }
8323 }
8324 return false;
8325}
8326
8327/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8328/// In that case, LHS = cond.
8329/// C99 6.5.15
8331 ExprResult &RHS, ExprValueKind &VK,
8332 ExprObjectKind &OK,
8333 SourceLocation QuestionLoc) {
8334
8335 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8336 if (!LHSResult.isUsable()) return QualType();
8337 LHS = LHSResult;
8338
8339 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8340 if (!RHSResult.isUsable()) return QualType();
8341 RHS = RHSResult;
8342
8343 // C++ is sufficiently different to merit its own checker.
8344 if (getLangOpts().CPlusPlus)
8345 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8346
8347 VK = VK_PRValue;
8348 OK = OK_Ordinary;
8349
8351 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8352 RHS.get()->isTypeDependent())) {
8353 assert(!getLangOpts().CPlusPlus);
8354 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8355 RHS.get()->containsErrors()) &&
8356 "should only occur in error-recovery path.");
8357 return Context.DependentTy;
8358 }
8359
8360 // The OpenCL operator with a vector condition is sufficiently
8361 // different to merit its own checker.
8362 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8363 Cond.get()->getType()->isExtVectorType())
8364 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8365
8366 // First, check the condition.
8367 Cond = UsualUnaryConversions(Cond.get());
8368 if (Cond.isInvalid())
8369 return QualType();
8370 if (checkCondition(*this, Cond.get(), QuestionLoc))
8371 return QualType();
8372
8373 // Handle vectors.
8374 if (LHS.get()->getType()->isVectorType() ||
8375 RHS.get()->getType()->isVectorType())
8376 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8377 /*AllowBothBool*/ true,
8378 /*AllowBoolConversions*/ false,
8379 /*AllowBooleanOperation*/ false,
8380 /*ReportInvalid*/ true);
8381
8382 QualType ResTy =
8383 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8384 if (LHS.isInvalid() || RHS.isInvalid())
8385 return QualType();
8386
8387 // WebAssembly tables are not allowed as conditional LHS or RHS.
8388 QualType LHSTy = LHS.get()->getType();
8389 QualType RHSTy = RHS.get()->getType();
8390 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8391 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8392 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8393 return QualType();
8394 }
8395
8396 // Diagnose attempts to convert between __ibm128, __float128 and long double
8397 // where such conversions currently can't be handled.
8398 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8399 Diag(QuestionLoc,
8400 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8401 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8402 return QualType();
8403 }
8404
8405 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8406 // selection operator (?:).
8407 if (getLangOpts().OpenCL &&
8408 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8409 return QualType();
8410 }
8411
8412 // If both operands have arithmetic type, do the usual arithmetic conversions
8413 // to find a common type: C99 6.5.15p3,5.
8414 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8415 // Disallow invalid arithmetic conversions, such as those between bit-
8416 // precise integers types of different sizes, or between a bit-precise
8417 // integer and another type.
8418 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8419 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8420 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8421 << RHS.get()->getSourceRange();
8422 return QualType();
8423 }
8424
8425 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8426 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8427
8428 return ResTy;
8429 }
8430
8431 // If both operands are the same structure or union type, the result is that
8432 // type.
8433 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8434 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8435 if (LHSRT->getDecl() == RHSRT->getDecl())
8436 // "If both the operands have structure or union type, the result has
8437 // that type." This implies that CV qualifiers are dropped.
8439 RHSTy.getUnqualifiedType());
8440 // FIXME: Type of conditional expression must be complete in C mode.
8441 }
8442
8443 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8444 // The following || allows only one side to be void (a GCC-ism).
8445 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8446 QualType ResTy;
8447 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8448 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8449 } else if (RHSTy->isVoidType()) {
8450 ResTy = RHSTy;
8451 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8452 << RHS.get()->getSourceRange();
8453 } else {
8454 ResTy = LHSTy;
8455 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8456 << LHS.get()->getSourceRange();
8457 }
8458 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8459 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8460 return ResTy;
8461 }
8462
8463 // C23 6.5.15p7:
8464 // ... if both the second and third operands have nullptr_t type, the
8465 // result also has that type.
8466 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8467 return ResTy;
8468
8469 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8470 // the type of the other operand."
8471 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8472 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8473
8474 // All objective-c pointer type analysis is done here.
8475 QualType compositeType =
8476 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8477 if (LHS.isInvalid() || RHS.isInvalid())
8478 return QualType();
8479 if (!compositeType.isNull())
8480 return compositeType;
8481
8482
8483 // Handle block pointer types.
8484 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8485 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8486 QuestionLoc);
8487
8488 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8489 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8490 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8491 QuestionLoc);
8492
8493 // GCC compatibility: soften pointer/integer mismatch. Note that
8494 // null pointers have been filtered out by this point.
8495 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8496 /*IsIntFirstExpr=*/true))
8497 return RHSTy;
8498 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8499 /*IsIntFirstExpr=*/false))
8500 return LHSTy;
8501
8502 // Emit a better diagnostic if one of the expressions is a null pointer
8503 // constant and the other is not a pointer type. In this case, the user most
8504 // likely forgot to take the address of the other expression.
8505 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8506 return QualType();
8507
8508 // Finally, if the LHS and RHS types are canonically the same type, we can
8509 // use the common sugared type.
8510 if (Context.hasSameType(LHSTy, RHSTy))
8511 return Context.getCommonSugaredType(LHSTy, RHSTy);
8512
8513 // Otherwise, the operands are not compatible.
8514 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8515 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8516 << RHS.get()->getSourceRange();
8517 return QualType();
8518}
8519
8520/// SuggestParentheses - Emit a note with a fixit hint that wraps
8521/// ParenRange in parentheses.
8523 const PartialDiagnostic &Note,
8524 SourceRange ParenRange) {
8525 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8526 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8527 EndLoc.isValid()) {
8528 Self.Diag(Loc, Note)
8529 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8530 << FixItHint::CreateInsertion(EndLoc, ")");
8531 } else {
8532 // We can't display the parentheses, so just show the bare note.
8533 Self.Diag(Loc, Note) << ParenRange;
8534 }
8535}
8536
8538 return BinaryOperator::isAdditiveOp(Opc) ||
8540 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8541 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8542 // not any of the logical operators. Bitwise-xor is commonly used as a
8543 // logical-xor because there is no logical-xor operator. The logical
8544 // operators, including uses of xor, have a high false positive rate for
8545 // precedence warnings.
8546}
8547
8548/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8549/// expression, either using a built-in or overloaded operator,
8550/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8551/// expression.
8553 const Expr **RHSExprs) {
8554 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8555 E = E->IgnoreImpCasts();
8557 E = E->IgnoreImpCasts();
8558 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8559 E = MTE->getSubExpr();
8560 E = E->IgnoreImpCasts();
8561 }
8562
8563 // Built-in binary operator.
8564 if (const auto *OP = dyn_cast<BinaryOperator>(E);
8565 OP && IsArithmeticOp(OP->getOpcode())) {
8566 *Opcode = OP->getOpcode();
8567 *RHSExprs = OP->getRHS();
8568 return true;
8569 }
8570
8571 // Overloaded operator.
8572 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8573 if (Call->getNumArgs() != 2)
8574 return false;
8575
8576 // Make sure this is really a binary operator that is safe to pass into
8577 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8578 OverloadedOperatorKind OO = Call->getOperator();
8579 if (OO < OO_Plus || OO > OO_Arrow ||
8580 OO == OO_PlusPlus || OO == OO_MinusMinus)
8581 return false;
8582
8584 if (IsArithmeticOp(OpKind)) {
8585 *Opcode = OpKind;
8586 *RHSExprs = Call->getArg(1);
8587 return true;
8588 }
8589 }
8590
8591 return false;
8592}
8593
8594/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8595/// or is a logical expression such as (x==y) which has int type, but is
8596/// commonly interpreted as boolean.
8597static bool ExprLooksBoolean(const Expr *E) {
8598 E = E->IgnoreParenImpCasts();
8599
8600 if (E->getType()->isBooleanType())
8601 return true;
8602 if (const auto *OP = dyn_cast<BinaryOperator>(E))
8603 return OP->isComparisonOp() || OP->isLogicalOp();
8604 if (const auto *OP = dyn_cast<UnaryOperator>(E))
8605 return OP->getOpcode() == UO_LNot;
8606 if (E->getType()->isPointerType())
8607 return true;
8608 // FIXME: What about overloaded operator calls returning "unspecified boolean
8609 // type"s (commonly pointer-to-members)?
8610
8611 return false;
8612}
8613
8614/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8615/// and binary operator are mixed in a way that suggests the programmer assumed
8616/// the conditional operator has higher precedence, for example:
8617/// "int x = a + someBinaryCondition ? 1 : 2".
8619 Expr *Condition, const Expr *LHSExpr,
8620 const Expr *RHSExpr) {
8621 BinaryOperatorKind CondOpcode;
8622 const Expr *CondRHS;
8623
8624 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8625 return;
8626 if (!ExprLooksBoolean(CondRHS))
8627 return;
8628
8629 // The condition is an arithmetic binary expression, with a right-
8630 // hand side that looks boolean, so warn.
8631
8632 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8633 ? diag::warn_precedence_bitwise_conditional
8634 : diag::warn_precedence_conditional;
8635
8636 Self.Diag(OpLoc, DiagID)
8637 << Condition->getSourceRange()
8638 << BinaryOperator::getOpcodeStr(CondOpcode);
8639
8641 Self, OpLoc,
8642 Self.PDiag(diag::note_precedence_silence)
8643 << BinaryOperator::getOpcodeStr(CondOpcode),
8644 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8645
8646 SuggestParentheses(Self, OpLoc,
8647 Self.PDiag(diag::note_precedence_conditional_first),
8648 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8649}
8650
8651/// Compute the nullability of a conditional expression.
8653 QualType LHSTy, QualType RHSTy,
8654 ASTContext &Ctx) {
8655 if (!ResTy->isAnyPointerType())
8656 return ResTy;
8657
8658 auto GetNullability = [](QualType Ty) {
8659 std::optional<NullabilityKind> Kind = Ty->getNullability();
8660 if (Kind) {
8661 // For our purposes, treat _Nullable_result as _Nullable.
8664 return *Kind;
8665 }
8667 };
8668
8669 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8670 NullabilityKind MergedKind;
8671
8672 // Compute nullability of a binary conditional expression.
8673 if (IsBin) {
8674 if (LHSKind == NullabilityKind::NonNull)
8675 MergedKind = NullabilityKind::NonNull;
8676 else
8677 MergedKind = RHSKind;
8678 // Compute nullability of a normal conditional expression.
8679 } else {
8680 if (LHSKind == NullabilityKind::Nullable ||
8681 RHSKind == NullabilityKind::Nullable)
8682 MergedKind = NullabilityKind::Nullable;
8683 else if (LHSKind == NullabilityKind::NonNull)
8684 MergedKind = RHSKind;
8685 else if (RHSKind == NullabilityKind::NonNull)
8686 MergedKind = LHSKind;
8687 else
8688 MergedKind = NullabilityKind::Unspecified;
8689 }
8690
8691 // Return if ResTy already has the correct nullability.
8692 if (GetNullability(ResTy) == MergedKind)
8693 return ResTy;
8694
8695 // Strip all nullability from ResTy.
8696 while (ResTy->getNullability())
8697 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8698
8699 // Create a new AttributedType with the new nullability kind.
8700 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8701 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8702}
8703
8705 SourceLocation ColonLoc,
8706 Expr *CondExpr, Expr *LHSExpr,
8707 Expr *RHSExpr) {
8709 // C cannot handle TypoExpr nodes in the condition because it
8710 // doesn't handle dependent types properly, so make sure any TypoExprs have
8711 // been dealt with before checking the operands.
8712 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8713 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8714 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8715
8716 if (!CondResult.isUsable())
8717 return ExprError();
8718
8719 if (LHSExpr) {
8720 if (!LHSResult.isUsable())
8721 return ExprError();
8722 }
8723
8724 if (!RHSResult.isUsable())
8725 return ExprError();
8726
8727 CondExpr = CondResult.get();
8728 LHSExpr = LHSResult.get();
8729 RHSExpr = RHSResult.get();
8730 }
8731
8732 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8733 // was the condition.
8734 OpaqueValueExpr *opaqueValue = nullptr;
8735 Expr *commonExpr = nullptr;
8736 if (!LHSExpr) {
8737 commonExpr = CondExpr;
8738 // Lower out placeholder types first. This is important so that we don't
8739 // try to capture a placeholder. This happens in few cases in C++; such
8740 // as Objective-C++'s dictionary subscripting syntax.
8741 if (commonExpr->hasPlaceholderType()) {
8742 ExprResult result = CheckPlaceholderExpr(commonExpr);
8743 if (!result.isUsable()) return ExprError();
8744 commonExpr = result.get();
8745 }
8746 // We usually want to apply unary conversions *before* saving, except
8747 // in the special case of a C++ l-value conditional.
8748 if (!(getLangOpts().CPlusPlus
8749 && !commonExpr->isTypeDependent()
8750 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8751 && commonExpr->isGLValue()
8752 && commonExpr->isOrdinaryOrBitFieldObject()
8753 && RHSExpr->isOrdinaryOrBitFieldObject()
8754 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8755 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8756 if (commonRes.isInvalid())
8757 return ExprError();
8758 commonExpr = commonRes.get();
8759 }
8760
8761 // If the common expression is a class or array prvalue, materialize it
8762 // so that we can safely refer to it multiple times.
8763 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8764 commonExpr->getType()->isArrayType())) {
8765 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8766 if (MatExpr.isInvalid())
8767 return ExprError();
8768 commonExpr = MatExpr.get();
8769 }
8770
8771 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8772 commonExpr->getType(),
8773 commonExpr->getValueKind(),
8774 commonExpr->getObjectKind(),
8775 commonExpr);
8776 LHSExpr = CondExpr = opaqueValue;
8777 }
8778
8779 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8782 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8783 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8784 VK, OK, QuestionLoc);
8785 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8786 RHS.isInvalid())
8787 return ExprError();
8788
8789 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8790 RHS.get());
8791
8792 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8793
8794 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8795 Context);
8796
8797 if (!commonExpr)
8798 return new (Context)
8799 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8800 RHS.get(), result, VK, OK);
8801
8803 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8804 ColonLoc, result, VK, OK);
8805}
8806
8808 unsigned FromAttributes = 0, ToAttributes = 0;
8809 if (const auto *FromFn =
8810 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
8811 FromAttributes =
8812 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8813 if (const auto *ToFn =
8814 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
8815 ToAttributes =
8816 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8817
8818 return FromAttributes != ToAttributes;
8819}
8820
8821// Check if we have a conversion between incompatible cmse function pointer
8822// types, that is, a conversion between a function pointer with the
8823// cmse_nonsecure_call attribute and one without.
8825 QualType ToType) {
8826 if (const auto *ToFn =
8827 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8828 if (const auto *FromFn =
8829 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8830 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8831 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8832
8833 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8834 }
8835 }
8836 return false;
8837}
8838
8839// checkPointerTypesForAssignment - This is a very tricky routine (despite
8840// being closely modeled after the C99 spec:-). The odd characteristic of this
8841// routine is it effectively iqnores the qualifiers on the top level pointee.
8842// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8843// FIXME: add a couple examples in this comment.
8847 assert(LHSType.isCanonical() && "LHS not canonicalized!");
8848 assert(RHSType.isCanonical() && "RHS not canonicalized!");
8849
8850 // get the "pointed to" type (ignoring qualifiers at the top level)
8851 const Type *lhptee, *rhptee;
8852 Qualifiers lhq, rhq;
8853 std::tie(lhptee, lhq) =
8854 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8855 std::tie(rhptee, rhq) =
8856 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8857
8859
8860 // C99 6.5.16.1p1: This following citation is common to constraints
8861 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8862 // qualifiers of the type *pointed to* by the right;
8863
8864 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8865 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8867 // Ignore lifetime for further calculation.
8868 lhq.removeObjCLifetime();
8869 rhq.removeObjCLifetime();
8870 }
8871
8872 if (!lhq.compatiblyIncludes(rhq)) {
8873 // Treat address-space mismatches as fatal.
8874 if (!lhq.isAddressSpaceSupersetOf(rhq))
8876
8877 // It's okay to add or remove GC or lifetime qualifiers when converting to
8878 // and from void*.
8879 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8882 && (lhptee->isVoidType() || rhptee->isVoidType()))
8883 ; // keep old
8884
8885 // Treat lifetime mismatches as fatal.
8886 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8888
8889 // For GCC/MS compatibility, other qualifier mismatches are treated
8890 // as still compatible in C.
8892 }
8893
8894 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8895 // incomplete type and the other is a pointer to a qualified or unqualified
8896 // version of void...
8897 if (lhptee->isVoidType()) {
8898 if (rhptee->isIncompleteOrObjectType())
8899 return ConvTy;
8900
8901 // As an extension, we allow cast to/from void* to function pointer.
8902 assert(rhptee->isFunctionType());
8904 }
8905
8906 if (rhptee->isVoidType()) {
8907 if (lhptee->isIncompleteOrObjectType())
8908 return ConvTy;
8909
8910 // As an extension, we allow cast to/from void* to function pointer.
8911 assert(lhptee->isFunctionType());
8913 }
8914
8915 if (!S.Diags.isIgnored(
8916 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
8917 Loc) &&
8918 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
8919 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
8921
8922 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8923 // unqualified versions of compatible types, ...
8924 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8925 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8926 // Check if the pointee types are compatible ignoring the sign.
8927 // We explicitly check for char so that we catch "char" vs
8928 // "unsigned char" on systems where "char" is unsigned.
8929 if (lhptee->isCharType())
8930 ltrans = S.Context.UnsignedCharTy;
8931 else if (lhptee->hasSignedIntegerRepresentation())
8932 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8933
8934 if (rhptee->isCharType())
8935 rtrans = S.Context.UnsignedCharTy;
8936 else if (rhptee->hasSignedIntegerRepresentation())
8937 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8938
8939 if (ltrans == rtrans) {
8940 // Types are compatible ignoring the sign. Qualifier incompatibility
8941 // takes priority over sign incompatibility because the sign
8942 // warning can be disabled.
8943 if (ConvTy != Sema::Compatible)
8944 return ConvTy;
8945
8947 }
8948
8949 // If we are a multi-level pointer, it's possible that our issue is simply
8950 // one of qualification - e.g. char ** -> const char ** is not allowed. If
8951 // the eventual target type is the same and the pointers have the same
8952 // level of indirection, this must be the issue.
8953 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8954 do {
8955 std::tie(lhptee, lhq) =
8956 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8957 std::tie(rhptee, rhq) =
8958 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8959
8960 // Inconsistent address spaces at this point is invalid, even if the
8961 // address spaces would be compatible.
8962 // FIXME: This doesn't catch address space mismatches for pointers of
8963 // different nesting levels, like:
8964 // __local int *** a;
8965 // int ** b = a;
8966 // It's not clear how to actually determine when such pointers are
8967 // invalidly incompatible.
8968 if (lhq.getAddressSpace() != rhq.getAddressSpace())
8970
8971 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8972
8973 if (lhptee == rhptee)
8975 }
8976
8977 // General pointer incompatibility takes priority over qualifiers.
8978 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8981 }
8982 if (!S.getLangOpts().CPlusPlus &&
8983 S.IsFunctionConversion(ltrans, rtrans, ltrans))
8985 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8987 if (S.IsInvalidSMECallConversion(rtrans, ltrans))
8989 return ConvTy;
8990}
8991
8992/// checkBlockPointerTypesForAssignment - This routine determines whether two
8993/// block pointer types are compatible or whether a block and normal pointer
8994/// are compatible. It is more restrict than comparing two function pointer
8995// types.
8998 QualType RHSType) {
8999 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9000 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9001
9002 QualType lhptee, rhptee;
9003
9004 // get the "pointed to" type (ignoring qualifiers at the top level)
9005 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9006 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9007
9008 // In C++, the types have to match exactly.
9009 if (S.getLangOpts().CPlusPlus)
9011
9013
9014 // For blocks we enforce that qualifiers are identical.
9015 Qualifiers LQuals = lhptee.getLocalQualifiers();
9016 Qualifiers RQuals = rhptee.getLocalQualifiers();
9017 if (S.getLangOpts().OpenCL) {
9018 LQuals.removeAddressSpace();
9019 RQuals.removeAddressSpace();
9020 }
9021 if (LQuals != RQuals)
9023
9024 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9025 // assignment.
9026 // The current behavior is similar to C++ lambdas. A block might be
9027 // assigned to a variable iff its return type and parameters are compatible
9028 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9029 // an assignment. Presumably it should behave in way that a function pointer
9030 // assignment does in C, so for each parameter and return type:
9031 // * CVR and address space of LHS should be a superset of CVR and address
9032 // space of RHS.
9033 // * unqualified types should be compatible.
9034 if (S.getLangOpts().OpenCL) {
9036 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9037 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9039 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9041
9042 return ConvTy;
9043}
9044
9045/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9046/// for assignment compatibility.
9049 QualType RHSType) {
9050 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9051 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9052
9053 if (LHSType->isObjCBuiltinType()) {
9054 // Class is not compatible with ObjC object pointers.
9055 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9056 !RHSType->isObjCQualifiedClassType())
9058 return Sema::Compatible;
9059 }
9060 if (RHSType->isObjCBuiltinType()) {
9061 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9062 !LHSType->isObjCQualifiedClassType())
9064 return Sema::Compatible;
9065 }
9066 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9067 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9068
9069 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9070 // make an exception for id<P>
9071 !LHSType->isObjCQualifiedIdType())
9073
9074 if (S.Context.typesAreCompatible(LHSType, RHSType))
9075 return Sema::Compatible;
9076 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9079}
9080
9083 QualType LHSType, QualType RHSType) {
9084 // Fake up an opaque expression. We don't actually care about what
9085 // cast operations are required, so if CheckAssignmentConstraints
9086 // adds casts to this they'll be wasted, but fortunately that doesn't
9087 // usually happen on valid code.
9088 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9089 ExprResult RHSPtr = &RHSExpr;
9090 CastKind K;
9091
9092 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9093}
9094
9095/// This helper function returns true if QT is a vector type that has element
9096/// type ElementType.
9097static bool isVector(QualType QT, QualType ElementType) {
9098 if (const VectorType *VT = QT->getAs<VectorType>())
9099 return VT->getElementType().getCanonicalType() == ElementType;
9100 return false;
9101}
9102
9103/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9104/// has code to accommodate several GCC extensions when type checking
9105/// pointers. Here are some objectionable examples that GCC considers warnings:
9106///
9107/// int a, *pint;
9108/// short *pshort;
9109/// struct foo *pfoo;
9110///
9111/// pint = pshort; // warning: assignment from incompatible pointer type
9112/// a = pint; // warning: assignment makes integer from pointer without a cast
9113/// pint = a; // warning: assignment makes pointer from integer without a cast
9114/// pint = pfoo; // warning: assignment from incompatible pointer type
9115///
9116/// As a result, the code for dealing with pointers is more complex than the
9117/// C99 spec dictates.
9118///
9119/// Sets 'Kind' for any result kind except Incompatible.
9122 CastKind &Kind, bool ConvertRHS) {
9123 QualType RHSType = RHS.get()->getType();
9124 QualType OrigLHSType = LHSType;
9125
9126 // Get canonical types. We're not formatting these types, just comparing
9127 // them.
9128 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9129 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9130
9131 // Common case: no conversion required.
9132 if (LHSType == RHSType) {
9133 Kind = CK_NoOp;
9134 return Compatible;
9135 }
9136
9137 // If the LHS has an __auto_type, there are no additional type constraints
9138 // to be worried about.
9139 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9140 if (AT->isGNUAutoType()) {
9141 Kind = CK_NoOp;
9142 return Compatible;
9143 }
9144 }
9145
9146 // If we have an atomic type, try a non-atomic assignment, then just add an
9147 // atomic qualification step.
9148 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9150 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9151 if (result != Compatible)
9152 return result;
9153 if (Kind != CK_NoOp && ConvertRHS)
9154 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9155 Kind = CK_NonAtomicToAtomic;
9156 return Compatible;
9157 }
9158
9159 // If the left-hand side is a reference type, then we are in a
9160 // (rare!) case where we've allowed the use of references in C,
9161 // e.g., as a parameter type in a built-in function. In this case,
9162 // just make sure that the type referenced is compatible with the
9163 // right-hand side type. The caller is responsible for adjusting
9164 // LHSType so that the resulting expression does not have reference
9165 // type.
9166 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9167 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9168 Kind = CK_LValueBitCast;
9169 return Compatible;
9170 }
9171 return Incompatible;
9172 }
9173
9174 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9175 // to the same ExtVector type.
9176 if (LHSType->isExtVectorType()) {
9177 if (RHSType->isExtVectorType())
9178 return Incompatible;
9179 if (RHSType->isArithmeticType()) {
9180 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9181 if (ConvertRHS)
9182 RHS = prepareVectorSplat(LHSType, RHS.get());
9183 Kind = CK_VectorSplat;
9184 return Compatible;
9185 }
9186 }
9187
9188 // Conversions to or from vector type.
9189 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9190 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9191 // Allow assignments of an AltiVec vector type to an equivalent GCC
9192 // vector type and vice versa
9193 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9194 Kind = CK_BitCast;
9195 return Compatible;
9196 }
9197
9198 // If we are allowing lax vector conversions, and LHS and RHS are both
9199 // vectors, the total size only needs to be the same. This is a bitcast;
9200 // no bits are changed but the result type is different.
9201 if (isLaxVectorConversion(RHSType, LHSType)) {
9202 // The default for lax vector conversions with Altivec vectors will
9203 // change, so if we are converting between vector types where
9204 // at least one is an Altivec vector, emit a warning.
9205 if (Context.getTargetInfo().getTriple().isPPC() &&
9206 anyAltivecTypes(RHSType, LHSType) &&
9207 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9208 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9209 << RHSType << LHSType;
9210 Kind = CK_BitCast;
9211 return IncompatibleVectors;
9212 }
9213 }
9214
9215 // When the RHS comes from another lax conversion (e.g. binops between
9216 // scalars and vectors) the result is canonicalized as a vector. When the
9217 // LHS is also a vector, the lax is allowed by the condition above. Handle
9218 // the case where LHS is a scalar.
9219 if (LHSType->isScalarType()) {
9220 const VectorType *VecType = RHSType->getAs<VectorType>();
9221 if (VecType && VecType->getNumElements() == 1 &&
9222 isLaxVectorConversion(RHSType, LHSType)) {
9223 if (Context.getTargetInfo().getTriple().isPPC() &&
9225 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9227 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9228 << RHSType << LHSType;
9229 ExprResult *VecExpr = &RHS;
9230 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9231 Kind = CK_BitCast;
9232 return Compatible;
9233 }
9234 }
9235
9236 // Allow assignments between fixed-length and sizeless SVE vectors.
9237 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9238 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9239 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9240 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9241 Kind = CK_BitCast;
9242 return Compatible;
9243 }
9244
9245 // Allow assignments between fixed-length and sizeless RVV vectors.
9246 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9247 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9248 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9249 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9250 Kind = CK_BitCast;
9251 return Compatible;
9252 }
9253 }
9254
9255 return Incompatible;
9256 }
9257
9258 // Diagnose attempts to convert between __ibm128, __float128 and long double
9259 // where such conversions currently can't be handled.
9260 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9261 return Incompatible;
9262
9263 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9264 // discards the imaginary part.
9265 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9266 !LHSType->getAs<ComplexType>())
9267 return Incompatible;
9268
9269 // Arithmetic conversions.
9270 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9271 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9272 if (ConvertRHS)
9273 Kind = PrepareScalarCast(RHS, LHSType);
9274 return Compatible;
9275 }
9276
9277 // Conversions to normal pointers.
9278 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9279 // U* -> T*
9280 if (isa<PointerType>(RHSType)) {
9281 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9282 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9283 if (AddrSpaceL != AddrSpaceR)
9284 Kind = CK_AddressSpaceConversion;
9285 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9286 Kind = CK_NoOp;
9287 else
9288 Kind = CK_BitCast;
9289 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9290 RHS.get()->getBeginLoc());
9291 }
9292
9293 // int -> T*
9294 if (RHSType->isIntegerType()) {
9295 Kind = CK_IntegralToPointer; // FIXME: null?
9296 return IntToPointer;
9297 }
9298
9299 // C pointers are not compatible with ObjC object pointers,
9300 // with two exceptions:
9301 if (isa<ObjCObjectPointerType>(RHSType)) {
9302 // - conversions to void*
9303 if (LHSPointer->getPointeeType()->isVoidType()) {
9304 Kind = CK_BitCast;
9305 return Compatible;
9306 }
9307
9308 // - conversions from 'Class' to the redefinition type
9309 if (RHSType->isObjCClassType() &&
9310 Context.hasSameType(LHSType,
9312 Kind = CK_BitCast;
9313 return Compatible;
9314 }
9315
9316 Kind = CK_BitCast;
9317 return IncompatiblePointer;
9318 }
9319
9320 // U^ -> void*
9321 if (RHSType->getAs<BlockPointerType>()) {
9322 if (LHSPointer->getPointeeType()->isVoidType()) {
9323 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9324 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9325 ->getPointeeType()
9326 .getAddressSpace();
9327 Kind =
9328 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9329 return Compatible;
9330 }
9331 }
9332
9333 return Incompatible;
9334 }
9335
9336 // Conversions to block pointers.
9337 if (isa<BlockPointerType>(LHSType)) {
9338 // U^ -> T^
9339 if (RHSType->isBlockPointerType()) {
9340 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9341 ->getPointeeType()
9342 .getAddressSpace();
9343 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9344 ->getPointeeType()
9345 .getAddressSpace();
9346 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9347 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9348 }
9349
9350 // int or null -> T^
9351 if (RHSType->isIntegerType()) {
9352 Kind = CK_IntegralToPointer; // FIXME: null
9353 return IntToBlockPointer;
9354 }
9355
9356 // id -> T^
9357 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9358 Kind = CK_AnyPointerToBlockPointerCast;
9359 return Compatible;
9360 }
9361
9362 // void* -> T^
9363 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9364 if (RHSPT->getPointeeType()->isVoidType()) {
9365 Kind = CK_AnyPointerToBlockPointerCast;
9366 return Compatible;
9367 }
9368
9369 return Incompatible;
9370 }
9371
9372 // Conversions to Objective-C pointers.
9373 if (isa<ObjCObjectPointerType>(LHSType)) {
9374 // A* -> B*
9375 if (RHSType->isObjCObjectPointerType()) {
9376 Kind = CK_BitCast;
9378 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9379 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9380 result == Compatible &&
9381 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9382 result = IncompatibleObjCWeakRef;
9383 return result;
9384 }
9385
9386 // int or null -> A*
9387 if (RHSType->isIntegerType()) {
9388 Kind = CK_IntegralToPointer; // FIXME: null
9389 return IntToPointer;
9390 }
9391
9392 // In general, C pointers are not compatible with ObjC object pointers,
9393 // with two exceptions:
9394 if (isa<PointerType>(RHSType)) {
9395 Kind = CK_CPointerToObjCPointerCast;
9396
9397 // - conversions from 'void*'
9398 if (RHSType->isVoidPointerType()) {
9399 return Compatible;
9400 }
9401
9402 // - conversions to 'Class' from its redefinition type
9403 if (LHSType->isObjCClassType() &&
9404 Context.hasSameType(RHSType,
9406 return Compatible;
9407 }
9408
9409 return IncompatiblePointer;
9410 }
9411
9412 // Only under strict condition T^ is compatible with an Objective-C pointer.
9413 if (RHSType->isBlockPointerType() &&
9415 if (ConvertRHS)
9417 Kind = CK_BlockPointerToObjCPointerCast;
9418 return Compatible;
9419 }
9420
9421 return Incompatible;
9422 }
9423
9424 // Conversion to nullptr_t (C23 only)
9425 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9428 // null -> nullptr_t
9429 Kind = CK_NullToPointer;
9430 return Compatible;
9431 }
9432
9433 // Conversions from pointers that are not covered by the above.
9434 if (isa<PointerType>(RHSType)) {
9435 // T* -> _Bool
9436 if (LHSType == Context.BoolTy) {
9437 Kind = CK_PointerToBoolean;
9438 return Compatible;
9439 }
9440
9441 // T* -> int
9442 if (LHSType->isIntegerType()) {
9443 Kind = CK_PointerToIntegral;
9444 return PointerToInt;
9445 }
9446
9447 return Incompatible;
9448 }
9449
9450 // Conversions from Objective-C pointers that are not covered by the above.
9451 if (isa<ObjCObjectPointerType>(RHSType)) {
9452 // T* -> _Bool
9453 if (LHSType == Context.BoolTy) {
9454 Kind = CK_PointerToBoolean;
9455 return Compatible;
9456 }
9457
9458 // T* -> int
9459 if (LHSType->isIntegerType()) {
9460 Kind = CK_PointerToIntegral;
9461 return PointerToInt;
9462 }
9463
9464 return Incompatible;
9465 }
9466
9467 // struct A -> struct B
9468 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9469 if (Context.typesAreCompatible(LHSType, RHSType)) {
9470 Kind = CK_NoOp;
9471 return Compatible;
9472 }
9473 }
9474
9475 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9476 Kind = CK_IntToOCLSampler;
9477 return Compatible;
9478 }
9479
9480 return Incompatible;
9481}
9482
9483/// Constructs a transparent union from an expression that is
9484/// used to initialize the transparent union.
9486 ExprResult &EResult, QualType UnionType,
9487 FieldDecl *Field) {
9488 // Build an initializer list that designates the appropriate member
9489 // of the transparent union.
9490 Expr *E = EResult.get();
9492 E, SourceLocation());
9493 Initializer->setType(UnionType);
9494 Initializer->setInitializedFieldInUnion(Field);
9495
9496 // Build a compound literal constructing a value of the transparent
9497 // union type from this initializer list.
9498 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9499 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9500 VK_PRValue, Initializer, false);
9501}
9502
9505 ExprResult &RHS) {
9506 QualType RHSType = RHS.get()->getType();
9507
9508 // If the ArgType is a Union type, we want to handle a potential
9509 // transparent_union GCC extension.
9510 const RecordType *UT = ArgType->getAsUnionType();
9511 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9512 return Incompatible;
9513
9514 // The field to initialize within the transparent union.
9515 RecordDecl *UD = UT->getDecl();
9516 FieldDecl *InitField = nullptr;
9517 // It's compatible if the expression matches any of the fields.
9518 for (auto *it : UD->fields()) {
9519 if (it->getType()->isPointerType()) {
9520 // If the transparent union contains a pointer type, we allow:
9521 // 1) void pointer
9522 // 2) null pointer constant
9523 if (RHSType->isPointerType())
9524 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9525 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9526 InitField = it;
9527 break;
9528 }
9529
9532 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9533 CK_NullToPointer);
9534 InitField = it;
9535 break;
9536 }
9537 }
9538
9539 CastKind Kind;
9540 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9541 == Compatible) {
9542 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9543 InitField = it;
9544 break;
9545 }
9546 }
9547
9548 if (!InitField)
9549 return Incompatible;
9550
9551 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9552 return Compatible;
9553}
9554
9557 bool Diagnose,
9558 bool DiagnoseCFAudited,
9559 bool ConvertRHS) {
9560 // We need to be able to tell the caller whether we diagnosed a problem, if
9561 // they ask us to issue diagnostics.
9562 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9563
9564 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9565 // we can't avoid *all* modifications at the moment, so we need some somewhere
9566 // to put the updated value.
9567 ExprResult LocalRHS = CallerRHS;
9568 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9569
9570 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9571 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9572 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9573 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9574 Diag(RHS.get()->getExprLoc(),
9575 diag::warn_noderef_to_dereferenceable_pointer)
9576 << RHS.get()->getSourceRange();
9577 }
9578 }
9579 }
9580
9581 if (getLangOpts().CPlusPlus) {
9582 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9583 // C++ 5.17p3: If the left operand is not of class type, the
9584 // expression is implicitly converted (C++ 4) to the
9585 // cv-unqualified type of the left operand.
9586 QualType RHSType = RHS.get()->getType();
9587 if (Diagnose) {
9588 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9589 AA_Assigning);
9590 } else {
9593 /*SuppressUserConversions=*/false,
9594 AllowedExplicit::None,
9595 /*InOverloadResolution=*/false,
9596 /*CStyle=*/false,
9597 /*AllowObjCWritebackConversion=*/false);
9598 if (ICS.isFailure())
9599 return Incompatible;
9600 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9601 ICS, AA_Assigning);
9602 }
9603 if (RHS.isInvalid())
9604 return Incompatible;
9606 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9607 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9608 result = IncompatibleObjCWeakRef;
9609 return result;
9610 }
9611
9612 // FIXME: Currently, we fall through and treat C++ classes like C
9613 // structures.
9614 // FIXME: We also fall through for atomics; not sure what should
9615 // happen there, though.
9616 } else if (RHS.get()->getType() == Context.OverloadTy) {
9617 // As a set of extensions to C, we support overloading on functions. These
9618 // functions need to be resolved here.
9619 DeclAccessPair DAP;
9621 RHS.get(), LHSType, /*Complain=*/false, DAP))
9622 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9623 else
9624 return Incompatible;
9625 }
9626
9627 // This check seems unnatural, however it is necessary to ensure the proper
9628 // conversion of functions/arrays. If the conversion were done for all
9629 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9630 // expressions that suppress this implicit conversion (&, sizeof). This needs
9631 // to happen before we check for null pointer conversions because C does not
9632 // undergo the same implicit conversions as C++ does above (by the calls to
9633 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
9634 // lvalue to rvalue cast before checking for null pointer constraints. This
9635 // addresses code like: nullptr_t val; int *ptr; ptr = val;
9636 //
9637 // Suppress this for references: C++ 8.5.3p5.
9638 if (!LHSType->isReferenceType()) {
9639 // FIXME: We potentially allocate here even if ConvertRHS is false.
9641 if (RHS.isInvalid())
9642 return Incompatible;
9643 }
9644
9645 // The constraints are expressed in terms of the atomic, qualified, or
9646 // unqualified type of the LHS.
9647 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
9648
9649 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9650 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
9651 if ((LHSTypeAfterConversion->isPointerType() ||
9652 LHSTypeAfterConversion->isObjCObjectPointerType() ||
9653 LHSTypeAfterConversion->isBlockPointerType()) &&
9654 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
9657 if (Diagnose || ConvertRHS) {
9658 CastKind Kind;
9660 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9661 /*IgnoreBaseAccess=*/false, Diagnose);
9662 if (ConvertRHS)
9663 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9664 }
9665 return Compatible;
9666 }
9667 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
9668 // unqualified bool, and the right operand is a pointer or its type is
9669 // nullptr_t.
9670 if (getLangOpts().C23 && LHSType->isBooleanType() &&
9671 RHS.get()->getType()->isNullPtrType()) {
9672 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
9673 // only handles nullptr -> _Bool due to needing an extra conversion
9674 // step.
9675 // We model this by converting from nullptr -> void * and then let the
9676 // conversion from void * -> _Bool happen naturally.
9677 if (Diagnose || ConvertRHS) {
9678 CastKind Kind;
9681 /*IgnoreBaseAccess=*/false, Diagnose);
9682 if (ConvertRHS)
9683 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
9684 &Path);
9685 }
9686 }
9687
9688 // OpenCL queue_t type assignment.
9689 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9691 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9692 return Compatible;
9693 }
9694
9695 CastKind Kind;
9697 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9698
9699 // C99 6.5.16.1p2: The value of the right operand is converted to the
9700 // type of the assignment expression.
9701 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9702 // so that we can use references in built-in functions even in C.
9703 // The getNonReferenceType() call makes sure that the resulting expression
9704 // does not have reference type.
9705 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9707 Expr *E = RHS.get();
9708
9709 // Check for various Objective-C errors. If we are not reporting
9710 // diagnostics and just checking for errors, e.g., during overload
9711 // resolution, return Incompatible to indicate the failure.
9712 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9713 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
9715 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
9716 if (!Diagnose)
9717 return Incompatible;
9718 }
9719 if (getLangOpts().ObjC &&
9720 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9721 E->getType(), E, Diagnose) ||
9722 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9723 if (!Diagnose)
9724 return Incompatible;
9725 // Replace the expression with a corrected version and continue so we
9726 // can find further errors.
9727 RHS = E;
9728 return Compatible;
9729 }
9730
9731 if (ConvertRHS)
9732 RHS = ImpCastExprToType(E, Ty, Kind);
9733 }
9734
9735 return result;
9736}
9737
9738namespace {
9739/// The original operand to an operator, prior to the application of the usual
9740/// arithmetic conversions and converting the arguments of a builtin operator
9741/// candidate.
9742struct OriginalOperand {
9743 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9744 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9745 Op = MTE->getSubExpr();
9746 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9747 Op = BTE->getSubExpr();
9748 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9749 Orig = ICE->getSubExprAsWritten();
9750 Conversion = ICE->getConversionFunction();
9751 }
9752 }
9753
9754 QualType getType() const { return Orig->getType(); }
9755
9756 Expr *Orig;
9757 NamedDecl *Conversion;
9758};
9759}
9760
9762 ExprResult &RHS) {
9763 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9764
9765 Diag(Loc, diag::err_typecheck_invalid_operands)
9766 << OrigLHS.getType() << OrigRHS.getType()
9767 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9768
9769 // If a user-defined conversion was applied to either of the operands prior
9770 // to applying the built-in operator rules, tell the user about it.
9771 if (OrigLHS.Conversion) {
9772 Diag(OrigLHS.Conversion->getLocation(),
9773 diag::note_typecheck_invalid_operands_converted)
9774 << 0 << LHS.get()->getType();
9775 }
9776 if (OrigRHS.Conversion) {
9777 Diag(OrigRHS.Conversion->getLocation(),
9778 diag::note_typecheck_invalid_operands_converted)
9779 << 1 << RHS.get()->getType();
9780 }
9781
9782 return QualType();
9783}
9784
9786 ExprResult &RHS) {
9787 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9788 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9789
9790 bool LHSNatVec = LHSType->isVectorType();
9791 bool RHSNatVec = RHSType->isVectorType();
9792
9793 if (!(LHSNatVec && RHSNatVec)) {
9794 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9795 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9796 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9797 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9798 << Vector->getSourceRange();
9799 return QualType();
9800 }
9801
9802 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9803 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9804 << RHS.get()->getSourceRange();
9805
9806 return QualType();
9807}
9808
9809/// Try to convert a value of non-vector type to a vector type by converting
9810/// the type to the element type of the vector and then performing a splat.
9811/// If the language is OpenCL, we only use conversions that promote scalar
9812/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9813/// for float->int.
9814///
9815/// OpenCL V2.0 6.2.6.p2:
9816/// An error shall occur if any scalar operand type has greater rank
9817/// than the type of the vector element.
9818///
9819/// \param scalar - if non-null, actually perform the conversions
9820/// \return true if the operation fails (but without diagnosing the failure)
9822 QualType scalarTy,
9823 QualType vectorEltTy,
9824 QualType vectorTy,
9825 unsigned &DiagID) {
9826 // The conversion to apply to the scalar before splatting it,
9827 // if necessary.
9828 CastKind scalarCast = CK_NoOp;
9829
9830 if (vectorEltTy->isIntegralType(S.Context)) {
9831 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9832 (scalarTy->isIntegerType() &&
9833 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9834 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9835 return true;
9836 }
9837 if (!scalarTy->isIntegralType(S.Context))
9838 return true;
9839 scalarCast = CK_IntegralCast;
9840 } else if (vectorEltTy->isRealFloatingType()) {
9841 if (scalarTy->isRealFloatingType()) {
9842 if (S.getLangOpts().OpenCL &&
9843 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9844 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9845 return true;
9846 }
9847 scalarCast = CK_FloatingCast;
9848 }
9849 else if (scalarTy->isIntegralType(S.Context))
9850 scalarCast = CK_IntegralToFloating;
9851 else
9852 return true;
9853 } else {
9854 return true;
9855 }
9856
9857 // Adjust scalar if desired.
9858 if (scalar) {
9859 if (scalarCast != CK_NoOp)
9860 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9861 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9862 }
9863 return false;
9864}
9865
9866/// Convert vector E to a vector with the same number of elements but different
9867/// element type.
9868static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9869 const auto *VecTy = E->getType()->getAs<VectorType>();
9870 assert(VecTy && "Expression E must be a vector");
9871 QualType NewVecTy =
9872 VecTy->isExtVectorType()
9873 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
9874 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
9875 VecTy->getVectorKind());
9876
9877 // Look through the implicit cast. Return the subexpression if its type is
9878 // NewVecTy.
9879 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9880 if (ICE->getSubExpr()->getType() == NewVecTy)
9881 return ICE->getSubExpr();
9882
9883 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9884 return S.ImpCastExprToType(E, NewVecTy, Cast);
9885}
9886
9887/// Test if a (constant) integer Int can be casted to another integer type
9888/// IntTy without losing precision.
9890 QualType OtherIntTy) {
9891 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9892
9893 // Reject cases where the value of the Int is unknown as that would
9894 // possibly cause truncation, but accept cases where the scalar can be
9895 // demoted without loss of precision.
9896 Expr::EvalResult EVResult;
9897 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9898 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9899 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9900 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9901
9902 if (CstInt) {
9903 // If the scalar is constant and is of a higher order and has more active
9904 // bits that the vector element type, reject it.
9905 llvm::APSInt Result = EVResult.Val.getInt();
9906 unsigned NumBits = IntSigned
9907 ? (Result.isNegative() ? Result.getSignificantBits()
9908 : Result.getActiveBits())
9909 : Result.getActiveBits();
9910 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9911 return true;
9912
9913 // If the signedness of the scalar type and the vector element type
9914 // differs and the number of bits is greater than that of the vector
9915 // element reject it.
9916 return (IntSigned != OtherIntSigned &&
9917 NumBits > S.Context.getIntWidth(OtherIntTy));
9918 }
9919
9920 // Reject cases where the value of the scalar is not constant and it's
9921 // order is greater than that of the vector element type.
9922 return (Order < 0);
9923}
9924
9925/// Test if a (constant) integer Int can be casted to floating point type
9926/// FloatTy without losing precision.
9928 QualType FloatTy) {
9929 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9930
9931 // Determine if the integer constant can be expressed as a floating point
9932 // number of the appropriate type.
9933 Expr::EvalResult EVResult;
9934 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9935
9936 uint64_t Bits = 0;
9937 if (CstInt) {
9938 // Reject constants that would be truncated if they were converted to
9939 // the floating point type. Test by simple to/from conversion.
9940 // FIXME: Ideally the conversion to an APFloat and from an APFloat
9941 // could be avoided if there was a convertFromAPInt method
9942 // which could signal back if implicit truncation occurred.
9943 llvm::APSInt Result = EVResult.Val.getInt();
9944 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9945 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9946 llvm::APFloat::rmTowardZero);
9947 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9949 bool Ignored = false;
9950 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9951 &Ignored);
9952 if (Result != ConvertBack)
9953 return true;
9954 } else {
9955 // Reject types that cannot be fully encoded into the mantissa of
9956 // the float.
9957 Bits = S.Context.getTypeSize(IntTy);
9958 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9959 S.Context.getFloatTypeSemantics(FloatTy));
9960 if (Bits > FloatPrec)
9961 return true;
9962 }
9963
9964 return false;
9965}
9966
9967/// Attempt to convert and splat Scalar into a vector whose types matches
9968/// Vector following GCC conversion rules. The rule is that implicit
9969/// conversion can occur when Scalar can be casted to match Vector's element
9970/// type without causing truncation of Scalar.
9972 ExprResult *Vector) {
9973 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9974 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9975 QualType VectorEltTy;
9976
9977 if (const auto *VT = VectorTy->getAs<VectorType>()) {
9978 assert(!isa<ExtVectorType>(VT) &&
9979 "ExtVectorTypes should not be handled here!");
9980 VectorEltTy = VT->getElementType();
9981 } else if (VectorTy->isSveVLSBuiltinType()) {
9982 VectorEltTy =
9983 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
9984 } else {
9985 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
9986 }
9987
9988 // Reject cases where the vector element type or the scalar element type are
9989 // not integral or floating point types.
9990 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9991 return true;
9992
9993 // The conversion to apply to the scalar before splatting it,
9994 // if necessary.
9995 CastKind ScalarCast = CK_NoOp;
9996
9997 // Accept cases where the vector elements are integers and the scalar is
9998 // an integer.
9999 // FIXME: Notionally if the scalar was a floating point value with a precise
10000 // integral representation, we could cast it to an appropriate integer
10001 // type and then perform the rest of the checks here. GCC will perform
10002 // this conversion in some cases as determined by the input language.
10003 // We should accept it on a language independent basis.
10004 if (VectorEltTy->isIntegralType(S.Context) &&
10005 ScalarTy->isIntegralType(S.Context) &&
10006 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10007
10008 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10009 return true;
10010
10011 ScalarCast = CK_IntegralCast;
10012 } else if (VectorEltTy->isIntegralType(S.Context) &&
10013 ScalarTy->isRealFloatingType()) {
10014 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10015 ScalarCast = CK_FloatingToIntegral;
10016 else
10017 return true;
10018 } else if (VectorEltTy->isRealFloatingType()) {
10019 if (ScalarTy->isRealFloatingType()) {
10020
10021 // Reject cases where the scalar type is not a constant and has a higher
10022 // Order than the vector element type.
10023 llvm::APFloat Result(0.0);
10024
10025 // Determine whether this is a constant scalar. In the event that the
10026 // value is dependent (and thus cannot be evaluated by the constant
10027 // evaluator), skip the evaluation. This will then diagnose once the
10028 // expression is instantiated.
10029 bool CstScalar = Scalar->get()->isValueDependent() ||
10030 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10031 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10032 if (!CstScalar && Order < 0)
10033 return true;
10034
10035 // If the scalar cannot be safely casted to the vector element type,
10036 // reject it.
10037 if (CstScalar) {
10038 bool Truncated = false;
10039 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10040 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10041 if (Truncated)
10042 return true;
10043 }
10044
10045 ScalarCast = CK_FloatingCast;
10046 } else if (ScalarTy->isIntegralType(S.Context)) {
10047 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10048 return true;
10049
10050 ScalarCast = CK_IntegralToFloating;
10051 } else
10052 return true;
10053 } else if (ScalarTy->isEnumeralType())
10054 return true;
10055
10056 // Adjust scalar if desired.
10057 if (ScalarCast != CK_NoOp)
10058 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10059 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10060 return false;
10061}
10062
10064 SourceLocation Loc, bool IsCompAssign,
10065 bool AllowBothBool,
10066 bool AllowBoolConversions,
10067 bool AllowBoolOperation,
10068 bool ReportInvalid) {
10069 if (!IsCompAssign) {
10071 if (LHS.isInvalid())
10072 return QualType();
10073 }
10075 if (RHS.isInvalid())
10076 return QualType();
10077
10078 // For conversion purposes, we ignore any qualifiers.
10079 // For example, "const float" and "float" are equivalent.
10080 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10081 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10082
10083 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10084 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10085 assert(LHSVecType || RHSVecType);
10086
10087 // AltiVec-style "vector bool op vector bool" combinations are allowed
10088 // for some operators but not others.
10089 if (!AllowBothBool && LHSVecType &&
10090 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10091 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10092 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10093
10094 // This operation may not be performed on boolean vectors.
10095 if (!AllowBoolOperation &&
10096 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10097 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10098
10099 // If the vector types are identical, return.
10100 if (Context.hasSameType(LHSType, RHSType))
10101 return Context.getCommonSugaredType(LHSType, RHSType);
10102
10103 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10104 if (LHSVecType && RHSVecType &&
10105 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10106 if (isa<ExtVectorType>(LHSVecType)) {
10107 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10108 return LHSType;
10109 }
10110
10111 if (!IsCompAssign)
10112 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10113 return RHSType;
10114 }
10115
10116 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10117 // can be mixed, with the result being the non-bool type. The non-bool
10118 // operand must have integer element type.
10119 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10120 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10121 (Context.getTypeSize(LHSVecType->getElementType()) ==
10122 Context.getTypeSize(RHSVecType->getElementType()))) {
10123 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10124 LHSVecType->getElementType()->isIntegerType() &&
10125 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10126 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10127 return LHSType;
10128 }
10129 if (!IsCompAssign &&
10130 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10131 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10132 RHSVecType->getElementType()->isIntegerType()) {
10133 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10134 return RHSType;
10135 }
10136 }
10137
10138 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10139 // invalid since the ambiguity can affect the ABI.
10140 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10141 unsigned &SVEorRVV) {
10142 const VectorType *VecType = SecondType->getAs<VectorType>();
10143 SVEorRVV = 0;
10144 if (FirstType->isSizelessBuiltinType() && VecType) {
10147 return true;
10153 SVEorRVV = 1;
10154 return true;
10155 }
10156 }
10157
10158 return false;
10159 };
10160
10161 unsigned SVEorRVV;
10162 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10163 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10164 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10165 << SVEorRVV << LHSType << RHSType;
10166 return QualType();
10167 }
10168
10169 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10170 // invalid since the ambiguity can affect the ABI.
10171 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10172 unsigned &SVEorRVV) {
10173 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10174 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10175
10176 SVEorRVV = 0;
10177 if (FirstVecType && SecondVecType) {
10178 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10179 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10180 SecondVecType->getVectorKind() ==
10182 return true;
10183 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10184 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10185 SecondVecType->getVectorKind() ==
10187 SecondVecType->getVectorKind() ==
10189 SecondVecType->getVectorKind() ==
10191 SVEorRVV = 1;
10192 return true;
10193 }
10194 }
10195 return false;
10196 }
10197
10198 if (SecondVecType &&
10199 SecondVecType->getVectorKind() == VectorKind::Generic) {
10200 if (FirstType->isSVESizelessBuiltinType())
10201 return true;
10202 if (FirstType->isRVVSizelessBuiltinType()) {
10203 SVEorRVV = 1;
10204 return true;
10205 }
10206 }
10207
10208 return false;
10209 };
10210
10211 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10212 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10213 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10214 << SVEorRVV << LHSType << RHSType;
10215 return QualType();
10216 }
10217
10218 // If there's a vector type and a scalar, try to convert the scalar to
10219 // the vector element type and splat.
10220 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10221 if (!RHSVecType) {
10222 if (isa<ExtVectorType>(LHSVecType)) {
10223 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10224 LHSVecType->getElementType(), LHSType,
10225 DiagID))
10226 return LHSType;
10227 } else {
10228 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10229 return LHSType;
10230 }
10231 }
10232 if (!LHSVecType) {
10233 if (isa<ExtVectorType>(RHSVecType)) {
10234 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10235 LHSType, RHSVecType->getElementType(),
10236 RHSType, DiagID))
10237 return RHSType;
10238 } else {
10239 if (LHS.get()->isLValue() ||
10240 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10241 return RHSType;
10242 }
10243 }
10244
10245 // FIXME: The code below also handles conversion between vectors and
10246 // non-scalars, we should break this down into fine grained specific checks
10247 // and emit proper diagnostics.
10248 QualType VecType = LHSVecType ? LHSType : RHSType;
10249 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10250 QualType OtherType = LHSVecType ? RHSType : LHSType;
10251 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10252 if (isLaxVectorConversion(OtherType, VecType)) {
10253 if (Context.getTargetInfo().getTriple().isPPC() &&
10254 anyAltivecTypes(RHSType, LHSType) &&
10255 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10256 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10257 // If we're allowing lax vector conversions, only the total (data) size
10258 // needs to be the same. For non compound assignment, if one of the types is
10259 // scalar, the result is always the vector type.
10260 if (!IsCompAssign) {
10261 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10262 return VecType;
10263 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10264 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10265 // type. Note that this is already done by non-compound assignments in
10266 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10267 // <1 x T> -> T. The result is also a vector type.
10268 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10269 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10270 ExprResult *RHSExpr = &RHS;
10271 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10272 return VecType;
10273 }
10274 }
10275
10276 // Okay, the expression is invalid.
10277
10278 // If there's a non-vector, non-real operand, diagnose that.
10279 if ((!RHSVecType && !RHSType->isRealType()) ||
10280 (!LHSVecType && !LHSType->isRealType())) {
10281 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10282 << LHSType << RHSType
10283 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10284 return QualType();
10285 }
10286
10287 // OpenCL V1.1 6.2.6.p1:
10288 // If the operands are of more than one vector type, then an error shall
10289 // occur. Implicit conversions between vector types are not permitted, per
10290 // section 6.2.1.
10291 if (getLangOpts().OpenCL &&
10292 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10293 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10294 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10295 << RHSType;
10296 return QualType();
10297 }
10298
10299
10300 // If there is a vector type that is not a ExtVector and a scalar, we reach
10301 // this point if scalar could not be converted to the vector's element type
10302 // without truncation.
10303 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10304 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10305 QualType Scalar = LHSVecType ? RHSType : LHSType;
10306 QualType Vector = LHSVecType ? LHSType : RHSType;
10307 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10308 Diag(Loc,
10309 diag::err_typecheck_vector_not_convertable_implict_truncation)
10310 << ScalarOrVector << Scalar << Vector;
10311
10312 return QualType();
10313 }
10314
10315 // Otherwise, use the generic diagnostic.
10316 Diag(Loc, DiagID)
10317 << LHSType << RHSType
10318 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10319 return QualType();
10320}
10321
10324 bool IsCompAssign,
10325 ArithConvKind OperationKind) {
10326 if (!IsCompAssign) {
10328 if (LHS.isInvalid())
10329 return QualType();
10330 }
10332 if (RHS.isInvalid())
10333 return QualType();
10334
10335 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10336 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10337
10338 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10339 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10340
10341 unsigned DiagID = diag::err_typecheck_invalid_operands;
10342 if ((OperationKind == ACK_Arithmetic) &&
10343 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10344 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10345 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10346 << RHS.get()->getSourceRange();
10347 return QualType();
10348 }
10349
10350 if (Context.hasSameType(LHSType, RHSType))
10351 return LHSType;
10352
10353 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10354 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10355 return LHSType;
10356 }
10357 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10358 if (LHS.get()->isLValue() ||
10359 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10360 return RHSType;
10361 }
10362
10363 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10364 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10365 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10366 << LHSType << RHSType << LHS.get()->getSourceRange()
10367 << RHS.get()->getSourceRange();
10368 return QualType();
10369 }
10370
10371 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10372 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10373 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10374 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10375 << LHSType << RHSType << LHS.get()->getSourceRange()
10376 << RHS.get()->getSourceRange();
10377 return QualType();
10378 }
10379
10380 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10381 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10382 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10383 bool ScalarOrVector =
10384 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10385
10386 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10387 << ScalarOrVector << Scalar << Vector;
10388
10389 return QualType();
10390 }
10391
10392 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10393 << RHS.get()->getSourceRange();
10394 return QualType();
10395}
10396
10397// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10398// expression. These are mainly cases where the null pointer is used as an
10399// integer instead of a pointer.
10401 SourceLocation Loc, bool IsCompare) {
10402 // The canonical way to check for a GNU null is with isNullPointerConstant,
10403 // but we use a bit of a hack here for speed; this is a relatively
10404 // hot path, and isNullPointerConstant is slow.
10405 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10406 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10407
10408 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10409
10410 // Avoid analyzing cases where the result will either be invalid (and
10411 // diagnosed as such) or entirely valid and not something to warn about.
10412 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10413 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10414 return;
10415
10416 // Comparison operations would not make sense with a null pointer no matter
10417 // what the other expression is.
10418 if (!IsCompare) {
10419 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10420 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10421 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10422 return;
10423 }
10424
10425 // The rest of the operations only make sense with a null pointer
10426 // if the other expression is a pointer.
10427 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10428 NonNullType->canDecayToPointerType())
10429 return;
10430
10431 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10432 << LHSNull /* LHS is NULL */ << NonNullType
10433 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10434}
10435
10438 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10439 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10440 if (!LUE || !RUE)
10441 return;
10442 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10443 RUE->getKind() != UETT_SizeOf)
10444 return;
10445
10446 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10447 QualType LHSTy = LHSArg->getType();
10448 QualType RHSTy;
10449
10450 if (RUE->isArgumentType())
10451 RHSTy = RUE->getArgumentType().getNonReferenceType();
10452 else
10453 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10454
10455 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10456 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10457 return;
10458
10459 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10460 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10461 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10462 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10463 << LHSArgDecl;
10464 }
10465 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10466 QualType ArrayElemTy = ArrayTy->getElementType();
10467 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10468 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10469 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10470 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10471 return;
10472 S.Diag(Loc, diag::warn_division_sizeof_array)
10473 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10474 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10475 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10476 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10477 << LHSArgDecl;
10478 }
10479
10480 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10481 }
10482}
10483
10485 ExprResult &RHS,
10486 SourceLocation Loc, bool IsDiv) {
10487 // Check for division/remainder by zero.
10488 Expr::EvalResult RHSValue;
10489 if (!RHS.get()->isValueDependent() &&
10490 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10491 RHSValue.Val.getInt() == 0)
10492 S.DiagRuntimeBehavior(Loc, RHS.get(),
10493 S.PDiag(diag::warn_remainder_division_by_zero)
10494 << IsDiv << RHS.get()->getSourceRange());
10495}
10496
10499 bool IsCompAssign, bool IsDiv) {
10500 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10501
10502 QualType LHSTy = LHS.get()->getType();
10503 QualType RHSTy = RHS.get()->getType();
10504 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10505 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10506 /*AllowBothBool*/ getLangOpts().AltiVec,
10507 /*AllowBoolConversions*/ false,
10508 /*AllowBooleanOperation*/ false,
10509 /*ReportInvalid*/ true);
10510 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10511 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10513 if (!IsDiv &&
10514 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10515 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10516 // For division, only matrix-by-scalar is supported. Other combinations with
10517 // matrix types are invalid.
10518 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10519 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10520
10522 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10523 if (LHS.isInvalid() || RHS.isInvalid())
10524 return QualType();
10525
10526
10527 if (compType.isNull() || !compType->isArithmeticType())
10528 return InvalidOperands(Loc, LHS, RHS);
10529 if (IsDiv) {
10530 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10531 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10532 }
10533 return compType;
10534}
10535
10537 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10538 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10539
10540 if (LHS.get()->getType()->isVectorType() ||
10541 RHS.get()->getType()->isVectorType()) {
10542 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10544 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10545 /*AllowBothBool*/ getLangOpts().AltiVec,
10546 /*AllowBoolConversions*/ false,
10547 /*AllowBooleanOperation*/ false,
10548 /*ReportInvalid*/ true);
10549 return InvalidOperands(Loc, LHS, RHS);
10550 }
10551
10552 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10553 RHS.get()->getType()->isSveVLSBuiltinType()) {
10554 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10556 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10558
10559 return InvalidOperands(Loc, LHS, RHS);
10560 }
10561
10563 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10564 if (LHS.isInvalid() || RHS.isInvalid())
10565 return QualType();
10566
10567 if (compType.isNull() || !compType->isIntegerType())
10568 return InvalidOperands(Loc, LHS, RHS);
10569 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10570 return compType;
10571}
10572
10573/// Diagnose invalid arithmetic on two void pointers.
10575 Expr *LHSExpr, Expr *RHSExpr) {
10576 S.Diag(Loc, S.getLangOpts().CPlusPlus
10577 ? diag::err_typecheck_pointer_arith_void_type
10578 : diag::ext_gnu_void_ptr)
10579 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10580 << RHSExpr->getSourceRange();
10581}
10582
10583/// Diagnose invalid arithmetic on a void pointer.
10585 Expr *Pointer) {
10586 S.Diag(Loc, S.getLangOpts().CPlusPlus
10587 ? diag::err_typecheck_pointer_arith_void_type
10588 : diag::ext_gnu_void_ptr)
10589 << 0 /* one pointer */ << Pointer->getSourceRange();
10590}
10591
10592/// Diagnose invalid arithmetic on a null pointer.
10593///
10594/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10595/// idiom, which we recognize as a GNU extension.
10596///
10598 Expr *Pointer, bool IsGNUIdiom) {
10599 if (IsGNUIdiom)
10600 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10601 << Pointer->getSourceRange();
10602 else
10603 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10604 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10605}
10606
10607/// Diagnose invalid subraction on a null pointer.
10608///
10610 Expr *Pointer, bool BothNull) {
10611 // Null - null is valid in C++ [expr.add]p7
10612 if (BothNull && S.getLangOpts().CPlusPlus)
10613 return;
10614
10615 // Is this s a macro from a system header?
10617 return;
10618
10620 S.PDiag(diag::warn_pointer_sub_null_ptr)
10621 << S.getLangOpts().CPlusPlus
10622 << Pointer->getSourceRange());
10623}
10624
10625/// Diagnose invalid arithmetic on two function pointers.
10627 Expr *LHS, Expr *RHS) {
10628 assert(LHS->getType()->isAnyPointerType());
10629 assert(RHS->getType()->isAnyPointerType());
10630 S.Diag(Loc, S.getLangOpts().CPlusPlus
10631 ? diag::err_typecheck_pointer_arith_function_type
10632 : diag::ext_gnu_ptr_func_arith)
10633 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10634 // We only show the second type if it differs from the first.
10636 RHS->getType())
10637 << RHS->getType()->getPointeeType()
10638 << LHS->getSourceRange() << RHS->getSourceRange();
10639}
10640
10641/// Diagnose invalid arithmetic on a function pointer.
10643 Expr *Pointer) {
10644 assert(Pointer->getType()->isAnyPointerType());
10645 S.Diag(Loc, S.getLangOpts().CPlusPlus
10646 ? diag::err_typecheck_pointer_arith_function_type
10647 : diag::ext_gnu_ptr_func_arith)
10648 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10649 << 0 /* one pointer, so only one type */
10650 << Pointer->getSourceRange();
10651}
10652
10653/// Emit error if Operand is incomplete pointer type
10654///
10655/// \returns True if pointer has incomplete type
10657 Expr *Operand) {
10658 QualType ResType = Operand->getType();
10659 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10660 ResType = ResAtomicType->getValueType();
10661
10662 assert(ResType->isAnyPointerType());
10663 QualType PointeeTy = ResType->getPointeeType();
10664 return S.RequireCompleteSizedType(
10665 Loc, PointeeTy,
10666 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10667 Operand->getSourceRange());
10668}
10669
10670/// Check the validity of an arithmetic pointer operand.
10671///
10672/// If the operand has pointer type, this code will check for pointer types
10673/// which are invalid in arithmetic operations. These will be diagnosed
10674/// appropriately, including whether or not the use is supported as an
10675/// extension.
10676///
10677/// \returns True when the operand is valid to use (even if as an extension).
10679 Expr *Operand) {
10680 QualType ResType = Operand->getType();
10681 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10682 ResType = ResAtomicType->getValueType();
10683
10684 if (!ResType->isAnyPointerType()) return true;
10685
10686 QualType PointeeTy = ResType->getPointeeType();
10687 if (PointeeTy->isVoidType()) {
10689 return !S.getLangOpts().CPlusPlus;
10690 }
10691 if (PointeeTy->isFunctionType()) {
10693 return !S.getLangOpts().CPlusPlus;
10694 }
10695
10696 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10697
10698 return true;
10699}
10700
10701/// Check the validity of a binary arithmetic operation w.r.t. pointer
10702/// operands.
10703///
10704/// This routine will diagnose any invalid arithmetic on pointer operands much
10705/// like \see checkArithmeticOpPointerOperand. However, it has special logic
10706/// for emitting a single diagnostic even for operations where both LHS and RHS
10707/// are (potentially problematic) pointers.
10708///
10709/// \returns True when the operand is valid to use (even if as an extension).
10711 Expr *LHSExpr, Expr *RHSExpr) {
10712 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10713 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10714 if (!isLHSPointer && !isRHSPointer) return true;
10715
10716 QualType LHSPointeeTy, RHSPointeeTy;
10717 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10718 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10719
10720 // if both are pointers check if operation is valid wrt address spaces
10721 if (isLHSPointer && isRHSPointer) {
10722 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10723 S.Diag(Loc,
10724 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10725 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10726 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10727 return false;
10728 }
10729 }
10730
10731 // Check for arithmetic on pointers to incomplete types.
10732 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10733 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10734 if (isLHSVoidPtr || isRHSVoidPtr) {
10735 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10736 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10737 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10738
10739 return !S.getLangOpts().CPlusPlus;
10740 }
10741
10742 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10743 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10744 if (isLHSFuncPtr || isRHSFuncPtr) {
10745 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10746 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10747 RHSExpr);
10748 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10749
10750 return !S.getLangOpts().CPlusPlus;
10751 }
10752
10753 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10754 return false;
10755 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10756 return false;
10757
10758 return true;
10759}
10760
10761/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10762/// literal.
10764 Expr *LHSExpr, Expr *RHSExpr) {
10765 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10766 Expr* IndexExpr = RHSExpr;
10767 if (!StrExpr) {
10768 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10769 IndexExpr = LHSExpr;
10770 }
10771
10772 bool IsStringPlusInt = StrExpr &&
10774 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10775 return;
10776
10777 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10778 Self.Diag(OpLoc, diag::warn_string_plus_int)
10779 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10780
10781 // Only print a fixit for "str" + int, not for int + "str".
10782 if (IndexExpr == RHSExpr) {
10783 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10784 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10785 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10787 << FixItHint::CreateInsertion(EndLoc, "]");
10788 } else
10789 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10790}
10791
10792/// Emit a warning when adding a char literal to a string.
10794 Expr *LHSExpr, Expr *RHSExpr) {
10795 const Expr *StringRefExpr = LHSExpr;
10796 const CharacterLiteral *CharExpr =
10797 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10798
10799 if (!CharExpr) {
10800 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10801 StringRefExpr = RHSExpr;
10802 }
10803
10804 if (!CharExpr || !StringRefExpr)
10805 return;
10806
10807 const QualType StringType = StringRefExpr->getType();
10808
10809 // Return if not a PointerType.
10810 if (!StringType->isAnyPointerType())
10811 return;
10812
10813 // Return if not a CharacterType.
10814 if (!StringType->getPointeeType()->isAnyCharacterType())
10815 return;
10816
10817 ASTContext &Ctx = Self.getASTContext();
10818 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10819
10820 const QualType CharType = CharExpr->getType();
10821 if (!CharType->isAnyCharacterType() &&
10822 CharType->isIntegerType() &&
10823 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10824 Self.Diag(OpLoc, diag::warn_string_plus_char)
10825 << DiagRange << Ctx.CharTy;
10826 } else {
10827 Self.Diag(OpLoc, diag::warn_string_plus_char)
10828 << DiagRange << CharExpr->getType();
10829 }
10830
10831 // Only print a fixit for str + char, not for char + str.
10832 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10833 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10834 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10835 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10837 << FixItHint::CreateInsertion(EndLoc, "]");
10838 } else {
10839 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10840 }
10841}
10842
10843/// Emit error when two pointers are incompatible.
10845 Expr *LHSExpr, Expr *RHSExpr) {
10846 assert(LHSExpr->getType()->isAnyPointerType());
10847 assert(RHSExpr->getType()->isAnyPointerType());
10848 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10849 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10850 << RHSExpr->getSourceRange();
10851}
10852
10853// C99 6.5.6
10856 QualType* CompLHSTy) {
10857 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10858
10859 if (LHS.get()->getType()->isVectorType() ||
10860 RHS.get()->getType()->isVectorType()) {
10861 QualType compType =
10862 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
10863 /*AllowBothBool*/ getLangOpts().AltiVec,
10864 /*AllowBoolConversions*/ getLangOpts().ZVector,
10865 /*AllowBooleanOperation*/ false,
10866 /*ReportInvalid*/ true);
10867 if (CompLHSTy) *CompLHSTy = compType;
10868 return compType;
10869 }
10870
10871 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10872 RHS.get()->getType()->isSveVLSBuiltinType()) {
10873 QualType compType =
10874 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
10875 if (CompLHSTy)
10876 *CompLHSTy = compType;
10877 return compType;
10878 }
10879
10880 if (LHS.get()->getType()->isConstantMatrixType() ||
10881 RHS.get()->getType()->isConstantMatrixType()) {
10882 QualType compType =
10883 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10884 if (CompLHSTy)
10885 *CompLHSTy = compType;
10886 return compType;
10887 }
10888
10890 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10891 if (LHS.isInvalid() || RHS.isInvalid())
10892 return QualType();
10893
10894 // Diagnose "string literal" '+' int and string '+' "char literal".
10895 if (Opc == BO_Add) {
10896 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10897 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10898 }
10899
10900 // handle the common case first (both operands are arithmetic).
10901 if (!compType.isNull() && compType->isArithmeticType()) {
10902 if (CompLHSTy) *CompLHSTy = compType;
10903 return compType;
10904 }
10905
10906 // Type-checking. Ultimately the pointer's going to be in PExp;
10907 // note that we bias towards the LHS being the pointer.
10908 Expr *PExp = LHS.get(), *IExp = RHS.get();
10909
10910 bool isObjCPointer;
10911 if (PExp->getType()->isPointerType()) {
10912 isObjCPointer = false;
10913 } else if (PExp->getType()->isObjCObjectPointerType()) {
10914 isObjCPointer = true;
10915 } else {
10916 std::swap(PExp, IExp);
10917 if (PExp->getType()->isPointerType()) {
10918 isObjCPointer = false;
10919 } else if (PExp->getType()->isObjCObjectPointerType()) {
10920 isObjCPointer = true;
10921 } else {
10922 return InvalidOperands(Loc, LHS, RHS);
10923 }
10924 }
10925 assert(PExp->getType()->isAnyPointerType());
10926
10927 if (!IExp->getType()->isIntegerType())
10928 return InvalidOperands(Loc, LHS, RHS);
10929
10930 // Adding to a null pointer results in undefined behavior.
10933 // In C++ adding zero to a null pointer is defined.
10934 Expr::EvalResult KnownVal;
10935 if (!getLangOpts().CPlusPlus ||
10936 (!IExp->isValueDependent() &&
10937 (!IExp->EvaluateAsInt(KnownVal, Context) ||
10938 KnownVal.Val.getInt() != 0))) {
10939 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10941 Context, BO_Add, PExp, IExp);
10942 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10943 }
10944 }
10945
10946 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10947 return QualType();
10948
10949 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10950 return QualType();
10951
10952 // Arithmetic on label addresses is normally allowed, except when we add
10953 // a ptrauth signature to the addresses.
10954 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
10955 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
10956 << /*addition*/ 1;
10957 return QualType();
10958 }
10959
10960 // Check array bounds for pointer arithemtic
10961 CheckArrayAccess(PExp, IExp);
10962
10963 if (CompLHSTy) {
10965 if (LHSTy.isNull()) {
10966 LHSTy = LHS.get()->getType();
10968 LHSTy = Context.getPromotedIntegerType(LHSTy);
10969 }
10970 *CompLHSTy = LHSTy;
10971 }
10972
10973 return PExp->getType();
10974}
10975
10976// C99 6.5.6
10979 QualType* CompLHSTy) {
10980 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10981
10982 if (LHS.get()->getType()->isVectorType() ||
10983 RHS.get()->getType()->isVectorType()) {
10984 QualType compType =
10985 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
10986 /*AllowBothBool*/ getLangOpts().AltiVec,
10987 /*AllowBoolConversions*/ getLangOpts().ZVector,
10988 /*AllowBooleanOperation*/ false,
10989 /*ReportInvalid*/ true);
10990 if (CompLHSTy) *CompLHSTy = compType;
10991 return compType;
10992 }
10993
10994 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10995 RHS.get()->getType()->isSveVLSBuiltinType()) {
10996 QualType compType =
10997 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
10998 if (CompLHSTy)
10999 *CompLHSTy = compType;
11000 return compType;
11001 }
11002
11003 if (LHS.get()->getType()->isConstantMatrixType() ||
11004 RHS.get()->getType()->isConstantMatrixType()) {
11005 QualType compType =
11006 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11007 if (CompLHSTy)
11008 *CompLHSTy = compType;
11009 return compType;
11010 }
11011
11013 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11014 if (LHS.isInvalid() || RHS.isInvalid())
11015 return QualType();
11016
11017 // Enforce type constraints: C99 6.5.6p3.
11018
11019 // Handle the common case first (both operands are arithmetic).
11020 if (!compType.isNull() && compType->isArithmeticType()) {
11021 if (CompLHSTy) *CompLHSTy = compType;
11022 return compType;
11023 }
11024
11025 // Either ptr - int or ptr - ptr.
11026 if (LHS.get()->getType()->isAnyPointerType()) {
11027 QualType lpointee = LHS.get()->getType()->getPointeeType();
11028
11029 // Diagnose bad cases where we step over interface counts.
11030 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11031 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11032 return QualType();
11033
11034 // Arithmetic on label addresses is normally allowed, except when we add
11035 // a ptrauth signature to the addresses.
11036 if (isa<AddrLabelExpr>(LHS.get()) &&
11037 getLangOpts().PointerAuthIndirectGotos) {
11038 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11039 << /*subtraction*/ 0;
11040 return QualType();
11041 }
11042
11043 // The result type of a pointer-int computation is the pointer type.
11044 if (RHS.get()->getType()->isIntegerType()) {
11045 // Subtracting from a null pointer should produce a warning.
11046 // The last argument to the diagnose call says this doesn't match the
11047 // GNU int-to-pointer idiom.
11050 // In C++ adding zero to a null pointer is defined.
11051 Expr::EvalResult KnownVal;
11052 if (!getLangOpts().CPlusPlus ||
11053 (!RHS.get()->isValueDependent() &&
11054 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11055 KnownVal.Val.getInt() != 0))) {
11056 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11057 }
11058 }
11059
11060 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11061 return QualType();
11062
11063 // Check array bounds for pointer arithemtic
11064 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11065 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11066
11067 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11068 return LHS.get()->getType();
11069 }
11070
11071 // Handle pointer-pointer subtractions.
11072 if (const PointerType *RHSPTy
11073 = RHS.get()->getType()->getAs<PointerType>()) {
11074 QualType rpointee = RHSPTy->getPointeeType();
11075
11076 if (getLangOpts().CPlusPlus) {
11077 // Pointee types must be the same: C++ [expr.add]
11078 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11079 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11080 }
11081 } else {
11082 // Pointee types must be compatible C99 6.5.6p3
11086 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11087 return QualType();
11088 }
11089 }
11090
11092 LHS.get(), RHS.get()))
11093 return QualType();
11094
11095 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11097 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11099
11100 // Subtracting nullptr or from nullptr is suspect
11101 if (LHSIsNullPtr)
11102 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11103 if (RHSIsNullPtr)
11104 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11105
11106 // The pointee type may have zero size. As an extension, a structure or
11107 // union may have zero size or an array may have zero length. In this
11108 // case subtraction does not make sense.
11109 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11110 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11111 if (ElementSize.isZero()) {
11112 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11113 << rpointee.getUnqualifiedType()
11114 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11115 }
11116 }
11117
11118 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11119 return Context.getPointerDiffType();
11120 }
11121 }
11122
11123 return InvalidOperands(Loc, LHS, RHS);
11124}
11125
11127 if (const EnumType *ET = T->getAs<EnumType>())
11128 return ET->getDecl()->isScoped();
11129 return false;
11130}
11131
11134 QualType LHSType) {
11135 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11136 // so skip remaining warnings as we don't want to modify values within Sema.
11137 if (S.getLangOpts().OpenCL)
11138 return;
11139
11140 // Check right/shifter operand
11141 Expr::EvalResult RHSResult;
11142 if (RHS.get()->isValueDependent() ||
11143 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11144 return;
11145 llvm::APSInt Right = RHSResult.Val.getInt();
11146
11147 if (Right.isNegative()) {
11148 S.DiagRuntimeBehavior(Loc, RHS.get(),
11149 S.PDiag(diag::warn_shift_negative)
11150 << RHS.get()->getSourceRange());
11151 return;
11152 }
11153
11154 QualType LHSExprType = LHS.get()->getType();
11155 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11156 if (LHSExprType->isBitIntType())
11157 LeftSize = S.Context.getIntWidth(LHSExprType);
11158 else if (LHSExprType->isFixedPointType()) {
11159 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11160 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11161 }
11162 if (Right.uge(LeftSize)) {
11163 S.DiagRuntimeBehavior(Loc, RHS.get(),
11164 S.PDiag(diag::warn_shift_gt_typewidth)
11165 << RHS.get()->getSourceRange());
11166 return;
11167 }
11168
11169 // FIXME: We probably need to handle fixed point types specially here.
11170 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11171 return;
11172
11173 // When left shifting an ICE which is signed, we can check for overflow which
11174 // according to C++ standards prior to C++2a has undefined behavior
11175 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11176 // more than the maximum value representable in the result type, so never
11177 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11178 // expression is still probably a bug.)
11179 Expr::EvalResult LHSResult;
11180 if (LHS.get()->isValueDependent() ||
11182 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11183 return;
11184 llvm::APSInt Left = LHSResult.Val.getInt();
11185
11186 // Don't warn if signed overflow is defined, then all the rest of the
11187 // diagnostics will not be triggered because the behavior is defined.
11188 // Also don't warn in C++20 mode (and newer), as signed left shifts
11189 // always wrap and never overflow.
11190 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11191 return;
11192
11193 // If LHS does not have a non-negative value then, the
11194 // behavior is undefined before C++2a. Warn about it.
11195 if (Left.isNegative()) {
11196 S.DiagRuntimeBehavior(Loc, LHS.get(),
11197 S.PDiag(diag::warn_shift_lhs_negative)
11198 << LHS.get()->getSourceRange());
11199 return;
11200 }
11201
11202 llvm::APInt ResultBits =
11203 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11204 if (ResultBits.ule(LeftSize))
11205 return;
11206 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11207 Result = Result.shl(Right);
11208
11209 // Print the bit representation of the signed integer as an unsigned
11210 // hexadecimal number.
11211 SmallString<40> HexResult;
11212 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11213
11214 // If we are only missing a sign bit, this is less likely to result in actual
11215 // bugs -- if the result is cast back to an unsigned type, it will have the
11216 // expected value. Thus we place this behind a different warning that can be
11217 // turned off separately if needed.
11218 if (ResultBits - 1 == LeftSize) {
11219 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11220 << HexResult << LHSType
11221 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11222 return;
11223 }
11224
11225 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11226 << HexResult.str() << Result.getSignificantBits() << LHSType
11227 << Left.getBitWidth() << LHS.get()->getSourceRange()
11228 << RHS.get()->getSourceRange();
11229}
11230
11231/// Return the resulting type when a vector is shifted
11232/// by a scalar or vector shift amount.
11234 SourceLocation Loc, bool IsCompAssign) {
11235 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11236 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11237 !LHS.get()->getType()->isVectorType()) {
11238 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11239 << RHS.get()->getType() << LHS.get()->getType()
11240 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11241 return QualType();
11242 }
11243
11244 if (!IsCompAssign) {
11245 LHS = S.UsualUnaryConversions(LHS.get());
11246 if (LHS.isInvalid()) return QualType();
11247 }
11248
11249 RHS = S.UsualUnaryConversions(RHS.get());
11250 if (RHS.isInvalid()) return QualType();
11251
11252 QualType LHSType = LHS.get()->getType();
11253 // Note that LHS might be a scalar because the routine calls not only in
11254 // OpenCL case.
11255 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11256 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11257
11258 // Note that RHS might not be a vector.
11259 QualType RHSType = RHS.get()->getType();
11260 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11261 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11262
11263 // Do not allow shifts for boolean vectors.
11264 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11265 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11266 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11267 << LHS.get()->getType() << RHS.get()->getType()
11268 << LHS.get()->getSourceRange();
11269 return QualType();
11270 }
11271
11272 // The operands need to be integers.
11273 if (!LHSEleType->isIntegerType()) {
11274 S.Diag(Loc, diag::err_typecheck_expect_int)
11275 << LHS.get()->getType() << LHS.get()->getSourceRange();
11276 return QualType();
11277 }
11278
11279 if (!RHSEleType->isIntegerType()) {
11280 S.Diag(Loc, diag::err_typecheck_expect_int)
11281 << RHS.get()->getType() << RHS.get()->getSourceRange();
11282 return QualType();
11283 }
11284
11285 if (!LHSVecTy) {
11286 assert(RHSVecTy);
11287 if (IsCompAssign)
11288 return RHSType;
11289 if (LHSEleType != RHSEleType) {
11290 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11291 LHSEleType = RHSEleType;
11292 }
11293 QualType VecTy =
11294 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11295 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11296 LHSType = VecTy;
11297 } else if (RHSVecTy) {
11298 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11299 // are applied component-wise. So if RHS is a vector, then ensure
11300 // that the number of elements is the same as LHS...
11301 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11302 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11303 << LHS.get()->getType() << RHS.get()->getType()
11304 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11305 return QualType();
11306 }
11307 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11308 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11309 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11310 if (LHSBT != RHSBT &&
11311 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11312 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11313 << LHS.get()->getType() << RHS.get()->getType()
11314 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11315 }
11316 }
11317 } else {
11318 // ...else expand RHS to match the number of elements in LHS.
11319 QualType VecTy =
11320 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11321 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11322 }
11323
11324 return LHSType;
11325}
11326
11329 bool IsCompAssign) {
11330 if (!IsCompAssign) {
11331 LHS = S.UsualUnaryConversions(LHS.get());
11332 if (LHS.isInvalid())
11333 return QualType();
11334 }
11335
11336 RHS = S.UsualUnaryConversions(RHS.get());
11337 if (RHS.isInvalid())
11338 return QualType();
11339
11340 QualType LHSType = LHS.get()->getType();
11341 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11342 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11343 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11344 : LHSType;
11345
11346 // Note that RHS might not be a vector
11347 QualType RHSType = RHS.get()->getType();
11348 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11349 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11350 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11351 : RHSType;
11352
11353 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11354 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11355 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11356 << LHSType << RHSType << LHS.get()->getSourceRange();
11357 return QualType();
11358 }
11359
11360 if (!LHSEleType->isIntegerType()) {
11361 S.Diag(Loc, diag::err_typecheck_expect_int)
11362 << LHS.get()->getType() << LHS.get()->getSourceRange();
11363 return QualType();
11364 }
11365
11366 if (!RHSEleType->isIntegerType()) {
11367 S.Diag(Loc, diag::err_typecheck_expect_int)
11368 << RHS.get()->getType() << RHS.get()->getSourceRange();
11369 return QualType();
11370 }
11371
11372 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11373 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11374 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11375 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11376 << LHSType << RHSType << LHS.get()->getSourceRange()
11377 << RHS.get()->getSourceRange();
11378 return QualType();
11379 }
11380
11381 if (!LHSType->isSveVLSBuiltinType()) {
11382 assert(RHSType->isSveVLSBuiltinType());
11383 if (IsCompAssign)
11384 return RHSType;
11385 if (LHSEleType != RHSEleType) {
11386 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11387 LHSEleType = RHSEleType;
11388 }
11389 const llvm::ElementCount VecSize =
11390 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11391 QualType VecTy =
11392 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11393 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11394 LHSType = VecTy;
11395 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11396 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11397 S.Context.getTypeSize(LHSBuiltinTy)) {
11398 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11399 << LHSType << RHSType << LHS.get()->getSourceRange()
11400 << RHS.get()->getSourceRange();
11401 return QualType();
11402 }
11403 } else {
11404 const llvm::ElementCount VecSize =
11405 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11406 if (LHSEleType != RHSEleType) {
11407 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11408 RHSEleType = LHSEleType;
11409 }
11410 QualType VecTy =
11411 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11412 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11413 }
11414
11415 return LHSType;
11416}
11417
11418// C99 6.5.7
11421 bool IsCompAssign) {
11422 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11423
11424 // Vector shifts promote their scalar inputs to vector type.
11425 if (LHS.get()->getType()->isVectorType() ||
11426 RHS.get()->getType()->isVectorType()) {
11427 if (LangOpts.ZVector) {
11428 // The shift operators for the z vector extensions work basically
11429 // like general shifts, except that neither the LHS nor the RHS is
11430 // allowed to be a "vector bool".
11431 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11432 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11433 return InvalidOperands(Loc, LHS, RHS);
11434 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11435 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11436 return InvalidOperands(Loc, LHS, RHS);
11437 }
11438 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11439 }
11440
11441 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11442 RHS.get()->getType()->isSveVLSBuiltinType())
11443 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11444
11445 // Shifts don't perform usual arithmetic conversions, they just do integer
11446 // promotions on each operand. C99 6.5.7p3
11447
11448 // For the LHS, do usual unary conversions, but then reset them away
11449 // if this is a compound assignment.
11450 ExprResult OldLHS = LHS;
11451 LHS = UsualUnaryConversions(LHS.get());
11452 if (LHS.isInvalid())
11453 return QualType();
11454 QualType LHSType = LHS.get()->getType();
11455 if (IsCompAssign) LHS = OldLHS;
11456
11457 // The RHS is simpler.
11458 RHS = UsualUnaryConversions(RHS.get());
11459 if (RHS.isInvalid())
11460 return QualType();
11461 QualType RHSType = RHS.get()->getType();
11462
11463 // C99 6.5.7p2: Each of the operands shall have integer type.
11464 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11465 if ((!LHSType->isFixedPointOrIntegerType() &&
11466 !LHSType->hasIntegerRepresentation()) ||
11467 !RHSType->hasIntegerRepresentation())
11468 return InvalidOperands(Loc, LHS, RHS);
11469
11470 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11471 // hasIntegerRepresentation() above instead of this.
11472 if (isScopedEnumerationType(LHSType) ||
11473 isScopedEnumerationType(RHSType)) {
11474 return InvalidOperands(Loc, LHS, RHS);
11475 }
11476 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11477
11478 // "The type of the result is that of the promoted left operand."
11479 return LHSType;
11480}
11481
11482/// Diagnose bad pointer comparisons.
11484 ExprResult &LHS, ExprResult &RHS,
11485 bool IsError) {
11486 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11487 : diag::ext_typecheck_comparison_of_distinct_pointers)
11488 << LHS.get()->getType() << RHS.get()->getType()
11489 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11490}
11491
11492/// Returns false if the pointers are converted to a composite type,
11493/// true otherwise.
11495 ExprResult &LHS, ExprResult &RHS) {
11496 // C++ [expr.rel]p2:
11497 // [...] Pointer conversions (4.10) and qualification
11498 // conversions (4.4) are performed on pointer operands (or on
11499 // a pointer operand and a null pointer constant) to bring
11500 // them to their composite pointer type. [...]
11501 //
11502 // C++ [expr.eq]p1 uses the same notion for (in)equality
11503 // comparisons of pointers.
11504
11505 QualType LHSType = LHS.get()->getType();
11506 QualType RHSType = RHS.get()->getType();
11507 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11508 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11509
11510 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11511 if (T.isNull()) {
11512 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11513 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11514 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11515 else
11516 S.InvalidOperands(Loc, LHS, RHS);
11517 return true;
11518 }
11519
11520 return false;
11521}
11522
11524 ExprResult &LHS,
11525 ExprResult &RHS,
11526 bool IsError) {
11527 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11528 : diag::ext_typecheck_comparison_of_fptr_to_void)
11529 << LHS.get()->getType() << RHS.get()->getType()
11530 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11531}
11532
11534 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11535 case Stmt::ObjCArrayLiteralClass:
11536 case Stmt::ObjCDictionaryLiteralClass:
11537 case Stmt::ObjCStringLiteralClass:
11538 case Stmt::ObjCBoxedExprClass:
11539 return true;
11540 default:
11541 // Note that ObjCBoolLiteral is NOT an object literal!
11542 return false;
11543 }
11544}
11545
11546static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11549
11550 // If this is not actually an Objective-C object, bail out.
11551 if (!Type)
11552 return false;
11553
11554 // Get the LHS object's interface type.
11555 QualType InterfaceType = Type->getPointeeType();
11556
11557 // If the RHS isn't an Objective-C object, bail out.
11558 if (!RHS->getType()->isObjCObjectPointerType())
11559 return false;
11560
11561 // Try to find the -isEqual: method.
11562 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
11563 ObjCMethodDecl *Method =
11564 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
11565 /*IsInstance=*/true);
11566 if (!Method) {
11567 if (Type->isObjCIdType()) {
11568 // For 'id', just check the global pool.
11569 Method =
11571 /*receiverId=*/true);
11572 } else {
11573 // Check protocols.
11574 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
11575 /*IsInstance=*/true);
11576 }
11577 }
11578
11579 if (!Method)
11580 return false;
11581
11582 QualType T = Method->parameters()[0]->getType();
11583 if (!T->isObjCObjectPointerType())
11584 return false;
11585
11586 QualType R = Method->getReturnType();
11587 if (!R->isScalarType())
11588 return false;
11589
11590 return true;
11591}
11592
11594 ExprResult &LHS, ExprResult &RHS,
11596 Expr *Literal;
11597 Expr *Other;
11598 if (isObjCObjectLiteral(LHS)) {
11599 Literal = LHS.get();
11600 Other = RHS.get();
11601 } else {
11602 Literal = RHS.get();
11603 Other = LHS.get();
11604 }
11605
11606 // Don't warn on comparisons against nil.
11607 Other = Other->IgnoreParenCasts();
11608 if (Other->isNullPointerConstant(S.getASTContext(),
11610 return;
11611
11612 // This should be kept in sync with warn_objc_literal_comparison.
11613 // LK_String should always be after the other literals, since it has its own
11614 // warning flag.
11615 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
11616 assert(LiteralKind != SemaObjC::LK_Block);
11617 if (LiteralKind == SemaObjC::LK_None) {
11618 llvm_unreachable("Unknown Objective-C object literal kind");
11619 }
11620
11621 if (LiteralKind == SemaObjC::LK_String)
11622 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11623 << Literal->getSourceRange();
11624 else
11625 S.Diag(Loc, diag::warn_objc_literal_comparison)
11626 << LiteralKind << Literal->getSourceRange();
11627
11629 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11630 SourceLocation Start = LHS.get()->getBeginLoc();
11632 CharSourceRange OpRange =
11634
11635 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11636 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11637 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11638 << FixItHint::CreateInsertion(End, "]");
11639 }
11640}
11641
11642/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11645 BinaryOperatorKind Opc) {
11646 // Check that left hand side is !something.
11647 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11648 if (!UO || UO->getOpcode() != UO_LNot) return;
11649
11650 // Only check if the right hand side is non-bool arithmetic type.
11651 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11652
11653 // Make sure that the something in !something is not bool.
11654 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11655 if (SubExpr->isKnownToHaveBooleanValue()) return;
11656
11657 // Emit warning.
11658 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11659 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11660 << Loc << IsBitwiseOp;
11661
11662 // First note suggest !(x < y)
11663 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11664 SourceLocation FirstClose = RHS.get()->getEndLoc();
11665 FirstClose = S.getLocForEndOfToken(FirstClose);
11666 if (FirstClose.isInvalid())
11667 FirstOpen = SourceLocation();
11668 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11669 << IsBitwiseOp
11670 << FixItHint::CreateInsertion(FirstOpen, "(")
11671 << FixItHint::CreateInsertion(FirstClose, ")");
11672
11673 // Second note suggests (!x) < y
11674 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11675 SourceLocation SecondClose = LHS.get()->getEndLoc();
11676 SecondClose = S.getLocForEndOfToken(SecondClose);
11677 if (SecondClose.isInvalid())
11678 SecondOpen = SourceLocation();
11679 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11680 << FixItHint::CreateInsertion(SecondOpen, "(")
11681 << FixItHint::CreateInsertion(SecondClose, ")");
11682}
11683
11684// Returns true if E refers to a non-weak array.
11685static bool checkForArray(const Expr *E) {
11686 const ValueDecl *D = nullptr;
11687 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11688 D = DR->getDecl();
11689 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11690 if (Mem->isImplicitAccess())
11691 D = Mem->getMemberDecl();
11692 }
11693 if (!D)
11694 return false;
11695 return D->getType()->isArrayType() && !D->isWeak();
11696}
11697
11698/// Diagnose some forms of syntactically-obvious tautological comparison.
11700 Expr *LHS, Expr *RHS,
11701 BinaryOperatorKind Opc) {
11702 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11703 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11704
11705 QualType LHSType = LHS->getType();
11706 QualType RHSType = RHS->getType();
11707 if (LHSType->hasFloatingRepresentation() ||
11708 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11710 return;
11711
11712 // WebAssembly Tables cannot be compared, therefore shouldn't emit
11713 // Tautological diagnostics.
11714 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
11715 return;
11716
11717 // Comparisons between two array types are ill-formed for operator<=>, so
11718 // we shouldn't emit any additional warnings about it.
11719 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11720 return;
11721
11722 // For non-floating point types, check for self-comparisons of the form
11723 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11724 // often indicate logic errors in the program.
11725 //
11726 // NOTE: Don't warn about comparison expressions resulting from macro
11727 // expansion. Also don't warn about comparisons which are only self
11728 // comparisons within a template instantiation. The warnings should catch
11729 // obvious cases in the definition of the template anyways. The idea is to
11730 // warn when the typed comparison operator will always evaluate to the same
11731 // result.
11732
11733 // Used for indexing into %select in warn_comparison_always
11734 enum {
11735 AlwaysConstant,
11736 AlwaysTrue,
11737 AlwaysFalse,
11738 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11739 };
11740
11741 // C++2a [depr.array.comp]:
11742 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11743 // operands of array type are deprecated.
11744 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11745 RHSStripped->getType()->isArrayType()) {
11746 S.Diag(Loc, diag::warn_depr_array_comparison)
11747 << LHS->getSourceRange() << RHS->getSourceRange()
11748 << LHSStripped->getType() << RHSStripped->getType();
11749 // Carry on to produce the tautological comparison warning, if this
11750 // expression is potentially-evaluated, we can resolve the array to a
11751 // non-weak declaration, and so on.
11752 }
11753
11754 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11755 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11756 unsigned Result;
11757 switch (Opc) {
11758 case BO_EQ:
11759 case BO_LE:
11760 case BO_GE:
11761 Result = AlwaysTrue;
11762 break;
11763 case BO_NE:
11764 case BO_LT:
11765 case BO_GT:
11766 Result = AlwaysFalse;
11767 break;
11768 case BO_Cmp:
11769 Result = AlwaysEqual;
11770 break;
11771 default:
11772 Result = AlwaysConstant;
11773 break;
11774 }
11775 S.DiagRuntimeBehavior(Loc, nullptr,
11776 S.PDiag(diag::warn_comparison_always)
11777 << 0 /*self-comparison*/
11778 << Result);
11779 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11780 // What is it always going to evaluate to?
11781 unsigned Result;
11782 switch (Opc) {
11783 case BO_EQ: // e.g. array1 == array2
11784 Result = AlwaysFalse;
11785 break;
11786 case BO_NE: // e.g. array1 != array2
11787 Result = AlwaysTrue;
11788 break;
11789 default: // e.g. array1 <= array2
11790 // The best we can say is 'a constant'
11791 Result = AlwaysConstant;
11792 break;
11793 }
11794 S.DiagRuntimeBehavior(Loc, nullptr,
11795 S.PDiag(diag::warn_comparison_always)
11796 << 1 /*array comparison*/
11797 << Result);
11798 }
11799 }
11800
11801 if (isa<CastExpr>(LHSStripped))
11802 LHSStripped = LHSStripped->IgnoreParenCasts();
11803 if (isa<CastExpr>(RHSStripped))
11804 RHSStripped = RHSStripped->IgnoreParenCasts();
11805
11806 // Warn about comparisons against a string constant (unless the other
11807 // operand is null); the user probably wants string comparison function.
11808 Expr *LiteralString = nullptr;
11809 Expr *LiteralStringStripped = nullptr;
11810 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11811 !RHSStripped->isNullPointerConstant(S.Context,
11813 LiteralString = LHS;
11814 LiteralStringStripped = LHSStripped;
11815 } else if ((isa<StringLiteral>(RHSStripped) ||
11816 isa<ObjCEncodeExpr>(RHSStripped)) &&
11817 !LHSStripped->isNullPointerConstant(S.Context,
11819 LiteralString = RHS;
11820 LiteralStringStripped = RHSStripped;
11821 }
11822
11823 if (LiteralString) {
11824 S.DiagRuntimeBehavior(Loc, nullptr,
11825 S.PDiag(diag::warn_stringcompare)
11826 << isa<ObjCEncodeExpr>(LiteralStringStripped)
11827 << LiteralString->getSourceRange());
11828 }
11829}
11830
11832 switch (CK) {
11833 default: {
11834#ifndef NDEBUG
11835 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11836 << "\n";
11837#endif
11838 llvm_unreachable("unhandled cast kind");
11839 }
11840 case CK_UserDefinedConversion:
11841 return ICK_Identity;
11842 case CK_LValueToRValue:
11843 return ICK_Lvalue_To_Rvalue;
11844 case CK_ArrayToPointerDecay:
11845 return ICK_Array_To_Pointer;
11846 case CK_FunctionToPointerDecay:
11848 case CK_IntegralCast:
11850 case CK_FloatingCast:
11852 case CK_IntegralToFloating:
11853 case CK_FloatingToIntegral:
11854 return ICK_Floating_Integral;
11855 case CK_IntegralComplexCast:
11856 case CK_FloatingComplexCast:
11857 case CK_FloatingComplexToIntegralComplex:
11858 case CK_IntegralComplexToFloatingComplex:
11860 case CK_FloatingComplexToReal:
11861 case CK_FloatingRealToComplex:
11862 case CK_IntegralComplexToReal:
11863 case CK_IntegralRealToComplex:
11864 return ICK_Complex_Real;
11865 case CK_HLSLArrayRValue:
11866 return ICK_HLSL_Array_RValue;
11867 }
11868}
11869
11871 QualType FromType,
11873 // Check for a narrowing implicit conversion.
11876 SCS.setToType(0, FromType);
11877 SCS.setToType(1, ToType);
11878 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11879 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11880
11881 APValue PreNarrowingValue;
11882 QualType PreNarrowingType;
11883 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11884 PreNarrowingType,
11885 /*IgnoreFloatToIntegralConversion*/ true)) {
11887 // Implicit conversion to a narrower type, but the expression is
11888 // value-dependent so we can't tell whether it's actually narrowing.
11889 case NK_Not_Narrowing:
11890 return false;
11891
11893 // Implicit conversion to a narrower type, and the value is not a constant
11894 // expression.
11895 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11896 << /*Constant*/ 1
11897 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11898 return true;
11899
11901 // Implicit conversion to a narrower type, and the value is not a constant
11902 // expression.
11903 case NK_Type_Narrowing:
11904 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11905 << /*Constant*/ 0 << FromType << ToType;
11906 // TODO: It's not a constant expression, but what if the user intended it
11907 // to be? Can we produce notes to help them figure out why it isn't?
11908 return true;
11909 }
11910 llvm_unreachable("unhandled case in switch");
11911}
11912
11914 ExprResult &LHS,
11915 ExprResult &RHS,
11917 QualType LHSType = LHS.get()->getType();
11918 QualType RHSType = RHS.get()->getType();
11919 // Dig out the original argument type and expression before implicit casts
11920 // were applied. These are the types/expressions we need to check the
11921 // [expr.spaceship] requirements against.
11922 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11923 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11924 QualType LHSStrippedType = LHSStripped.get()->getType();
11925 QualType RHSStrippedType = RHSStripped.get()->getType();
11926
11927 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11928 // other is not, the program is ill-formed.
11929 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11930 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11931 return QualType();
11932 }
11933
11934 // FIXME: Consider combining this with checkEnumArithmeticConversions.
11935 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11936 RHSStrippedType->isEnumeralType();
11937 if (NumEnumArgs == 1) {
11938 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11939 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11940 if (OtherTy->hasFloatingRepresentation()) {
11941 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11942 return QualType();
11943 }
11944 }
11945 if (NumEnumArgs == 2) {
11946 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11947 // type E, the operator yields the result of converting the operands
11948 // to the underlying type of E and applying <=> to the converted operands.
11949 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11950 S.InvalidOperands(Loc, LHS, RHS);
11951 return QualType();
11952 }
11953 QualType IntType =
11954 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11955 assert(IntType->isArithmeticType());
11956
11957 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11958 // promote the boolean type, and all other promotable integer types, to
11959 // avoid this.
11960 if (S.Context.isPromotableIntegerType(IntType))
11961 IntType = S.Context.getPromotedIntegerType(IntType);
11962
11963 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11964 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11965 LHSType = RHSType = IntType;
11966 }
11967
11968 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11969 // usual arithmetic conversions are applied to the operands.
11970 QualType Type =
11972 if (LHS.isInvalid() || RHS.isInvalid())
11973 return QualType();
11974 if (Type.isNull())
11975 return S.InvalidOperands(Loc, LHS, RHS);
11976
11977 std::optional<ComparisonCategoryType> CCT =
11979 if (!CCT)
11980 return S.InvalidOperands(Loc, LHS, RHS);
11981
11982 bool HasNarrowing = checkThreeWayNarrowingConversion(
11983 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11984 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11985 RHS.get()->getBeginLoc());
11986 if (HasNarrowing)
11987 return QualType();
11988
11989 assert(!Type.isNull() && "composite type for <=> has not been set");
11990
11993}
11994
11996 ExprResult &RHS,
11998 BinaryOperatorKind Opc) {
11999 if (Opc == BO_Cmp)
12000 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12001
12002 // C99 6.5.8p3 / C99 6.5.9p4
12003 QualType Type =
12005 if (LHS.isInvalid() || RHS.isInvalid())
12006 return QualType();
12007 if (Type.isNull())
12008 return S.InvalidOperands(Loc, LHS, RHS);
12009 assert(Type->isArithmeticType() || Type->isEnumeralType());
12010
12012 return S.InvalidOperands(Loc, LHS, RHS);
12013
12014 // Check for comparisons of floating point operands using != and ==.
12016 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12017
12018 // The result of comparisons is 'bool' in C++, 'int' in C.
12020}
12021
12023 if (!NullE.get()->getType()->isAnyPointerType())
12024 return;
12025 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12026 if (!E.get()->getType()->isAnyPointerType() &&
12030 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12031 if (CL->getValue() == 0)
12032 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12033 << NullValue
12035 NullValue ? "NULL" : "(void *)0");
12036 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12037 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12039 if (T == Context.CharTy)
12040 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12041 << NullValue
12043 NullValue ? "NULL" : "(void *)0");
12044 }
12045 }
12046}
12047
12048// C99 6.5.8, C++ [expr.rel]
12051 BinaryOperatorKind Opc) {
12052 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12053 bool IsThreeWay = Opc == BO_Cmp;
12054 bool IsOrdered = IsRelational || IsThreeWay;
12055 auto IsAnyPointerType = [](ExprResult E) {
12056 QualType Ty = E.get()->getType();
12057 return Ty->isPointerType() || Ty->isMemberPointerType();
12058 };
12059
12060 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12061 // type, array-to-pointer, ..., conversions are performed on both operands to
12062 // bring them to their composite type.
12063 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12064 // any type-related checks.
12065 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12067 if (LHS.isInvalid())
12068 return QualType();
12070 if (RHS.isInvalid())
12071 return QualType();
12072 } else {
12073 LHS = DefaultLvalueConversion(LHS.get());
12074 if (LHS.isInvalid())
12075 return QualType();
12076 RHS = DefaultLvalueConversion(RHS.get());
12077 if (RHS.isInvalid())
12078 return QualType();
12079 }
12080
12081 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12085 }
12086
12087 // Handle vector comparisons separately.
12088 if (LHS.get()->getType()->isVectorType() ||
12089 RHS.get()->getType()->isVectorType())
12090 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12091
12092 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12093 RHS.get()->getType()->isSveVLSBuiltinType())
12094 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12095
12096 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12097 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12098
12099 QualType LHSType = LHS.get()->getType();
12100 QualType RHSType = RHS.get()->getType();
12101 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12102 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12103 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12104
12105 if ((LHSType->isPointerType() &&
12107 (RHSType->isPointerType() &&
12109 return InvalidOperands(Loc, LHS, RHS);
12110
12111 const Expr::NullPointerConstantKind LHSNullKind =
12113 const Expr::NullPointerConstantKind RHSNullKind =
12115 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12116 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12117
12118 auto computeResultTy = [&]() {
12119 if (Opc != BO_Cmp)
12121 assert(getLangOpts().CPlusPlus);
12122 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12123
12124 QualType CompositeTy = LHS.get()->getType();
12125 assert(!CompositeTy->isReferenceType());
12126
12127 std::optional<ComparisonCategoryType> CCT =
12129 if (!CCT)
12130 return InvalidOperands(Loc, LHS, RHS);
12131
12132 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12133 // P0946R0: Comparisons between a null pointer constant and an object
12134 // pointer result in std::strong_equality, which is ill-formed under
12135 // P1959R0.
12136 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12137 << (LHSIsNull ? LHS.get()->getSourceRange()
12138 : RHS.get()->getSourceRange());
12139 return QualType();
12140 }
12141
12144 };
12145
12146 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12147 bool IsEquality = Opc == BO_EQ;
12148 if (RHSIsNull)
12149 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12150 RHS.get()->getSourceRange());
12151 else
12152 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12153 LHS.get()->getSourceRange());
12154 }
12155
12156 if (IsOrdered && LHSType->isFunctionPointerType() &&
12157 RHSType->isFunctionPointerType()) {
12158 // Valid unless a relational comparison of function pointers
12159 bool IsError = Opc == BO_Cmp;
12160 auto DiagID =
12161 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12162 : getLangOpts().CPlusPlus
12163 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12164 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12165 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12166 << RHS.get()->getSourceRange();
12167 if (IsError)
12168 return QualType();
12169 }
12170
12171 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12172 (RHSType->isIntegerType() && !RHSIsNull)) {
12173 // Skip normal pointer conversion checks in this case; we have better
12174 // diagnostics for this below.
12175 } else if (getLangOpts().CPlusPlus) {
12176 // Equality comparison of a function pointer to a void pointer is invalid,
12177 // but we allow it as an extension.
12178 // FIXME: If we really want to allow this, should it be part of composite
12179 // pointer type computation so it works in conditionals too?
12180 if (!IsOrdered &&
12181 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12182 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12183 // This is a gcc extension compatibility comparison.
12184 // In a SFINAE context, we treat this as a hard error to maintain
12185 // conformance with the C++ standard.
12187 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12188
12189 if (isSFINAEContext())
12190 return QualType();
12191
12192 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12193 return computeResultTy();
12194 }
12195
12196 // C++ [expr.eq]p2:
12197 // If at least one operand is a pointer [...] bring them to their
12198 // composite pointer type.
12199 // C++ [expr.spaceship]p6
12200 // If at least one of the operands is of pointer type, [...] bring them
12201 // to their composite pointer type.
12202 // C++ [expr.rel]p2:
12203 // If both operands are pointers, [...] bring them to their composite
12204 // pointer type.
12205 // For <=>, the only valid non-pointer types are arrays and functions, and
12206 // we already decayed those, so this is really the same as the relational
12207 // comparison rule.
12208 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12209 (IsOrdered ? 2 : 1) &&
12210 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12211 RHSType->isObjCObjectPointerType()))) {
12212 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12213 return QualType();
12214 return computeResultTy();
12215 }
12216 } else if (LHSType->isPointerType() &&
12217 RHSType->isPointerType()) { // C99 6.5.8p2
12218 // All of the following pointer-related warnings are GCC extensions, except
12219 // when handling null pointer constants.
12220 QualType LCanPointeeTy =
12222 QualType RCanPointeeTy =
12224
12225 // C99 6.5.9p2 and C99 6.5.8p2
12226 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12227 RCanPointeeTy.getUnqualifiedType())) {
12228 if (IsRelational) {
12229 // Pointers both need to point to complete or incomplete types
12230 if ((LCanPointeeTy->isIncompleteType() !=
12231 RCanPointeeTy->isIncompleteType()) &&
12232 !getLangOpts().C11) {
12233 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12234 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12235 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12236 << RCanPointeeTy->isIncompleteType();
12237 }
12238 }
12239 } else if (!IsRelational &&
12240 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12241 // Valid unless comparison between non-null pointer and function pointer
12242 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12243 && !LHSIsNull && !RHSIsNull)
12245 /*isError*/false);
12246 } else {
12247 // Invalid
12248 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12249 }
12250 if (LCanPointeeTy != RCanPointeeTy) {
12251 // Treat NULL constant as a special case in OpenCL.
12252 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12253 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12254 Diag(Loc,
12255 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12256 << LHSType << RHSType << 0 /* comparison */
12257 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12258 }
12259 }
12260 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12261 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12262 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12263 : CK_BitCast;
12264 if (LHSIsNull && !RHSIsNull)
12265 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12266 else
12267 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12268 }
12269 return computeResultTy();
12270 }
12271
12272
12273 // C++ [expr.eq]p4:
12274 // Two operands of type std::nullptr_t or one operand of type
12275 // std::nullptr_t and the other a null pointer constant compare
12276 // equal.
12277 // C23 6.5.9p5:
12278 // If both operands have type nullptr_t or one operand has type nullptr_t
12279 // and the other is a null pointer constant, they compare equal if the
12280 // former is a null pointer.
12281 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12282 if (LHSType->isNullPtrType()) {
12283 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12284 return computeResultTy();
12285 }
12286 if (RHSType->isNullPtrType()) {
12287 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12288 return computeResultTy();
12289 }
12290 }
12291
12292 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12293 // C23 6.5.9p6:
12294 // Otherwise, at least one operand is a pointer. If one is a pointer and
12295 // the other is a null pointer constant or has type nullptr_t, they
12296 // compare equal
12297 if (LHSIsNull && RHSType->isPointerType()) {
12298 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12299 return computeResultTy();
12300 }
12301 if (RHSIsNull && LHSType->isPointerType()) {
12302 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12303 return computeResultTy();
12304 }
12305 }
12306
12307 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12308 // These aren't covered by the composite pointer type rules.
12309 if (!IsOrdered && RHSType->isNullPtrType() &&
12310 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12311 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12312 return computeResultTy();
12313 }
12314 if (!IsOrdered && LHSType->isNullPtrType() &&
12315 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12316 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12317 return computeResultTy();
12318 }
12319
12320 if (getLangOpts().CPlusPlus) {
12321 if (IsRelational &&
12322 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12323 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12324 // HACK: Relational comparison of nullptr_t against a pointer type is
12325 // invalid per DR583, but we allow it within std::less<> and friends,
12326 // since otherwise common uses of it break.
12327 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12328 // friends to have std::nullptr_t overload candidates.
12329 DeclContext *DC = CurContext;
12330 if (isa<FunctionDecl>(DC))
12331 DC = DC->getParent();
12332 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12333 if (CTSD->isInStdNamespace() &&
12334 llvm::StringSwitch<bool>(CTSD->getName())
12335 .Cases("less", "less_equal", "greater", "greater_equal", true)
12336 .Default(false)) {
12337 if (RHSType->isNullPtrType())
12338 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12339 else
12340 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12341 return computeResultTy();
12342 }
12343 }
12344 }
12345
12346 // C++ [expr.eq]p2:
12347 // If at least one operand is a pointer to member, [...] bring them to
12348 // their composite pointer type.
12349 if (!IsOrdered &&
12350 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12351 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12352 return QualType();
12353 else
12354 return computeResultTy();
12355 }
12356 }
12357
12358 // Handle block pointer types.
12359 if (!IsOrdered && LHSType->isBlockPointerType() &&
12360 RHSType->isBlockPointerType()) {
12361 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12362 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12363
12364 if (!LHSIsNull && !RHSIsNull &&
12365 !Context.typesAreCompatible(lpointee, rpointee)) {
12366 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12367 << LHSType << RHSType << LHS.get()->getSourceRange()
12368 << RHS.get()->getSourceRange();
12369 }
12370 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12371 return computeResultTy();
12372 }
12373
12374 // Allow block pointers to be compared with null pointer constants.
12375 if (!IsOrdered
12376 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12377 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12378 if (!LHSIsNull && !RHSIsNull) {
12379 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12381 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12382 ->getPointeeType()->isVoidType())))
12383 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12384 << LHSType << RHSType << LHS.get()->getSourceRange()
12385 << RHS.get()->getSourceRange();
12386 }
12387 if (LHSIsNull && !RHSIsNull)
12388 LHS = ImpCastExprToType(LHS.get(), RHSType,
12389 RHSType->isPointerType() ? CK_BitCast
12390 : CK_AnyPointerToBlockPointerCast);
12391 else
12392 RHS = ImpCastExprToType(RHS.get(), LHSType,
12393 LHSType->isPointerType() ? CK_BitCast
12394 : CK_AnyPointerToBlockPointerCast);
12395 return computeResultTy();
12396 }
12397
12398 if (LHSType->isObjCObjectPointerType() ||
12399 RHSType->isObjCObjectPointerType()) {
12400 const PointerType *LPT = LHSType->getAs<PointerType>();
12401 const PointerType *RPT = RHSType->getAs<PointerType>();
12402 if (LPT || RPT) {
12403 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12404 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12405
12406 if (!LPtrToVoid && !RPtrToVoid &&
12407 !Context.typesAreCompatible(LHSType, RHSType)) {
12408 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12409 /*isError*/false);
12410 }
12411 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12412 // the RHS, but we have test coverage for this behavior.
12413 // FIXME: Consider using convertPointersToCompositeType in C++.
12414 if (LHSIsNull && !RHSIsNull) {
12415 Expr *E = LHS.get();
12416 if (getLangOpts().ObjCAutoRefCount)
12417 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
12419 LHS = ImpCastExprToType(E, RHSType,
12420 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12421 }
12422 else {
12423 Expr *E = RHS.get();
12424 if (getLangOpts().ObjCAutoRefCount)
12425 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
12427 /*Diagnose=*/true,
12428 /*DiagnoseCFAudited=*/false, Opc);
12429 RHS = ImpCastExprToType(E, LHSType,
12430 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12431 }
12432 return computeResultTy();
12433 }
12434 if (LHSType->isObjCObjectPointerType() &&
12435 RHSType->isObjCObjectPointerType()) {
12436 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12437 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12438 /*isError*/false);
12440 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12441
12442 if (LHSIsNull && !RHSIsNull)
12443 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12444 else
12445 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12446 return computeResultTy();
12447 }
12448
12449 if (!IsOrdered && LHSType->isBlockPointerType() &&
12451 LHS = ImpCastExprToType(LHS.get(), RHSType,
12452 CK_BlockPointerToObjCPointerCast);
12453 return computeResultTy();
12454 } else if (!IsOrdered &&
12456 RHSType->isBlockPointerType()) {
12457 RHS = ImpCastExprToType(RHS.get(), LHSType,
12458 CK_BlockPointerToObjCPointerCast);
12459 return computeResultTy();
12460 }
12461 }
12462 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12463 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12464 unsigned DiagID = 0;
12465 bool isError = false;
12466 if (LangOpts.DebuggerSupport) {
12467 // Under a debugger, allow the comparison of pointers to integers,
12468 // since users tend to want to compare addresses.
12469 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12470 (RHSIsNull && RHSType->isIntegerType())) {
12471 if (IsOrdered) {
12472 isError = getLangOpts().CPlusPlus;
12473 DiagID =
12474 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12475 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12476 }
12477 } else if (getLangOpts().CPlusPlus) {
12478 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12479 isError = true;
12480 } else if (IsOrdered)
12481 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12482 else
12483 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12484
12485 if (DiagID) {
12486 Diag(Loc, DiagID)
12487 << LHSType << RHSType << LHS.get()->getSourceRange()
12488 << RHS.get()->getSourceRange();
12489 if (isError)
12490 return QualType();
12491 }
12492
12493 if (LHSType->isIntegerType())
12494 LHS = ImpCastExprToType(LHS.get(), RHSType,
12495 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12496 else
12497 RHS = ImpCastExprToType(RHS.get(), LHSType,
12498 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12499 return computeResultTy();
12500 }
12501
12502 // Handle block pointers.
12503 if (!IsOrdered && RHSIsNull
12504 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12505 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12506 return computeResultTy();
12507 }
12508 if (!IsOrdered && LHSIsNull
12509 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12510 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12511 return computeResultTy();
12512 }
12513
12514 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12515 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12516 return computeResultTy();
12517 }
12518
12519 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12520 return computeResultTy();
12521 }
12522
12523 if (LHSIsNull && RHSType->isQueueT()) {
12524 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12525 return computeResultTy();
12526 }
12527
12528 if (LHSType->isQueueT() && RHSIsNull) {
12529 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12530 return computeResultTy();
12531 }
12532 }
12533
12534 return InvalidOperands(Loc, LHS, RHS);
12535}
12536
12538 const VectorType *VTy = V->castAs<VectorType>();
12539 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12540
12541 if (isa<ExtVectorType>(VTy)) {
12542 if (VTy->isExtVectorBoolType())
12544 if (TypeSize == Context.getTypeSize(Context.CharTy))
12546 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12548 if (TypeSize == Context.getTypeSize(Context.IntTy))
12550 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12552 if (TypeSize == Context.getTypeSize(Context.LongTy))
12554 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12555 "Unhandled vector element size in vector compare");
12557 }
12558
12559 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12562 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12565 if (TypeSize == Context.getTypeSize(Context.LongTy))
12568 if (TypeSize == Context.getTypeSize(Context.IntTy))
12571 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12574 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12575 "Unhandled vector element size in vector compare");
12578}
12579
12581 const BuiltinType *VTy = V->castAs<BuiltinType>();
12582 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
12583
12584 const QualType ETy = V->getSveEltType(Context);
12585 const auto TypeSize = Context.getTypeSize(ETy);
12586
12587 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12588 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12589 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12590}
12591
12594 BinaryOperatorKind Opc) {
12595 if (Opc == BO_Cmp) {
12596 Diag(Loc, diag::err_three_way_vector_comparison);
12597 return QualType();
12598 }
12599
12600 // Check to make sure we're operating on vectors of the same type and width,
12601 // Allowing one side to be a scalar of element type.
12602 QualType vType =
12603 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12604 /*AllowBothBool*/ true,
12605 /*AllowBoolConversions*/ getLangOpts().ZVector,
12606 /*AllowBooleanOperation*/ true,
12607 /*ReportInvalid*/ true);
12608 if (vType.isNull())
12609 return vType;
12610
12611 QualType LHSType = LHS.get()->getType();
12612
12613 // Determine the return type of a vector compare. By default clang will return
12614 // a scalar for all vector compares except vector bool and vector pixel.
12615 // With the gcc compiler we will always return a vector type and with the xl
12616 // compiler we will always return a scalar type. This switch allows choosing
12617 // which behavior is prefered.
12618 if (getLangOpts().AltiVec) {
12619 switch (getLangOpts().getAltivecSrcCompat()) {
12621 // If AltiVec, the comparison results in a numeric type, i.e.
12622 // bool for C++, int for C
12623 if (vType->castAs<VectorType>()->getVectorKind() ==
12626 else
12627 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12628 break;
12630 // For GCC we always return the vector type.
12631 break;
12634 break;
12635 }
12636 }
12637
12638 // For non-floating point types, check for self-comparisons of the form
12639 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12640 // often indicate logic errors in the program.
12641 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12642
12643 // Check for comparisons of floating point operands using != and ==.
12644 if (LHSType->hasFloatingRepresentation()) {
12645 assert(RHS.get()->getType()->hasFloatingRepresentation());
12646 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12647 }
12648
12649 // Return a signed type for the vector.
12650 return GetSignedVectorType(vType);
12651}
12652
12654 ExprResult &RHS,
12656 BinaryOperatorKind Opc) {
12657 if (Opc == BO_Cmp) {
12658 Diag(Loc, diag::err_three_way_vector_comparison);
12659 return QualType();
12660 }
12661
12662 // Check to make sure we're operating on vectors of the same type and width,
12663 // Allowing one side to be a scalar of element type.
12665 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12666
12667 if (vType.isNull())
12668 return vType;
12669
12670 QualType LHSType = LHS.get()->getType();
12671
12672 // For non-floating point types, check for self-comparisons of the form
12673 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12674 // often indicate logic errors in the program.
12675 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12676
12677 // Check for comparisons of floating point operands using != and ==.
12678 if (LHSType->hasFloatingRepresentation()) {
12679 assert(RHS.get()->getType()->hasFloatingRepresentation());
12680 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12681 }
12682
12683 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12684 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12685
12686 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12687 RHSBuiltinTy->isSVEBool())
12688 return LHSType;
12689
12690 // Return a signed type for the vector.
12691 return GetSignedSizelessVectorType(vType);
12692}
12693
12694static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12695 const ExprResult &XorRHS,
12696 const SourceLocation Loc) {
12697 // Do not diagnose macros.
12698 if (Loc.isMacroID())
12699 return;
12700
12701 // Do not diagnose if both LHS and RHS are macros.
12702 if (XorLHS.get()->getExprLoc().isMacroID() &&
12703 XorRHS.get()->getExprLoc().isMacroID())
12704 return;
12705
12706 bool Negative = false;
12707 bool ExplicitPlus = false;
12708 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12709 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12710
12711 if (!LHSInt)
12712 return;
12713 if (!RHSInt) {
12714 // Check negative literals.
12715 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12716 UnaryOperatorKind Opc = UO->getOpcode();
12717 if (Opc != UO_Minus && Opc != UO_Plus)
12718 return;
12719 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12720 if (!RHSInt)
12721 return;
12722 Negative = (Opc == UO_Minus);
12723 ExplicitPlus = !Negative;
12724 } else {
12725 return;
12726 }
12727 }
12728
12729 const llvm::APInt &LeftSideValue = LHSInt->getValue();
12730 llvm::APInt RightSideValue = RHSInt->getValue();
12731 if (LeftSideValue != 2 && LeftSideValue != 10)
12732 return;
12733
12734 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12735 return;
12736
12738 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12739 llvm::StringRef ExprStr =
12741
12742 CharSourceRange XorRange =
12744 llvm::StringRef XorStr =
12746 // Do not diagnose if xor keyword/macro is used.
12747 if (XorStr == "xor")
12748 return;
12749
12750 std::string LHSStr = std::string(Lexer::getSourceText(
12751 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12752 S.getSourceManager(), S.getLangOpts()));
12753 std::string RHSStr = std::string(Lexer::getSourceText(
12754 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12755 S.getSourceManager(), S.getLangOpts()));
12756
12757 if (Negative) {
12758 RightSideValue = -RightSideValue;
12759 RHSStr = "-" + RHSStr;
12760 } else if (ExplicitPlus) {
12761 RHSStr = "+" + RHSStr;
12762 }
12763
12764 StringRef LHSStrRef = LHSStr;
12765 StringRef RHSStrRef = RHSStr;
12766 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12767 // literals.
12768 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
12769 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
12770 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
12771 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
12772 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
12773 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
12774 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12775 return;
12776
12777 bool SuggestXor =
12778 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12779 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12780 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12781 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12782 std::string SuggestedExpr = "1 << " + RHSStr;
12783 bool Overflow = false;
12784 llvm::APInt One = (LeftSideValue - 1);
12785 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12786 if (Overflow) {
12787 if (RightSideIntValue < 64)
12788 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12789 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12790 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12791 else if (RightSideIntValue == 64)
12792 S.Diag(Loc, diag::warn_xor_used_as_pow)
12793 << ExprStr << toString(XorValue, 10, true);
12794 else
12795 return;
12796 } else {
12797 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12798 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12799 << toString(PowValue, 10, true)
12801 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12802 }
12803
12804 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12805 << ("0x2 ^ " + RHSStr) << SuggestXor;
12806 } else if (LeftSideValue == 10) {
12807 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12808 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12809 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12810 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12811 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12812 << ("0xA ^ " + RHSStr) << SuggestXor;
12813 }
12814}
12815
12818 // Ensure that either both operands are of the same vector type, or
12819 // one operand is of a vector type and the other is of its element type.
12820 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12821 /*AllowBothBool*/ true,
12822 /*AllowBoolConversions*/ false,
12823 /*AllowBooleanOperation*/ false,
12824 /*ReportInvalid*/ false);
12825 if (vType.isNull())
12826 return InvalidOperands(Loc, LHS, RHS);
12827 if (getLangOpts().OpenCL &&
12828 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12830 return InvalidOperands(Loc, LHS, RHS);
12831 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12832 // usage of the logical operators && and || with vectors in C. This
12833 // check could be notionally dropped.
12834 if (!getLangOpts().CPlusPlus &&
12835 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12836 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12837
12838 return GetSignedVectorType(LHS.get()->getType());
12839}
12840
12843 bool IsCompAssign) {
12844 if (!IsCompAssign) {
12846 if (LHS.isInvalid())
12847 return QualType();
12848 }
12850 if (RHS.isInvalid())
12851 return QualType();
12852
12853 // For conversion purposes, we ignore any qualifiers.
12854 // For example, "const float" and "float" are equivalent.
12855 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12856 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12857
12858 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12859 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12860 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12861
12862 if (Context.hasSameType(LHSType, RHSType))
12863 return Context.getCommonSugaredType(LHSType, RHSType);
12864
12865 // Type conversion may change LHS/RHS. Keep copies to the original results, in
12866 // case we have to return InvalidOperands.
12867 ExprResult OriginalLHS = LHS;
12868 ExprResult OriginalRHS = RHS;
12869 if (LHSMatType && !RHSMatType) {
12870 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12871 if (!RHS.isInvalid())
12872 return LHSType;
12873
12874 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12875 }
12876
12877 if (!LHSMatType && RHSMatType) {
12878 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12879 if (!LHS.isInvalid())
12880 return RHSType;
12881 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12882 }
12883
12884 return InvalidOperands(Loc, LHS, RHS);
12885}
12886
12889 bool IsCompAssign) {
12890 if (!IsCompAssign) {
12892 if (LHS.isInvalid())
12893 return QualType();
12894 }
12896 if (RHS.isInvalid())
12897 return QualType();
12898
12899 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12900 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12901 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12902
12903 if (LHSMatType && RHSMatType) {
12904 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12905 return InvalidOperands(Loc, LHS, RHS);
12906
12907 if (Context.hasSameType(LHSMatType, RHSMatType))
12909 LHS.get()->getType().getUnqualifiedType(),
12910 RHS.get()->getType().getUnqualifiedType());
12911
12912 QualType LHSELTy = LHSMatType->getElementType(),
12913 RHSELTy = RHSMatType->getElementType();
12914 if (!Context.hasSameType(LHSELTy, RHSELTy))
12915 return InvalidOperands(Loc, LHS, RHS);
12916
12918 Context.getCommonSugaredType(LHSELTy, RHSELTy),
12919 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
12920 }
12921 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12922}
12923
12925 switch (Opc) {
12926 default:
12927 return false;
12928 case BO_And:
12929 case BO_AndAssign:
12930 case BO_Or:
12931 case BO_OrAssign:
12932 case BO_Xor:
12933 case BO_XorAssign:
12934 return true;
12935 }
12936}
12937
12940 BinaryOperatorKind Opc) {
12941 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12942
12943 bool IsCompAssign =
12944 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12945
12946 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
12947
12948 if (LHS.get()->getType()->isVectorType() ||
12949 RHS.get()->getType()->isVectorType()) {
12950 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12952 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12953 /*AllowBothBool*/ true,
12954 /*AllowBoolConversions*/ getLangOpts().ZVector,
12955 /*AllowBooleanOperation*/ LegalBoolVecOperator,
12956 /*ReportInvalid*/ true);
12957 return InvalidOperands(Loc, LHS, RHS);
12958 }
12959
12960 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12961 RHS.get()->getType()->isSveVLSBuiltinType()) {
12962 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12964 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
12966 return InvalidOperands(Loc, LHS, RHS);
12967 }
12968
12969 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12970 RHS.get()->getType()->isSveVLSBuiltinType()) {
12971 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12973 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
12975 return InvalidOperands(Loc, LHS, RHS);
12976 }
12977
12978 if (Opc == BO_And)
12979 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12980
12981 if (LHS.get()->getType()->hasFloatingRepresentation() ||
12983 return InvalidOperands(Loc, LHS, RHS);
12984
12985 ExprResult LHSResult = LHS, RHSResult = RHS;
12987 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12988 if (LHSResult.isInvalid() || RHSResult.isInvalid())
12989 return QualType();
12990 LHS = LHSResult.get();
12991 RHS = RHSResult.get();
12992
12993 if (Opc == BO_Xor)
12994 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12995
12996 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12997 return compType;
12998 return InvalidOperands(Loc, LHS, RHS);
12999}
13000
13001// C99 6.5.[13,14]
13004 BinaryOperatorKind Opc) {
13005 // Check vector operands differently.
13006 if (LHS.get()->getType()->isVectorType() ||
13007 RHS.get()->getType()->isVectorType())
13008 return CheckVectorLogicalOperands(LHS, RHS, Loc);
13009
13010 bool EnumConstantInBoolContext = false;
13011 for (const ExprResult &HS : {LHS, RHS}) {
13012 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13013 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13014 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13015 EnumConstantInBoolContext = true;
13016 }
13017 }
13018
13019 if (EnumConstantInBoolContext)
13020 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13021
13022 // WebAssembly tables can't be used with logical operators.
13023 QualType LHSTy = LHS.get()->getType();
13024 QualType RHSTy = RHS.get()->getType();
13025 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13026 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13027 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13028 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13029 return InvalidOperands(Loc, LHS, RHS);
13030 }
13031
13032 // Diagnose cases where the user write a logical and/or but probably meant a
13033 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13034 // is a constant.
13035 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13036 !LHS.get()->getType()->isBooleanType() &&
13037 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13038 // Don't warn in macros or template instantiations.
13040 // If the RHS can be constant folded, and if it constant folds to something
13041 // that isn't 0 or 1 (which indicate a potential logical operation that
13042 // happened to fold to true/false) then warn.
13043 // Parens on the RHS are ignored.
13044 Expr::EvalResult EVResult;
13045 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13046 llvm::APSInt Result = EVResult.Val.getInt();
13047 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13048 !RHS.get()->getExprLoc().isMacroID()) ||
13049 (Result != 0 && Result != 1)) {
13050 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13051 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13052 // Suggest replacing the logical operator with the bitwise version
13053 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13054 << (Opc == BO_LAnd ? "&" : "|")
13057 Opc == BO_LAnd ? "&" : "|");
13058 if (Opc == BO_LAnd)
13059 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13060 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13063 RHS.get()->getEndLoc()));
13064 }
13065 }
13066 }
13067
13068 if (!Context.getLangOpts().CPlusPlus) {
13069 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13070 // not operate on the built-in scalar and vector float types.
13071 if (Context.getLangOpts().OpenCL &&
13072 Context.getLangOpts().OpenCLVersion < 120) {
13073 if (LHS.get()->getType()->isFloatingType() ||
13074 RHS.get()->getType()->isFloatingType())
13075 return InvalidOperands(Loc, LHS, RHS);
13076 }
13077
13078 LHS = UsualUnaryConversions(LHS.get());
13079 if (LHS.isInvalid())
13080 return QualType();
13081
13082 RHS = UsualUnaryConversions(RHS.get());
13083 if (RHS.isInvalid())
13084 return QualType();
13085
13086 if (!LHS.get()->getType()->isScalarType() ||
13087 !RHS.get()->getType()->isScalarType())
13088 return InvalidOperands(Loc, LHS, RHS);
13089
13090 return Context.IntTy;
13091 }
13092
13093 // The following is safe because we only use this method for
13094 // non-overloadable operands.
13095
13096 // C++ [expr.log.and]p1
13097 // C++ [expr.log.or]p1
13098 // The operands are both contextually converted to type bool.
13100 if (LHSRes.isInvalid())
13101 return InvalidOperands(Loc, LHS, RHS);
13102 LHS = LHSRes;
13103
13105 if (RHSRes.isInvalid())
13106 return InvalidOperands(Loc, LHS, RHS);
13107 RHS = RHSRes;
13108
13109 // C++ [expr.log.and]p2
13110 // C++ [expr.log.or]p2
13111 // The result is a bool.
13112 return Context.BoolTy;
13113}
13114
13115static bool IsReadonlyMessage(Expr *E, Sema &S) {
13116 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13117 if (!ME) return false;
13118 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13119 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13121 if (!Base) return false;
13122 return Base->getMethodDecl() != nullptr;
13123}
13124
13125/// Is the given expression (which must be 'const') a reference to a
13126/// variable which was originally non-const, but which has become
13127/// 'const' due to being captured within a block?
13130 assert(E->isLValue() && E->getType().isConstQualified());
13131 E = E->IgnoreParens();
13132
13133 // Must be a reference to a declaration from an enclosing scope.
13134 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13135 if (!DRE) return NCCK_None;
13137
13138 // The declaration must be a variable which is not declared 'const'.
13139 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13140 if (!var) return NCCK_None;
13141 if (var->getType().isConstQualified()) return NCCK_None;
13142 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
13143
13144 // Decide whether the first capture was for a block or a lambda.
13145 DeclContext *DC = S.CurContext, *Prev = nullptr;
13146 // Decide whether the first capture was for a block or a lambda.
13147 while (DC) {
13148 // For init-capture, it is possible that the variable belongs to the
13149 // template pattern of the current context.
13150 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13151 if (var->isInitCapture() &&
13152 FD->getTemplateInstantiationPattern() == var->getDeclContext())
13153 break;
13154 if (DC == var->getDeclContext())
13155 break;
13156 Prev = DC;
13157 DC = DC->getParent();
13158 }
13159 // Unless we have an init-capture, we've gone one step too far.
13160 if (!var->isInitCapture())
13161 DC = Prev;
13162 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13163}
13164
13165static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13166 Ty = Ty.getNonReferenceType();
13167 if (IsDereference && Ty->isPointerType())
13168 Ty = Ty->getPointeeType();
13169 return !Ty.isConstQualified();
13170}
13171
13172// Update err_typecheck_assign_const and note_typecheck_assign_const
13173// when this enum is changed.
13174enum {
13180 ConstUnknown, // Keep as last element
13181};
13182
13183/// Emit the "read-only variable not assignable" error and print notes to give
13184/// more information about why the variable is not assignable, such as pointing
13185/// to the declaration of a const variable, showing that a method is const, or
13186/// that the function is returning a const reference.
13187static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13189 SourceRange ExprRange = E->getSourceRange();
13190
13191 // Only emit one error on the first const found. All other consts will emit
13192 // a note to the error.
13193 bool DiagnosticEmitted = false;
13194
13195 // Track if the current expression is the result of a dereference, and if the
13196 // next checked expression is the result of a dereference.
13197 bool IsDereference = false;
13198 bool NextIsDereference = false;
13199
13200 // Loop to process MemberExpr chains.
13201 while (true) {
13202 IsDereference = NextIsDereference;
13203
13205 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13206 NextIsDereference = ME->isArrow();
13207 const ValueDecl *VD = ME->getMemberDecl();
13208 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13209 // Mutable fields can be modified even if the class is const.
13210 if (Field->isMutable()) {
13211 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13212 break;
13213 }
13214
13215 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13216 if (!DiagnosticEmitted) {
13217 S.Diag(Loc, diag::err_typecheck_assign_const)
13218 << ExprRange << ConstMember << false /*static*/ << Field
13219 << Field->getType();
13220 DiagnosticEmitted = true;
13221 }
13222 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13223 << ConstMember << false /*static*/ << Field << Field->getType()
13224 << Field->getSourceRange();
13225 }
13226 E = ME->getBase();
13227 continue;
13228 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13229 if (VDecl->getType().isConstQualified()) {
13230 if (!DiagnosticEmitted) {
13231 S.Diag(Loc, diag::err_typecheck_assign_const)
13232 << ExprRange << ConstMember << true /*static*/ << VDecl
13233 << VDecl->getType();
13234 DiagnosticEmitted = true;
13235 }
13236 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13237 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13238 << VDecl->getSourceRange();
13239 }
13240 // Static fields do not inherit constness from parents.
13241 break;
13242 }
13243 break; // End MemberExpr
13244 } else if (const ArraySubscriptExpr *ASE =
13245 dyn_cast<ArraySubscriptExpr>(E)) {
13246 E = ASE->getBase()->IgnoreParenImpCasts();
13247 continue;
13248 } else if (const ExtVectorElementExpr *EVE =
13249 dyn_cast<ExtVectorElementExpr>(E)) {
13250 E = EVE->getBase()->IgnoreParenImpCasts();
13251 continue;
13252 }
13253 break;
13254 }
13255
13256 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13257 // Function calls
13258 const FunctionDecl *FD = CE->getDirectCallee();
13259 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13260 if (!DiagnosticEmitted) {
13261 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13262 << ConstFunction << FD;
13263 DiagnosticEmitted = true;
13264 }
13266 diag::note_typecheck_assign_const)
13267 << ConstFunction << FD << FD->getReturnType()
13268 << FD->getReturnTypeSourceRange();
13269 }
13270 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13271 // Point to variable declaration.
13272 if (const ValueDecl *VD = DRE->getDecl()) {
13273 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13274 if (!DiagnosticEmitted) {
13275 S.Diag(Loc, diag::err_typecheck_assign_const)
13276 << ExprRange << ConstVariable << VD << VD->getType();
13277 DiagnosticEmitted = true;
13278 }
13279 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13280 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13281 }
13282 }
13283 } else if (isa<CXXThisExpr>(E)) {
13284 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13285 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13286 if (MD->isConst()) {
13287 if (!DiagnosticEmitted) {
13288 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13289 << ConstMethod << MD;
13290 DiagnosticEmitted = true;
13291 }
13292 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13293 << ConstMethod << MD << MD->getSourceRange();
13294 }
13295 }
13296 }
13297 }
13298
13299 if (DiagnosticEmitted)
13300 return;
13301
13302 // Can't determine a more specific message, so display the generic error.
13303 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13304}
13305
13311
13313 const RecordType *Ty,
13315 OriginalExprKind OEK,
13316 bool &DiagnosticEmitted) {
13317 std::vector<const RecordType *> RecordTypeList;
13318 RecordTypeList.push_back(Ty);
13319 unsigned NextToCheckIndex = 0;
13320 // We walk the record hierarchy breadth-first to ensure that we print
13321 // diagnostics in field nesting order.
13322 while (RecordTypeList.size() > NextToCheckIndex) {
13323 bool IsNested = NextToCheckIndex > 0;
13324 for (const FieldDecl *Field :
13325 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13326 // First, check every field for constness.
13327 QualType FieldTy = Field->getType();
13328 if (FieldTy.isConstQualified()) {
13329 if (!DiagnosticEmitted) {
13330 S.Diag(Loc, diag::err_typecheck_assign_const)
13331 << Range << NestedConstMember << OEK << VD
13332 << IsNested << Field;
13333 DiagnosticEmitted = true;
13334 }
13335 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13336 << NestedConstMember << IsNested << Field
13337 << FieldTy << Field->getSourceRange();
13338 }
13339
13340 // Then we append it to the list to check next in order.
13341 FieldTy = FieldTy.getCanonicalType();
13342 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13343 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13344 RecordTypeList.push_back(FieldRecTy);
13345 }
13346 }
13347 ++NextToCheckIndex;
13348 }
13349}
13350
13351/// Emit an error for the case where a record we are trying to assign to has a
13352/// const-qualified field somewhere in its hierarchy.
13355 QualType Ty = E->getType();
13356 assert(Ty->isRecordType() && "lvalue was not record?");
13358 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13359 bool DiagEmitted = false;
13360
13361 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13362 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13363 Range, OEK_Member, DiagEmitted);
13364 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13365 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13366 Range, OEK_Variable, DiagEmitted);
13367 else
13368 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13369 Range, OEK_LValue, DiagEmitted);
13370 if (!DiagEmitted)
13372}
13373
13374/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13375/// emit an error and return true. If so, return false.
13377 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13378
13380
13381 SourceLocation OrigLoc = Loc;
13383 &Loc);
13384 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13386 if (IsLV == Expr::MLV_Valid)
13387 return false;
13388
13389 unsigned DiagID = 0;
13390 bool NeedType = false;
13391 switch (IsLV) { // C99 6.5.16p2
13393 // Use a specialized diagnostic when we're assigning to an object
13394 // from an enclosing function or block.
13396 if (NCCK == NCCK_Block)
13397 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13398 else
13399 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13400 break;
13401 }
13402
13403 // In ARC, use some specialized diagnostics for occasions where we
13404 // infer 'const'. These are always pseudo-strong variables.
13405 if (S.getLangOpts().ObjCAutoRefCount) {
13406 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13407 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13408 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13409
13410 // Use the normal diagnostic if it's pseudo-__strong but the
13411 // user actually wrote 'const'.
13412 if (var->isARCPseudoStrong() &&
13413 (!var->getTypeSourceInfo() ||
13414 !var->getTypeSourceInfo()->getType().isConstQualified())) {
13415 // There are three pseudo-strong cases:
13416 // - self
13417 ObjCMethodDecl *method = S.getCurMethodDecl();
13418 if (method && var == method->getSelfDecl()) {
13419 DiagID = method->isClassMethod()
13420 ? diag::err_typecheck_arc_assign_self_class_method
13421 : diag::err_typecheck_arc_assign_self;
13422
13423 // - Objective-C externally_retained attribute.
13424 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13425 isa<ParmVarDecl>(var)) {
13426 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13427
13428 // - fast enumeration variables
13429 } else {
13430 DiagID = diag::err_typecheck_arr_assign_enumeration;
13431 }
13432
13433 SourceRange Assign;
13434 if (Loc != OrigLoc)
13435 Assign = SourceRange(OrigLoc, OrigLoc);
13436 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13437 // We need to preserve the AST regardless, so migration tool
13438 // can do its job.
13439 return false;
13440 }
13441 }
13442 }
13443
13444 // If none of the special cases above are triggered, then this is a
13445 // simple const assignment.
13446 if (DiagID == 0) {
13448 return true;
13449 }
13450
13451 break;
13454 return true;
13457 return true;
13460 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13461 NeedType = true;
13462 break;
13464 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13465 NeedType = true;
13466 break;
13468 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13469 break;
13470 case Expr::MLV_Valid:
13471 llvm_unreachable("did not take early return for MLV_Valid");
13475 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13476 break;
13479 return S.RequireCompleteType(Loc, E->getType(),
13480 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13482 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13483 break;
13485 llvm_unreachable("readonly properties should be processed differently");
13487 DiagID = diag::err_readonly_message_assignment;
13488 break;
13490 DiagID = diag::err_no_subobject_property_setting;
13491 break;
13492 }
13493
13494 SourceRange Assign;
13495 if (Loc != OrigLoc)
13496 Assign = SourceRange(OrigLoc, OrigLoc);
13497 if (NeedType)
13498 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13499 else
13500 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13501 return true;
13502}
13503
13504static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13506 Sema &Sema) {
13508 return;
13510 return;
13511 if (Loc.isInvalid() || Loc.isMacroID())
13512 return;
13513 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13514 return;
13515
13516 // C / C++ fields
13517 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13518 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13519 if (ML && MR) {
13520 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13521 return;
13522 const ValueDecl *LHSDecl =
13523 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13524 const ValueDecl *RHSDecl =
13525 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13526 if (LHSDecl != RHSDecl)
13527 return;
13528 if (LHSDecl->getType().isVolatileQualified())
13529 return;
13530 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13531 if (RefTy->getPointeeType().isVolatileQualified())
13532 return;
13533
13534 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13535 }
13536
13537 // Objective-C instance variables
13538 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13539 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13540 if (OL && OR && OL->getDecl() == OR->getDecl()) {
13541 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13542 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13543 if (RL && RR && RL->getDecl() == RR->getDecl())
13544 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13545 }
13546}
13547
13548// C99 6.5.16.1
13551 QualType CompoundType,
13552 BinaryOperatorKind Opc) {
13553 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13554
13555 // Verify that LHS is a modifiable lvalue, and emit error if not.
13556 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13557 return QualType();
13558
13559 QualType LHSType = LHSExpr->getType();
13560 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13561 CompoundType;
13562 // OpenCL v1.2 s6.1.1.1 p2:
13563 // The half data type can only be used to declare a pointer to a buffer that
13564 // contains half values
13565 if (getLangOpts().OpenCL &&
13566 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13567 LHSType->isHalfType()) {
13568 Diag(Loc, diag::err_opencl_half_load_store) << 1
13569 << LHSType.getUnqualifiedType();
13570 return QualType();
13571 }
13572
13573 // WebAssembly tables can't be used on RHS of an assignment expression.
13574 if (RHSType->isWebAssemblyTableType()) {
13575 Diag(Loc, diag::err_wasm_table_art) << 0;
13576 return QualType();
13577 }
13578
13579 AssignConvertType ConvTy;
13580 if (CompoundType.isNull()) {
13581 Expr *RHSCheck = RHS.get();
13582
13583 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13584
13585 QualType LHSTy(LHSType);
13586 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13587 if (RHS.isInvalid())
13588 return QualType();
13589 // Special case of NSObject attributes on c-style pointer types.
13590 if (ConvTy == IncompatiblePointer &&
13591 ((Context.isObjCNSObjectType(LHSType) &&
13592 RHSType->isObjCObjectPointerType()) ||
13593 (Context.isObjCNSObjectType(RHSType) &&
13594 LHSType->isObjCObjectPointerType())))
13595 ConvTy = Compatible;
13596
13597 if (ConvTy == Compatible &&
13598 LHSType->isObjCObjectType())
13599 Diag(Loc, diag::err_objc_object_assignment)
13600 << LHSType;
13601
13602 // If the RHS is a unary plus or minus, check to see if they = and + are
13603 // right next to each other. If so, the user may have typo'd "x =+ 4"
13604 // instead of "x += 4".
13605 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13606 RHSCheck = ICE->getSubExpr();
13607 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13608 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13609 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13610 // Only if the two operators are exactly adjacent.
13611 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13612 // And there is a space or other character before the subexpr of the
13613 // unary +/-. We don't want to warn on "x=-1".
13614 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13615 UO->getSubExpr()->getBeginLoc().isFileID()) {
13616 Diag(Loc, diag::warn_not_compound_assign)
13617 << (UO->getOpcode() == UO_Plus ? "+" : "-")
13618 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13619 }
13620 }
13621
13622 if (ConvTy == Compatible) {
13623 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13624 // Warn about retain cycles where a block captures the LHS, but
13625 // not if the LHS is a simple variable into which the block is
13626 // being stored...unless that variable can be captured by reference!
13627 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13628 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13629 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13630 ObjC().checkRetainCycles(LHSExpr, RHS.get());
13631 }
13632
13633 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13635 // It is safe to assign a weak reference into a strong variable.
13636 // Although this code can still have problems:
13637 // id x = self.weakProp;
13638 // id y = self.weakProp;
13639 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13640 // paths through the function. This should be revisited if
13641 // -Wrepeated-use-of-weak is made flow-sensitive.
13642 // For ObjCWeak only, we do not warn if the assign is to a non-weak
13643 // variable, which will be valid for the current autorelease scope.
13644 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13645 RHS.get()->getBeginLoc()))
13647
13648 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13649 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13650 }
13651 }
13652 } else {
13653 // Compound assignment "x += y"
13654 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13655 }
13656
13657 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13658 RHS.get(), AA_Assigning))
13659 return QualType();
13660
13661 CheckForNullPointerDereference(*this, LHSExpr);
13662
13663 AssignedEntity AE{LHSExpr};
13664 checkExprLifetime(*this, AE, RHS.get());
13665
13666 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13667 if (CompoundType.isNull()) {
13668 // C++2a [expr.ass]p5:
13669 // A simple-assignment whose left operand is of a volatile-qualified
13670 // type is deprecated unless the assignment is either a discarded-value
13671 // expression or an unevaluated operand
13672 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13673 }
13674 }
13675
13676 // C11 6.5.16p3: The type of an assignment expression is the type of the
13677 // left operand would have after lvalue conversion.
13678 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13679 // qualified type, the value has the unqualified version of the type of the
13680 // lvalue; additionally, if the lvalue has atomic type, the value has the
13681 // non-atomic version of the type of the lvalue.
13682 // C++ 5.17p1: the type of the assignment expression is that of its left
13683 // operand.
13684 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13685}
13686
13687// Scenarios to ignore if expression E is:
13688// 1. an explicit cast expression into void
13689// 2. a function call expression that returns void
13690static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
13691 E = E->IgnoreParens();
13692
13693 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13694 if (CE->getCastKind() == CK_ToVoid) {
13695 return true;
13696 }
13697
13698 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13699 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13700 CE->getSubExpr()->getType()->isDependentType()) {
13701 return true;
13702 }
13703 }
13704
13705 if (const auto *CE = dyn_cast<CallExpr>(E))
13706 return CE->getCallReturnType(Context)->isVoidType();
13707 return false;
13708}
13709
13711 // No warnings in macros
13712 if (Loc.isMacroID())
13713 return;
13714
13715 // Don't warn in template instantiations.
13717 return;
13718
13719 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13720 // instead, skip more than needed, then call back into here with the
13721 // CommaVisitor in SemaStmt.cpp.
13722 // The listed locations are the initialization and increment portions
13723 // of a for loop. The additional checks are on the condition of
13724 // if statements, do/while loops, and for loops.
13725 // Differences in scope flags for C89 mode requires the extra logic.
13726 const unsigned ForIncrementFlags =
13727 getLangOpts().C99 || getLangOpts().CPlusPlus
13730 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13731 const unsigned ScopeFlags = getCurScope()->getFlags();
13732 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13733 (ScopeFlags & ForInitFlags) == ForInitFlags)
13734 return;
13735
13736 // If there are multiple comma operators used together, get the RHS of the
13737 // of the comma operator as the LHS.
13738 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13739 if (BO->getOpcode() != BO_Comma)
13740 break;
13741 LHS = BO->getRHS();
13742 }
13743
13744 // Only allow some expressions on LHS to not warn.
13745 if (IgnoreCommaOperand(LHS, Context))
13746 return;
13747
13748 Diag(Loc, diag::warn_comma_operator);
13749 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13750 << LHS->getSourceRange()
13752 LangOpts.CPlusPlus ? "static_cast<void>("
13753 : "(void)(")
13755 ")");
13756}
13757
13758// C99 6.5.17
13761 LHS = S.CheckPlaceholderExpr(LHS.get());
13762 RHS = S.CheckPlaceholderExpr(RHS.get());
13763 if (LHS.isInvalid() || RHS.isInvalid())
13764 return QualType();
13765
13766 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13767 // operands, but not unary promotions.
13768 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13769
13770 // So we treat the LHS as a ignored value, and in C++ we allow the
13771 // containing site to determine what should be done with the RHS.
13772 LHS = S.IgnoredValueConversions(LHS.get());
13773 if (LHS.isInvalid())
13774 return QualType();
13775
13776 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13777
13778 if (!S.getLangOpts().CPlusPlus) {
13780 if (RHS.isInvalid())
13781 return QualType();
13782 if (!RHS.get()->getType()->isVoidType())
13783 S.RequireCompleteType(Loc, RHS.get()->getType(),
13784 diag::err_incomplete_type);
13785 }
13786
13787 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13788 S.DiagnoseCommaOperator(LHS.get(), Loc);
13789
13790 return RHS.get()->getType();
13791}
13792
13793/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13794/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13796 ExprValueKind &VK,
13797 ExprObjectKind &OK,
13798 SourceLocation OpLoc, bool IsInc,
13799 bool IsPrefix) {
13800 QualType ResType = Op->getType();
13801 // Atomic types can be used for increment / decrement where the non-atomic
13802 // versions can, so ignore the _Atomic() specifier for the purpose of
13803 // checking.
13804 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13805 ResType = ResAtomicType->getValueType();
13806
13807 assert(!ResType.isNull() && "no type for increment/decrement expression");
13808
13809 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13810 // Decrement of bool is not allowed.
13811 if (!IsInc) {
13812 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13813 return QualType();
13814 }
13815 // Increment of bool sets it to true, but is deprecated.
13816 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13817 : diag::warn_increment_bool)
13818 << Op->getSourceRange();
13819 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13820 // Error on enum increments and decrements in C++ mode
13821 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13822 return QualType();
13823 } else if (ResType->isRealType()) {
13824 // OK!
13825 } else if (ResType->isPointerType()) {
13826 // C99 6.5.2.4p2, 6.5.6p2
13827 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13828 return QualType();
13829 } else if (ResType->isObjCObjectPointerType()) {
13830 // On modern runtimes, ObjC pointer arithmetic is forbidden.
13831 // Otherwise, we just need a complete type.
13832 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13833 checkArithmeticOnObjCPointer(S, OpLoc, Op))
13834 return QualType();
13835 } else if (ResType->isAnyComplexType()) {
13836 // C99 does not support ++/-- on complex types, we allow as an extension.
13837 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
13838 : diag::ext_c2y_increment_complex)
13839 << IsInc << Op->getSourceRange();
13840 } else if (ResType->isPlaceholderType()) {
13842 if (PR.isInvalid()) return QualType();
13843 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13844 IsInc, IsPrefix);
13845 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13846 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13847 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13848 (ResType->castAs<VectorType>()->getVectorKind() !=
13850 // The z vector extensions allow ++ and -- for non-bool vectors.
13851 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
13852 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13853 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13854 } else {
13855 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13856 << ResType << int(IsInc) << Op->getSourceRange();
13857 return QualType();
13858 }
13859 // At this point, we know we have a real, complex or pointer type.
13860 // Now make sure the operand is a modifiable lvalue.
13861 if (CheckForModifiableLvalue(Op, OpLoc, S))
13862 return QualType();
13863 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13864 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13865 // An operand with volatile-qualified type is deprecated
13866 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13867 << IsInc << ResType;
13868 }
13869 // In C++, a prefix increment is the same type as the operand. Otherwise
13870 // (in C or with postfix), the increment is the unqualified type of the
13871 // operand.
13872 if (IsPrefix && S.getLangOpts().CPlusPlus) {
13873 VK = VK_LValue;
13874 OK = Op->getObjectKind();
13875 return ResType;
13876 } else {
13877 VK = VK_PRValue;
13878 return ResType.getUnqualifiedType();
13879 }
13880}
13881
13882/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13883/// This routine allows us to typecheck complex/recursive expressions
13884/// where the declaration is needed for type checking. We only need to
13885/// handle cases when the expression references a function designator
13886/// or is an lvalue. Here are some examples:
13887/// - &(x) => x
13888/// - &*****f => f for f a function designator.
13889/// - &s.xx => s
13890/// - &s.zz[1].yy -> s, if zz is an array
13891/// - *(x + 1) -> x, if x is an array
13892/// - &"123"[2] -> 0
13893/// - & __real__ x -> x
13894///
13895/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13896/// members.
13898 switch (E->getStmtClass()) {
13899 case Stmt::DeclRefExprClass:
13900 return cast<DeclRefExpr>(E)->getDecl();
13901 case Stmt::MemberExprClass:
13902 // If this is an arrow operator, the address is an offset from
13903 // the base's value, so the object the base refers to is
13904 // irrelevant.
13905 if (cast<MemberExpr>(E)->isArrow())
13906 return nullptr;
13907 // Otherwise, the expression refers to a part of the base
13908 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13909 case Stmt::ArraySubscriptExprClass: {
13910 // FIXME: This code shouldn't be necessary! We should catch the implicit
13911 // promotion of register arrays earlier.
13912 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13913 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13914 if (ICE->getSubExpr()->getType()->isArrayType())
13915 return getPrimaryDecl(ICE->getSubExpr());
13916 }
13917 return nullptr;
13918 }
13919 case Stmt::UnaryOperatorClass: {
13920 UnaryOperator *UO = cast<UnaryOperator>(E);
13921
13922 switch(UO->getOpcode()) {
13923 case UO_Real:
13924 case UO_Imag:
13925 case UO_Extension:
13926 return getPrimaryDecl(UO->getSubExpr());
13927 default:
13928 return nullptr;
13929 }
13930 }
13931 case Stmt::ParenExprClass:
13932 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13933 case Stmt::ImplicitCastExprClass:
13934 // If the result of an implicit cast is an l-value, we care about
13935 // the sub-expression; otherwise, the result here doesn't matter.
13936 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13937 case Stmt::CXXUuidofExprClass:
13938 return cast<CXXUuidofExpr>(E)->getGuidDecl();
13939 default:
13940 return nullptr;
13941 }
13942}
13943
13944namespace {
13945enum {
13946 AO_Bit_Field = 0,
13947 AO_Vector_Element = 1,
13948 AO_Property_Expansion = 2,
13949 AO_Register_Variable = 3,
13950 AO_Matrix_Element = 4,
13951 AO_No_Error = 5
13952};
13953}
13954/// Diagnose invalid operand for address of operations.
13955///
13956/// \param Type The type of operand which cannot have its address taken.
13958 Expr *E, unsigned Type) {
13959 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13960}
13961
13963 const Expr *Op,
13964 const CXXMethodDecl *MD) {
13965 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
13966
13967 if (Op != DRE)
13968 return Diag(OpLoc, diag::err_parens_pointer_member_function)
13969 << Op->getSourceRange();
13970
13971 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13972 if (isa<CXXDestructorDecl>(MD))
13973 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
13974 << DRE->getSourceRange();
13975
13976 if (DRE->getQualifier())
13977 return false;
13978
13979 if (MD->getParent()->getName().empty())
13980 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13981 << DRE->getSourceRange();
13982
13983 SmallString<32> Str;
13984 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13985 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13986 << DRE->getSourceRange()
13987 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
13988}
13989
13991 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13992 if (PTy->getKind() == BuiltinType::Overload) {
13993 Expr *E = OrigOp.get()->IgnoreParens();
13994 if (!isa<OverloadExpr>(E)) {
13995 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13996 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13997 << OrigOp.get()->getSourceRange();
13998 return QualType();
13999 }
14000
14001 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14002 if (isa<UnresolvedMemberExpr>(Ovl))
14004 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14005 << OrigOp.get()->getSourceRange();
14006 return QualType();
14007 }
14008
14009 return Context.OverloadTy;
14010 }
14011
14012 if (PTy->getKind() == BuiltinType::UnknownAny)
14013 return Context.UnknownAnyTy;
14014
14015 if (PTy->getKind() == BuiltinType::BoundMember) {
14016 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14017 << OrigOp.get()->getSourceRange();
14018 return QualType();
14019 }
14020
14021 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14022 if (OrigOp.isInvalid()) return QualType();
14023 }
14024
14025 if (OrigOp.get()->isTypeDependent())
14026 return Context.DependentTy;
14027
14028 assert(!OrigOp.get()->hasPlaceholderType());
14029
14030 // Make sure to ignore parentheses in subsequent checks
14031 Expr *op = OrigOp.get()->IgnoreParens();
14032
14033 // In OpenCL captures for blocks called as lambda functions
14034 // are located in the private address space. Blocks used in
14035 // enqueue_kernel can be located in a different address space
14036 // depending on a vendor implementation. Thus preventing
14037 // taking an address of the capture to avoid invalid AS casts.
14038 if (LangOpts.OpenCL) {
14039 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14040 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14041 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14042 return QualType();
14043 }
14044 }
14045
14046 if (getLangOpts().C99) {
14047 // Implement C99-only parts of addressof rules.
14048 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14049 if (uOp->getOpcode() == UO_Deref)
14050 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14051 // (assuming the deref expression is valid).
14052 return uOp->getSubExpr()->getType();
14053 }
14054 // Technically, there should be a check for array subscript
14055 // expressions here, but the result of one is always an lvalue anyway.
14056 }
14057 ValueDecl *dcl = getPrimaryDecl(op);
14058
14059 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14060 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14061 op->getBeginLoc()))
14062 return QualType();
14063
14065 unsigned AddressOfError = AO_No_Error;
14066
14067 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14068 bool sfinae = (bool)isSFINAEContext();
14069 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14070 : diag::ext_typecheck_addrof_temporary)
14071 << op->getType() << op->getSourceRange();
14072 if (sfinae)
14073 return QualType();
14074 // Materialize the temporary as an lvalue so that we can take its address.
14075 OrigOp = op =
14076 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14077 } else if (isa<ObjCSelectorExpr>(op)) {
14078 return Context.getPointerType(op->getType());
14079 } else if (lval == Expr::LV_MemberFunction) {
14080 // If it's an instance method, make a member pointer.
14081 // The expression must have exactly the form &A::foo.
14082
14083 // If the underlying expression isn't a decl ref, give up.
14084 if (!isa<DeclRefExpr>(op)) {
14085 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14086 << OrigOp.get()->getSourceRange();
14087 return QualType();
14088 }
14089 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14090 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14091
14092 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14093
14096
14097 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14098 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14099 // When pointer authentication is enabled, argument and return types of
14100 // vitual member functions must be complete. This is because vitrual
14101 // member function pointers are implemented using virtual dispatch
14102 // thunks and the thunks cannot be emitted if the argument or return
14103 // types are incomplete.
14104 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14105 SourceLocation DeclRefLoc,
14106 SourceLocation RetArgTypeLoc) {
14107 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
14108 Diag(DeclRefLoc,
14109 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14110 Diag(RetArgTypeLoc,
14111 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14112 << T;
14113 return true;
14114 }
14115 return false;
14116 };
14117 QualType RetTy = MD->getReturnType();
14118 bool IsIncomplete =
14119 !RetTy->isVoidType() &&
14120 ReturnOrParamTypeIsIncomplete(
14121 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14122 for (auto *PVD : MD->parameters())
14123 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14124 PVD->getBeginLoc());
14125 if (IsIncomplete)
14126 return QualType();
14127 }
14128
14129 // Under the MS ABI, lock down the inheritance model now.
14131 (void)isCompleteType(OpLoc, MPTy);
14132 return MPTy;
14133 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14134 // C99 6.5.3.2p1
14135 // The operand must be either an l-value or a function designator
14136 if (!op->getType()->isFunctionType()) {
14137 // Use a special diagnostic for loads from property references.
14138 if (isa<PseudoObjectExpr>(op)) {
14139 AddressOfError = AO_Property_Expansion;
14140 } else {
14141 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14142 << op->getType() << op->getSourceRange();
14143 return QualType();
14144 }
14145 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14146 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14147 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14148 }
14149
14150 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14151 // The operand cannot be a bit-field
14152 AddressOfError = AO_Bit_Field;
14153 } else if (op->getObjectKind() == OK_VectorComponent) {
14154 // The operand cannot be an element of a vector
14155 AddressOfError = AO_Vector_Element;
14156 } else if (op->getObjectKind() == OK_MatrixComponent) {
14157 // The operand cannot be an element of a matrix.
14158 AddressOfError = AO_Matrix_Element;
14159 } else if (dcl) { // C99 6.5.3.2p1
14160 // We have an lvalue with a decl. Make sure the decl is not declared
14161 // with the register storage-class specifier.
14162 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14163 // in C++ it is not error to take address of a register
14164 // variable (c++03 7.1.1P3)
14165 if (vd->getStorageClass() == SC_Register &&
14167 AddressOfError = AO_Register_Variable;
14168 }
14169 } else if (isa<MSPropertyDecl>(dcl)) {
14170 AddressOfError = AO_Property_Expansion;
14171 } else if (isa<FunctionTemplateDecl>(dcl)) {
14172 return Context.OverloadTy;
14173 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14174 // Okay: we can take the address of a field.
14175 // Could be a pointer to member, though, if there is an explicit
14176 // scope qualifier for the class.
14177
14178 // [C++26] [expr.prim.id.general]
14179 // If an id-expression E denotes a non-static non-type member
14180 // of some class C [...] and if E is a qualified-id, E is
14181 // not the un-parenthesized operand of the unary & operator [...]
14182 // the id-expression is transformed into a class member access expression.
14183 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
14184 !isa<ParenExpr>(OrigOp.get())) {
14185 DeclContext *Ctx = dcl->getDeclContext();
14186 if (Ctx && Ctx->isRecord()) {
14187 if (dcl->getType()->isReferenceType()) {
14188 Diag(OpLoc,
14189 diag::err_cannot_form_pointer_to_member_of_reference_type)
14190 << dcl->getDeclName() << dcl->getType();
14191 return QualType();
14192 }
14193
14194 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14195 Ctx = Ctx->getParent();
14196
14198 op->getType(),
14199 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14200 // Under the MS ABI, lock down the inheritance model now.
14202 (void)isCompleteType(OpLoc, MPTy);
14203 return MPTy;
14204 }
14205 }
14208 llvm_unreachable("Unknown/unexpected decl type");
14209 }
14210
14211 if (AddressOfError != AO_No_Error) {
14212 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14213 return QualType();
14214 }
14215
14216 if (lval == Expr::LV_IncompleteVoidType) {
14217 // Taking the address of a void variable is technically illegal, but we
14218 // allow it in cases which are otherwise valid.
14219 // Example: "extern void x; void* y = &x;".
14220 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14221 }
14222
14223 // If the operand has type "type", the result has type "pointer to type".
14224 if (op->getType()->isObjCObjectType())
14226
14227 // Cannot take the address of WebAssembly references or tables.
14228 if (Context.getTargetInfo().getTriple().isWasm()) {
14229 QualType OpTy = op->getType();
14230 if (OpTy.isWebAssemblyReferenceType()) {
14231 Diag(OpLoc, diag::err_wasm_ca_reference)
14232 << 1 << OrigOp.get()->getSourceRange();
14233 return QualType();
14234 }
14235 if (OpTy->isWebAssemblyTableType()) {
14236 Diag(OpLoc, diag::err_wasm_table_pr)
14237 << 1 << OrigOp.get()->getSourceRange();
14238 return QualType();
14239 }
14240 }
14241
14242 CheckAddressOfPackedMember(op);
14243
14244 return Context.getPointerType(op->getType());
14245}
14246
14247static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14248 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14249 if (!DRE)
14250 return;
14251 const Decl *D = DRE->getDecl();
14252 if (!D)
14253 return;
14254 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14255 if (!Param)
14256 return;
14257 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14258 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14259 return;
14260 if (FunctionScopeInfo *FD = S.getCurFunction())
14261 FD->ModifiedNonNullParams.insert(Param);
14262}
14263
14264/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14266 SourceLocation OpLoc,
14267 bool IsAfterAmp = false) {
14268 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14269 if (ConvResult.isInvalid())
14270 return QualType();
14271 Op = ConvResult.get();
14272 QualType OpTy = Op->getType();
14274
14275 if (isa<CXXReinterpretCastExpr>(Op)) {
14276 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14277 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14278 Op->getSourceRange());
14279 }
14280
14281 if (const PointerType *PT = OpTy->getAs<PointerType>())
14282 {
14283 Result = PT->getPointeeType();
14284 }
14285 else if (const ObjCObjectPointerType *OPT =
14287 Result = OPT->getPointeeType();
14288 else {
14290 if (PR.isInvalid()) return QualType();
14291 if (PR.get() != Op)
14292 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14293 }
14294
14295 if (Result.isNull()) {
14296 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14297 << OpTy << Op->getSourceRange();
14298 return QualType();
14299 }
14300
14301 if (Result->isVoidType()) {
14302 // C++ [expr.unary.op]p1:
14303 // [...] the expression to which [the unary * operator] is applied shall
14304 // be a pointer to an object type, or a pointer to a function type
14305 LangOptions LO = S.getLangOpts();
14306 if (LO.CPlusPlus)
14307 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14308 << OpTy << Op->getSourceRange();
14309 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14310 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14311 << OpTy << Op->getSourceRange();
14312 }
14313
14314 // Dereferences are usually l-values...
14315 VK = VK_LValue;
14316
14317 // ...except that certain expressions are never l-values in C.
14318 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14319 VK = VK_PRValue;
14320
14321 return Result;
14322}
14323
14324BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14326 switch (Kind) {
14327 default: llvm_unreachable("Unknown binop!");
14328 case tok::periodstar: Opc = BO_PtrMemD; break;
14329 case tok::arrowstar: Opc = BO_PtrMemI; break;
14330 case tok::star: Opc = BO_Mul; break;
14331 case tok::slash: Opc = BO_Div; break;
14332 case tok::percent: Opc = BO_Rem; break;
14333 case tok::plus: Opc = BO_Add; break;
14334 case tok::minus: Opc = BO_Sub; break;
14335 case tok::lessless: Opc = BO_Shl; break;
14336 case tok::greatergreater: Opc = BO_Shr; break;
14337 case tok::lessequal: Opc = BO_LE; break;
14338 case tok::less: Opc = BO_LT; break;
14339 case tok::greaterequal: Opc = BO_GE; break;
14340 case tok::greater: Opc = BO_GT; break;
14341 case tok::exclaimequal: Opc = BO_NE; break;
14342 case tok::equalequal: Opc = BO_EQ; break;
14343 case tok::spaceship: Opc = BO_Cmp; break;
14344 case tok::amp: Opc = BO_And; break;
14345 case tok::caret: Opc = BO_Xor; break;
14346 case tok::pipe: Opc = BO_Or; break;
14347 case tok::ampamp: Opc = BO_LAnd; break;
14348 case tok::pipepipe: Opc = BO_LOr; break;
14349 case tok::equal: Opc = BO_Assign; break;
14350 case tok::starequal: Opc = BO_MulAssign; break;
14351 case tok::slashequal: Opc = BO_DivAssign; break;
14352 case tok::percentequal: Opc = BO_RemAssign; break;
14353 case tok::plusequal: Opc = BO_AddAssign; break;
14354 case tok::minusequal: Opc = BO_SubAssign; break;
14355 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14356 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14357 case tok::ampequal: Opc = BO_AndAssign; break;
14358 case tok::caretequal: Opc = BO_XorAssign; break;
14359 case tok::pipeequal: Opc = BO_OrAssign; break;
14360 case tok::comma: Opc = BO_Comma; break;
14361 }
14362 return Opc;
14363}
14364
14366 tok::TokenKind Kind) {
14368 switch (Kind) {
14369 default: llvm_unreachable("Unknown unary op!");
14370 case tok::plusplus: Opc = UO_PreInc; break;
14371 case tok::minusminus: Opc = UO_PreDec; break;
14372 case tok::amp: Opc = UO_AddrOf; break;
14373 case tok::star: Opc = UO_Deref; break;
14374 case tok::plus: Opc = UO_Plus; break;
14375 case tok::minus: Opc = UO_Minus; break;
14376 case tok::tilde: Opc = UO_Not; break;
14377 case tok::exclaim: Opc = UO_LNot; break;
14378 case tok::kw___real: Opc = UO_Real; break;
14379 case tok::kw___imag: Opc = UO_Imag; break;
14380 case tok::kw___extension__: Opc = UO_Extension; break;
14381 }
14382 return Opc;
14383}
14384
14385const FieldDecl *
14387 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14388 // common for setters.
14389 // struct A {
14390 // int X;
14391 // -void setX(int X) { X = X; }
14392 // +void setX(int X) { this->X = X; }
14393 // };
14394
14395 // Only consider parameters for self assignment fixes.
14396 if (!isa<ParmVarDecl>(SelfAssigned))
14397 return nullptr;
14398 const auto *Method =
14399 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14400 if (!Method)
14401 return nullptr;
14402
14403 const CXXRecordDecl *Parent = Method->getParent();
14404 // In theory this is fixable if the lambda explicitly captures this, but
14405 // that's added complexity that's rarely going to be used.
14406 if (Parent->isLambda())
14407 return nullptr;
14408
14409 // FIXME: Use an actual Lookup operation instead of just traversing fields
14410 // in order to get base class fields.
14411 auto Field =
14412 llvm::find_if(Parent->fields(),
14413 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14414 return F->getDeclName() == Name;
14415 });
14416 return (Field != Parent->field_end()) ? *Field : nullptr;
14417}
14418
14419/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14420/// This warning suppressed in the event of macro expansions.
14421static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14422 SourceLocation OpLoc, bool IsBuiltin) {
14424 return;
14425 if (S.isUnevaluatedContext())
14426 return;
14427 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14428 return;
14429 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14430 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14431 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14432 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14433 if (!LHSDeclRef || !RHSDeclRef ||
14434 LHSDeclRef->getLocation().isMacroID() ||
14435 RHSDeclRef->getLocation().isMacroID())
14436 return;
14437 const ValueDecl *LHSDecl =
14438 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14439 const ValueDecl *RHSDecl =
14440 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14441 if (LHSDecl != RHSDecl)
14442 return;
14443 if (LHSDecl->getType().isVolatileQualified())
14444 return;
14445 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14446 if (RefTy->getPointeeType().isVolatileQualified())
14447 return;
14448
14449 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14450 : diag::warn_self_assignment_overloaded)
14451 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14452 << RHSExpr->getSourceRange();
14453 if (const FieldDecl *SelfAssignField =
14455 Diag << 1 << SelfAssignField
14456 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14457 else
14458 Diag << 0;
14459}
14460
14461/// Check if a bitwise-& is performed on an Objective-C pointer. This
14462/// is usually indicative of introspection within the Objective-C pointer.
14464 SourceLocation OpLoc) {
14465 if (!S.getLangOpts().ObjC)
14466 return;
14467
14468 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14469 const Expr *LHS = L.get();
14470 const Expr *RHS = R.get();
14471
14473 ObjCPointerExpr = LHS;
14474 OtherExpr = RHS;
14475 }
14476 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14477 ObjCPointerExpr = RHS;
14478 OtherExpr = LHS;
14479 }
14480
14481 // This warning is deliberately made very specific to reduce false
14482 // positives with logic that uses '&' for hashing. This logic mainly
14483 // looks for code trying to introspect into tagged pointers, which
14484 // code should generally never do.
14485 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14486 unsigned Diag = diag::warn_objc_pointer_masking;
14487 // Determine if we are introspecting the result of performSelectorXXX.
14488 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14489 // Special case messages to -performSelector and friends, which
14490 // can return non-pointer values boxed in a pointer value.
14491 // Some clients may wish to silence warnings in this subcase.
14492 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14493 Selector S = ME->getSelector();
14494 StringRef SelArg0 = S.getNameForSlot(0);
14495 if (SelArg0.starts_with("performSelector"))
14496 Diag = diag::warn_objc_pointer_masking_performSelector;
14497 }
14498
14499 S.Diag(OpLoc, Diag)
14500 << ObjCPointerExpr->getSourceRange();
14501 }
14502}
14503
14505 if (!E)
14506 return nullptr;
14507 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14508 return DRE->getDecl();
14509 if (auto *ME = dyn_cast<MemberExpr>(E))
14510 return ME->getMemberDecl();
14511 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14512 return IRE->getDecl();
14513 return nullptr;
14514}
14515
14516// This helper function promotes a binary operator's operands (which are of a
14517// half vector type) to a vector of floats and then truncates the result to
14518// a vector of either half or short.
14520 BinaryOperatorKind Opc, QualType ResultTy,
14522 bool IsCompAssign, SourceLocation OpLoc,
14523 FPOptionsOverride FPFeatures) {
14524 auto &Context = S.getASTContext();
14525 assert((isVector(ResultTy, Context.HalfTy) ||
14526 isVector(ResultTy, Context.ShortTy)) &&
14527 "Result must be a vector of half or short");
14528 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14529 isVector(RHS.get()->getType(), Context.HalfTy) &&
14530 "both operands expected to be a half vector");
14531
14532 RHS = convertVector(RHS.get(), Context.FloatTy, S);
14533 QualType BinOpResTy = RHS.get()->getType();
14534
14535 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14536 // change BinOpResTy to a vector of ints.
14537 if (isVector(ResultTy, Context.ShortTy))
14538 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14539
14540 if (IsCompAssign)
14541 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14542 ResultTy, VK, OK, OpLoc, FPFeatures,
14543 BinOpResTy, BinOpResTy);
14544
14545 LHS = convertVector(LHS.get(), Context.FloatTy, S);
14546 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14547 BinOpResTy, VK, OK, OpLoc, FPFeatures);
14548 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14549}
14550
14551static std::pair<ExprResult, ExprResult>
14553 Expr *RHSExpr) {
14554 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14555 if (!S.Context.isDependenceAllowed()) {
14556 // C cannot handle TypoExpr nodes on either side of a binop because it
14557 // doesn't handle dependent types properly, so make sure any TypoExprs have
14558 // been dealt with before checking the operands.
14559 LHS = S.CorrectDelayedTyposInExpr(LHS);
14561 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14562 [Opc, LHS](Expr *E) {
14563 if (Opc != BO_Assign)
14564 return ExprResult(E);
14565 // Avoid correcting the RHS to the same Expr as the LHS.
14566 Decl *D = getDeclFromExpr(E);
14567 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14568 });
14569 }
14570 return std::make_pair(LHS, RHS);
14571}
14572
14573/// Returns true if conversion between vectors of halfs and vectors of floats
14574/// is needed.
14575static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14576 Expr *E0, Expr *E1 = nullptr) {
14577 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14579 return false;
14580
14581 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14582 QualType Ty = E->IgnoreImplicit()->getType();
14583
14584 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14585 // to vectors of floats. Although the element type of the vectors is __fp16,
14586 // the vectors shouldn't be treated as storage-only types. See the
14587 // discussion here: https://reviews.llvm.org/rG825235c140e7
14588 if (const VectorType *VT = Ty->getAs<VectorType>()) {
14589 if (VT->getVectorKind() == VectorKind::Neon)
14590 return false;
14591 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14592 }
14593 return false;
14594 };
14595
14596 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14597}
14598
14601 Expr *LHSExpr, Expr *RHSExpr) {
14602 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14603 // The syntax only allows initializer lists on the RHS of assignment,
14604 // so we don't need to worry about accepting invalid code for
14605 // non-assignment operators.
14606 // C++11 5.17p9:
14607 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14608 // of x = {} is x = T().
14610 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14611 InitializedEntity Entity =
14613 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14614 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14615 if (Init.isInvalid())
14616 return Init;
14617 RHSExpr = Init.get();
14618 }
14619
14620 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14621 QualType ResultTy; // Result type of the binary operator.
14622 // The following two variables are used for compound assignment operators
14623 QualType CompLHSTy; // Type of LHS after promotions for computation
14624 QualType CompResultTy; // Type of computation result
14627 bool ConvertHalfVec = false;
14628
14629 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14630 if (!LHS.isUsable() || !RHS.isUsable())
14631 return ExprError();
14632
14633 if (getLangOpts().OpenCL) {
14634 QualType LHSTy = LHSExpr->getType();
14635 QualType RHSTy = RHSExpr->getType();
14636 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14637 // the ATOMIC_VAR_INIT macro.
14638 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14639 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14640 if (BO_Assign == Opc)
14641 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14642 else
14643 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14644 return ExprError();
14645 }
14646
14647 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14648 // only with a builtin functions and therefore should be disallowed here.
14649 if (LHSTy->isImageType() || RHSTy->isImageType() ||
14650 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14651 LHSTy->isPipeType() || RHSTy->isPipeType() ||
14652 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14653 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14654 return ExprError();
14655 }
14656 }
14657
14658 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14659 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14660
14661 switch (Opc) {
14662 case BO_Assign:
14663 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
14664 if (getLangOpts().CPlusPlus &&
14665 LHS.get()->getObjectKind() != OK_ObjCProperty) {
14666 VK = LHS.get()->getValueKind();
14667 OK = LHS.get()->getObjectKind();
14668 }
14669 if (!ResultTy.isNull()) {
14670 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14671 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14672
14673 // Avoid copying a block to the heap if the block is assigned to a local
14674 // auto variable that is declared in the same scope as the block. This
14675 // optimization is unsafe if the local variable is declared in an outer
14676 // scope. For example:
14677 //
14678 // BlockTy b;
14679 // {
14680 // b = ^{...};
14681 // }
14682 // // It is unsafe to invoke the block here if it wasn't copied to the
14683 // // heap.
14684 // b();
14685
14686 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14687 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14688 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14689 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14690 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14691
14693 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14695 }
14696 RecordModifiableNonNullParam(*this, LHS.get());
14697 break;
14698 case BO_PtrMemD:
14699 case BO_PtrMemI:
14700 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14701 Opc == BO_PtrMemI);
14702 break;
14703 case BO_Mul:
14704 case BO_Div:
14705 ConvertHalfVec = true;
14706 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14707 Opc == BO_Div);
14708 break;
14709 case BO_Rem:
14710 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14711 break;
14712 case BO_Add:
14713 ConvertHalfVec = true;
14714 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14715 break;
14716 case BO_Sub:
14717 ConvertHalfVec = true;
14718 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14719 break;
14720 case BO_Shl:
14721 case BO_Shr:
14722 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14723 break;
14724 case BO_LE:
14725 case BO_LT:
14726 case BO_GE:
14727 case BO_GT:
14728 ConvertHalfVec = true;
14729 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14730
14731 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
14732 BI && BI->isComparisonOp())
14733 Diag(OpLoc, diag::warn_consecutive_comparison);
14734
14735 break;
14736 case BO_EQ:
14737 case BO_NE:
14738 ConvertHalfVec = true;
14739 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14740 break;
14741 case BO_Cmp:
14742 ConvertHalfVec = true;
14743 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14744 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14745 break;
14746 case BO_And:
14747 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14748 [[fallthrough]];
14749 case BO_Xor:
14750 case BO_Or:
14751 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14752 break;
14753 case BO_LAnd:
14754 case BO_LOr:
14755 ConvertHalfVec = true;
14756 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14757 break;
14758 case BO_MulAssign:
14759 case BO_DivAssign:
14760 ConvertHalfVec = true;
14761 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14762 Opc == BO_DivAssign);
14763 CompLHSTy = CompResultTy;
14764 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14765 ResultTy =
14766 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14767 break;
14768 case BO_RemAssign:
14769 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14770 CompLHSTy = CompResultTy;
14771 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14772 ResultTy =
14773 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14774 break;
14775 case BO_AddAssign:
14776 ConvertHalfVec = true;
14777 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14778 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14779 ResultTy =
14780 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14781 break;
14782 case BO_SubAssign:
14783 ConvertHalfVec = true;
14784 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14785 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14786 ResultTy =
14787 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14788 break;
14789 case BO_ShlAssign:
14790 case BO_ShrAssign:
14791 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14792 CompLHSTy = CompResultTy;
14793 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14794 ResultTy =
14795 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14796 break;
14797 case BO_AndAssign:
14798 case BO_OrAssign: // fallthrough
14799 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14800 [[fallthrough]];
14801 case BO_XorAssign:
14802 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14803 CompLHSTy = CompResultTy;
14804 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14805 ResultTy =
14806 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14807 break;
14808 case BO_Comma:
14809 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14810 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14811 VK = RHS.get()->getValueKind();
14812 OK = RHS.get()->getObjectKind();
14813 }
14814 break;
14815 }
14816 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14817 return ExprError();
14818
14819 // Some of the binary operations require promoting operands of half vector to
14820 // float vectors and truncating the result back to half vector. For now, we do
14821 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14822 // arm64).
14823 assert(
14824 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14825 isVector(LHS.get()->getType(), Context.HalfTy)) &&
14826 "both sides are half vectors or neither sides are");
14827 ConvertHalfVec =
14828 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14829
14830 // Check for array bounds violations for both sides of the BinaryOperator
14831 CheckArrayAccess(LHS.get());
14832 CheckArrayAccess(RHS.get());
14833
14834 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14835 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14836 &Context.Idents.get("object_setClass"),
14838 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14839 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14840 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14842 "object_setClass(")
14843 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14844 ",")
14845 << FixItHint::CreateInsertion(RHSLocEnd, ")");
14846 }
14847 else
14848 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14849 }
14850 else if (const ObjCIvarRefExpr *OIRE =
14851 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14852 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14853
14854 // Opc is not a compound assignment if CompResultTy is null.
14855 if (CompResultTy.isNull()) {
14856 if (ConvertHalfVec)
14857 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14858 OpLoc, CurFPFeatureOverrides());
14859 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14860 VK, OK, OpLoc, CurFPFeatureOverrides());
14861 }
14862
14863 // Handle compound assignments.
14864 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14866 VK = VK_LValue;
14867 OK = LHS.get()->getObjectKind();
14868 }
14869
14870 // The LHS is not converted to the result type for fixed-point compound
14871 // assignment as the common type is computed on demand. Reset the CompLHSTy
14872 // to the LHS type we would have gotten after unary conversions.
14873 if (CompResultTy->isFixedPointType())
14874 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14875
14876 if (ConvertHalfVec)
14877 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14878 OpLoc, CurFPFeatureOverrides());
14879
14881 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14882 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14883}
14884
14885/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14886/// operators are mixed in a way that suggests that the programmer forgot that
14887/// comparison operators have higher precedence. The most typical example of
14888/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14890 SourceLocation OpLoc, Expr *LHSExpr,
14891 Expr *RHSExpr) {
14892 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14893 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14894
14895 // Check that one of the sides is a comparison operator and the other isn't.
14896 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14897 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14898 if (isLeftComp == isRightComp)
14899 return;
14900
14901 // Bitwise operations are sometimes used as eager logical ops.
14902 // Don't diagnose this.
14903 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14904 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14905 if (isLeftBitwise || isRightBitwise)
14906 return;
14907
14908 SourceRange DiagRange = isLeftComp
14909 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14910 : SourceRange(OpLoc, RHSExpr->getEndLoc());
14911 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14912 SourceRange ParensRange =
14913 isLeftComp
14914 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14915 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14916
14917 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14918 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14919 SuggestParentheses(Self, OpLoc,
14920 Self.PDiag(diag::note_precedence_silence) << OpStr,
14921 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14922 SuggestParentheses(Self, OpLoc,
14923 Self.PDiag(diag::note_precedence_bitwise_first)
14925 ParensRange);
14926}
14927
14928/// It accepts a '&&' expr that is inside a '||' one.
14929/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14930/// in parentheses.
14931static void
14933 BinaryOperator *Bop) {
14934 assert(Bop->getOpcode() == BO_LAnd);
14935 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14936 << Bop->getSourceRange() << OpLoc;
14938 Self.PDiag(diag::note_precedence_silence)
14939 << Bop->getOpcodeStr(),
14940 Bop->getSourceRange());
14941}
14942
14943/// Look for '&&' in the left hand of a '||' expr.
14945 Expr *LHSExpr, Expr *RHSExpr) {
14946 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14947 if (Bop->getOpcode() == BO_LAnd) {
14948 // If it's "string_literal && a || b" don't warn since the precedence
14949 // doesn't matter.
14950 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
14951 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14952 } else if (Bop->getOpcode() == BO_LOr) {
14953 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14954 // If it's "a || b && string_literal || c" we didn't warn earlier for
14955 // "a || b && string_literal", but warn now.
14956 if (RBop->getOpcode() == BO_LAnd &&
14957 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
14958 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14959 }
14960 }
14961 }
14962}
14963
14964/// Look for '&&' in the right hand of a '||' expr.
14966 Expr *LHSExpr, Expr *RHSExpr) {
14967 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14968 if (Bop->getOpcode() == BO_LAnd) {
14969 // If it's "a || b && string_literal" don't warn since the precedence
14970 // doesn't matter.
14971 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
14972 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14973 }
14974 }
14975}
14976
14977/// Look for bitwise op in the left or right hand of a bitwise op with
14978/// lower precedence and emit a diagnostic together with a fixit hint that wraps
14979/// the '&' expression in parentheses.
14981 SourceLocation OpLoc, Expr *SubExpr) {
14982 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14983 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14984 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14985 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14986 << Bop->getSourceRange() << OpLoc;
14987 SuggestParentheses(S, Bop->getOperatorLoc(),
14988 S.PDiag(diag::note_precedence_silence)
14989 << Bop->getOpcodeStr(),
14990 Bop->getSourceRange());
14991 }
14992 }
14993}
14994
14996 Expr *SubExpr, StringRef Shift) {
14997 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14998 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14999 StringRef Op = Bop->getOpcodeStr();
15000 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15001 << Bop->getSourceRange() << OpLoc << Shift << Op;
15002 SuggestParentheses(S, Bop->getOperatorLoc(),
15003 S.PDiag(diag::note_precedence_silence) << Op,
15004 Bop->getSourceRange());
15005 }
15006 }
15007}
15008
15010 Expr *LHSExpr, Expr *RHSExpr) {
15011 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15012 if (!OCE)
15013 return;
15014
15015 FunctionDecl *FD = OCE->getDirectCallee();
15016 if (!FD || !FD->isOverloadedOperator())
15017 return;
15018
15020 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15021 return;
15022
15023 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15024 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15025 << (Kind == OO_LessLess);
15027 S.PDiag(diag::note_precedence_silence)
15028 << (Kind == OO_LessLess ? "<<" : ">>"),
15029 OCE->getSourceRange());
15031 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15032 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15033}
15034
15035/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15036/// precedence.
15038 SourceLocation OpLoc, Expr *LHSExpr,
15039 Expr *RHSExpr){
15040 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15042 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15043
15044 // Diagnose "arg1 & arg2 | arg3"
15045 if ((Opc == BO_Or || Opc == BO_Xor) &&
15046 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15047 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15048 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15049 }
15050
15051 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15052 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15053 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15054 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15055 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15056 }
15057
15058 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15059 || Opc == BO_Shr) {
15060 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15061 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15062 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15063 }
15064
15065 // Warn on overloaded shift operators and comparisons, such as:
15066 // cout << 5 == 4;
15068 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15069}
15070
15072 tok::TokenKind Kind,
15073 Expr *LHSExpr, Expr *RHSExpr) {
15074 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15075 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15076 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15077
15078 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15079 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15080
15081 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15082}
15083
15085 UnresolvedSetImpl &Functions) {
15087 if (OverOp != OO_None && OverOp != OO_Equal)
15088 LookupOverloadedOperatorName(OverOp, S, Functions);
15089
15090 // In C++20 onwards, we may have a second operator to look up.
15091 if (getLangOpts().CPlusPlus20) {
15093 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15094 }
15095}
15096
15097/// Build an overloaded binary operator expression in the given scope.
15100 Expr *LHS, Expr *RHS) {
15101 switch (Opc) {
15102 case BO_Assign:
15103 // In the non-overloaded case, we warn about self-assignment (x = x) for
15104 // both simple assignment and certain compound assignments where algebra
15105 // tells us the operation yields a constant result. When the operator is
15106 // overloaded, we can't do the latter because we don't want to assume that
15107 // those algebraic identities still apply; for example, a path-building
15108 // library might use operator/= to append paths. But it's still reasonable
15109 // to assume that simple assignment is just moving/copying values around
15110 // and so self-assignment is likely a bug.
15111 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15112 [[fallthrough]];
15113 case BO_DivAssign:
15114 case BO_RemAssign:
15115 case BO_SubAssign:
15116 case BO_AndAssign:
15117 case BO_OrAssign:
15118 case BO_XorAssign:
15119 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15120 break;
15121 default:
15122 break;
15123 }
15124
15125 // Find all of the overloaded operators visible from this point.
15126 UnresolvedSet<16> Functions;
15127 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15128
15129 // Build the (potentially-overloaded, potentially-dependent)
15130 // binary operation.
15131 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15132}
15133
15136 Expr *LHSExpr, Expr *RHSExpr) {
15137 ExprResult LHS, RHS;
15138 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15139 if (!LHS.isUsable() || !RHS.isUsable())
15140 return ExprError();
15141 LHSExpr = LHS.get();
15142 RHSExpr = RHS.get();
15143
15144 // We want to end up calling one of SemaPseudoObject::checkAssignment
15145 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15146 // both expressions are overloadable or either is type-dependent),
15147 // or CreateBuiltinBinOp (in any other case). We also want to get
15148 // any placeholder types out of the way.
15149
15150 // Handle pseudo-objects in the LHS.
15151 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15152 // Assignments with a pseudo-object l-value need special analysis.
15153 if (pty->getKind() == BuiltinType::PseudoObject &&
15155 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15156
15157 // Don't resolve overloads if the other type is overloadable.
15158 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15159 // We can't actually test that if we still have a placeholder,
15160 // though. Fortunately, none of the exceptions we see in that
15161 // code below are valid when the LHS is an overload set. Note
15162 // that an overload set can be dependently-typed, but it never
15163 // instantiates to having an overloadable type.
15164 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15165 if (resolvedRHS.isInvalid()) return ExprError();
15166 RHSExpr = resolvedRHS.get();
15167
15168 if (RHSExpr->isTypeDependent() ||
15169 RHSExpr->getType()->isOverloadableType())
15170 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15171 }
15172
15173 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15174 // template, diagnose the missing 'template' keyword instead of diagnosing
15175 // an invalid use of a bound member function.
15176 //
15177 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15178 // to C++1z [over.over]/1.4, but we already checked for that case above.
15179 if (Opc == BO_LT && inTemplateInstantiation() &&
15180 (pty->getKind() == BuiltinType::BoundMember ||
15181 pty->getKind() == BuiltinType::Overload)) {
15182 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15183 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15184 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15185 return isa<FunctionTemplateDecl>(ND);
15186 })) {
15187 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15188 : OE->getNameLoc(),
15189 diag::err_template_kw_missing)
15190 << OE->getName().getAsString() << "";
15191 return ExprError();
15192 }
15193 }
15194
15195 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15196 if (LHS.isInvalid()) return ExprError();
15197 LHSExpr = LHS.get();
15198 }
15199
15200 // Handle pseudo-objects in the RHS.
15201 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15202 // An overload in the RHS can potentially be resolved by the type
15203 // being assigned to.
15204 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15205 if (getLangOpts().CPlusPlus &&
15206 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15207 LHSExpr->getType()->isOverloadableType()))
15208 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15209
15210 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15211 }
15212
15213 // Don't resolve overloads if the other type is overloadable.
15214 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15215 LHSExpr->getType()->isOverloadableType())
15216 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15217
15218 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15219 if (!resolvedRHS.isUsable()) return ExprError();
15220 RHSExpr = resolvedRHS.get();
15221 }
15222
15223 if (getLangOpts().CPlusPlus) {
15224 // Otherwise, build an overloaded op if either expression is type-dependent
15225 // or has an overloadable type.
15226 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15227 LHSExpr->getType()->isOverloadableType() ||
15228 RHSExpr->getType()->isOverloadableType())
15229 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15230 }
15231
15232 if (getLangOpts().RecoveryAST &&
15233 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15234 assert(!getLangOpts().CPlusPlus);
15235 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15236 "Should only occur in error-recovery path.");
15238 // C [6.15.16] p3:
15239 // An assignment expression has the value of the left operand after the
15240 // assignment, but is not an lvalue.
15242 Context, LHSExpr, RHSExpr, Opc,
15244 OpLoc, CurFPFeatureOverrides());
15245 QualType ResultType;
15246 switch (Opc) {
15247 case BO_Assign:
15248 ResultType = LHSExpr->getType().getUnqualifiedType();
15249 break;
15250 case BO_LT:
15251 case BO_GT:
15252 case BO_LE:
15253 case BO_GE:
15254 case BO_EQ:
15255 case BO_NE:
15256 case BO_LAnd:
15257 case BO_LOr:
15258 // These operators have a fixed result type regardless of operands.
15259 ResultType = Context.IntTy;
15260 break;
15261 case BO_Comma:
15262 ResultType = RHSExpr->getType();
15263 break;
15264 default:
15265 ResultType = Context.DependentTy;
15266 break;
15267 }
15268 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15269 VK_PRValue, OK_Ordinary, OpLoc,
15271 }
15272
15273 // Build a built-in binary operation.
15274 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15275}
15276
15278 if (T.isNull() || T->isDependentType())
15279 return false;
15280
15281 if (!Ctx.isPromotableIntegerType(T))
15282 return true;
15283
15284 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15285}
15286
15288 UnaryOperatorKind Opc, Expr *InputExpr,
15289 bool IsAfterAmp) {
15290 ExprResult Input = InputExpr;
15293 QualType resultType;
15294 bool CanOverflow = false;
15295
15296 bool ConvertHalfVec = false;
15297 if (getLangOpts().OpenCL) {
15298 QualType Ty = InputExpr->getType();
15299 // The only legal unary operation for atomics is '&'.
15300 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15301 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15302 // only with a builtin functions and therefore should be disallowed here.
15303 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15304 || Ty->isBlockPointerType())) {
15305 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15306 << InputExpr->getType()
15307 << Input.get()->getSourceRange());
15308 }
15309 }
15310
15311 if (getLangOpts().HLSL && OpLoc.isValid()) {
15312 if (Opc == UO_AddrOf)
15313 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15314 if (Opc == UO_Deref)
15315 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15316 }
15317
15318 if (InputExpr->isTypeDependent() &&
15319 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
15320 resultType = Context.DependentTy;
15321 } else {
15322 switch (Opc) {
15323 case UO_PreInc:
15324 case UO_PreDec:
15325 case UO_PostInc:
15326 case UO_PostDec:
15327 resultType =
15328 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
15329 Opc == UO_PreInc || Opc == UO_PostInc,
15330 Opc == UO_PreInc || Opc == UO_PreDec);
15331 CanOverflow = isOverflowingIntegerType(Context, resultType);
15332 break;
15333 case UO_AddrOf:
15334 resultType = CheckAddressOfOperand(Input, OpLoc);
15335 CheckAddressOfNoDeref(InputExpr);
15336 RecordModifiableNonNullParam(*this, InputExpr);
15337 break;
15338 case UO_Deref: {
15340 if (Input.isInvalid())
15341 return ExprError();
15342 resultType =
15343 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15344 break;
15345 }
15346 case UO_Plus:
15347 case UO_Minus:
15348 CanOverflow = Opc == UO_Minus &&
15350 Input = UsualUnaryConversions(Input.get());
15351 if (Input.isInvalid())
15352 return ExprError();
15353 // Unary plus and minus require promoting an operand of half vector to a
15354 // float vector and truncating the result back to a half vector. For now,
15355 // we do this only when HalfArgsAndReturns is set (that is, when the
15356 // target is arm or arm64).
15357 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15358
15359 // If the operand is a half vector, promote it to a float vector.
15360 if (ConvertHalfVec)
15361 Input = convertVector(Input.get(), Context.FloatTy, *this);
15362 resultType = Input.get()->getType();
15363 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15364 break;
15365 else if (resultType->isVectorType() &&
15366 // The z vector extensions don't allow + or - with bool vectors.
15367 (!Context.getLangOpts().ZVector ||
15368 resultType->castAs<VectorType>()->getVectorKind() !=
15370 break;
15371 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
15372 break;
15373 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15374 Opc == UO_Plus && resultType->isPointerType())
15375 break;
15376
15377 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15378 << resultType << Input.get()->getSourceRange());
15379
15380 case UO_Not: // bitwise complement
15381 Input = UsualUnaryConversions(Input.get());
15382 if (Input.isInvalid())
15383 return ExprError();
15384 resultType = Input.get()->getType();
15385 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15386 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15387 // C99 does not support '~' for complex conjugation.
15388 Diag(OpLoc, diag::ext_integer_complement_complex)
15389 << resultType << Input.get()->getSourceRange();
15390 else if (resultType->hasIntegerRepresentation())
15391 break;
15392 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15393 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15394 // on vector float types.
15395 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15396 if (!T->isIntegerType())
15397 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15398 << resultType << Input.get()->getSourceRange());
15399 } else {
15400 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15401 << resultType << Input.get()->getSourceRange());
15402 }
15403 break;
15404
15405 case UO_LNot: // logical negation
15406 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15408 if (Input.isInvalid())
15409 return ExprError();
15410 resultType = Input.get()->getType();
15411
15412 // Though we still have to promote half FP to float...
15413 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15414 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
15415 .get();
15416 resultType = Context.FloatTy;
15417 }
15418
15419 // WebAsembly tables can't be used in unary expressions.
15420 if (resultType->isPointerType() &&
15422 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15423 << resultType << Input.get()->getSourceRange());
15424 }
15425
15426 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15427 // C99 6.5.3.3p1: ok, fallthrough;
15428 if (Context.getLangOpts().CPlusPlus) {
15429 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15430 // operand contextually converted to bool.
15431 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15432 ScalarTypeToBooleanCastKind(resultType));
15433 } else if (Context.getLangOpts().OpenCL &&
15434 Context.getLangOpts().OpenCLVersion < 120) {
15435 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15436 // operate on scalar float types.
15437 if (!resultType->isIntegerType() && !resultType->isPointerType())
15438 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15439 << resultType << Input.get()->getSourceRange());
15440 }
15441 } else if (resultType->isExtVectorType()) {
15442 if (Context.getLangOpts().OpenCL &&
15444 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15445 // operate on vector float types.
15446 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15447 if (!T->isIntegerType())
15448 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15449 << resultType << Input.get()->getSourceRange());
15450 }
15451 // Vector logical not returns the signed variant of the operand type.
15452 resultType = GetSignedVectorType(resultType);
15453 break;
15454 } else if (Context.getLangOpts().CPlusPlus &&
15455 resultType->isVectorType()) {
15456 const VectorType *VTy = resultType->castAs<VectorType>();
15457 if (VTy->getVectorKind() != VectorKind::Generic)
15458 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15459 << resultType << Input.get()->getSourceRange());
15460
15461 // Vector logical not returns the signed variant of the operand type.
15462 resultType = GetSignedVectorType(resultType);
15463 break;
15464 } else {
15465 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15466 << resultType << Input.get()->getSourceRange());
15467 }
15468
15469 // LNot always has type int. C99 6.5.3.3p5.
15470 // In C++, it's bool. C++ 5.3.1p8
15471 resultType = Context.getLogicalOperationType();
15472 break;
15473 case UO_Real:
15474 case UO_Imag:
15475 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15476 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
15477 // ordinary complex l-values to ordinary l-values and all other values to
15478 // r-values.
15479 if (Input.isInvalid())
15480 return ExprError();
15481 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15482 if (Input.get()->isGLValue() &&
15483 Input.get()->getObjectKind() == OK_Ordinary)
15484 VK = Input.get()->getValueKind();
15485 } else if (!getLangOpts().CPlusPlus) {
15486 // In C, a volatile scalar is read by __imag. In C++, it is not.
15487 Input = DefaultLvalueConversion(Input.get());
15488 }
15489 break;
15490 case UO_Extension:
15491 resultType = Input.get()->getType();
15492 VK = Input.get()->getValueKind();
15493 OK = Input.get()->getObjectKind();
15494 break;
15495 case UO_Coawait:
15496 // It's unnecessary to represent the pass-through operator co_await in the
15497 // AST; just return the input expression instead.
15498 assert(!Input.get()->getType()->isDependentType() &&
15499 "the co_await expression must be non-dependant before "
15500 "building operator co_await");
15501 return Input;
15502 }
15503 }
15504 if (resultType.isNull() || Input.isInvalid())
15505 return ExprError();
15506
15507 // Check for array bounds violations in the operand of the UnaryOperator,
15508 // except for the '*' and '&' operators that have to be handled specially
15509 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15510 // that are explicitly defined as valid by the standard).
15511 if (Opc != UO_AddrOf && Opc != UO_Deref)
15512 CheckArrayAccess(Input.get());
15513
15514 auto *UO =
15515 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15516 OpLoc, CanOverflow, CurFPFeatureOverrides());
15517
15518 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15519 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15521 ExprEvalContexts.back().PossibleDerefs.insert(UO);
15522
15523 // Convert the result back to a half vector.
15524 if (ConvertHalfVec)
15525 return convertVector(UO, Context.HalfTy, *this);
15526 return UO;
15527}
15528
15530 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15531 if (!DRE->getQualifier())
15532 return false;
15533
15534 ValueDecl *VD = DRE->getDecl();
15535 if (!VD->isCXXClassMember())
15536 return false;
15537
15538 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15539 return true;
15540 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15541 return Method->isImplicitObjectMemberFunction();
15542
15543 return false;
15544 }
15545
15546 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15547 if (!ULE->getQualifier())
15548 return false;
15549
15550 for (NamedDecl *D : ULE->decls()) {
15551 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15552 if (Method->isImplicitObjectMemberFunction())
15553 return true;
15554 } else {
15555 // Overload set does not contain methods.
15556 break;
15557 }
15558 }
15559
15560 return false;
15561 }
15562
15563 return false;
15564}
15565
15567 UnaryOperatorKind Opc, Expr *Input,
15568 bool IsAfterAmp) {
15569 // First things first: handle placeholders so that the
15570 // overloaded-operator check considers the right type.
15571 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15572 // Increment and decrement of pseudo-object references.
15573 if (pty->getKind() == BuiltinType::PseudoObject &&
15575 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
15576
15577 // extension is always a builtin operator.
15578 if (Opc == UO_Extension)
15579 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15580
15581 // & gets special logic for several kinds of placeholder.
15582 // The builtin code knows what to do.
15583 if (Opc == UO_AddrOf &&
15584 (pty->getKind() == BuiltinType::Overload ||
15585 pty->getKind() == BuiltinType::UnknownAny ||
15586 pty->getKind() == BuiltinType::BoundMember))
15587 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15588
15589 // Anything else needs to be handled now.
15591 if (Result.isInvalid()) return ExprError();
15592 Input = Result.get();
15593 }
15594
15595 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15597 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15598 // Find all of the overloaded operators visible from this point.
15599 UnresolvedSet<16> Functions;
15601 if (S && OverOp != OO_None)
15602 LookupOverloadedOperatorName(OverOp, S, Functions);
15603
15604 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15605 }
15606
15607 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
15608}
15609
15611 Expr *Input, bool IsAfterAmp) {
15612 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
15613 IsAfterAmp);
15614}
15615
15617 LabelDecl *TheDecl) {
15618 TheDecl->markUsed(Context);
15619 // Create the AST node. The address of a label always has type 'void*'.
15620 auto *Res = new (Context) AddrLabelExpr(
15621 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
15622
15623 if (getCurFunction())
15624 getCurFunction()->AddrLabels.push_back(Res);
15625
15626 return Res;
15627}
15628
15631 // Make sure we diagnose jumping into a statement expression.
15633}
15634
15636 // Note that function is also called by TreeTransform when leaving a
15637 // StmtExpr scope without rebuilding anything.
15638
15641}
15642
15644 SourceLocation RPLoc) {
15645 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15646}
15647
15649 SourceLocation RPLoc, unsigned TemplateDepth) {
15650 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15651 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15652
15655 assert(!Cleanup.exprNeedsCleanups() &&
15656 "cleanups within StmtExpr not correctly bound!");
15658
15659 // FIXME: there are a variety of strange constraints to enforce here, for
15660 // example, it is not possible to goto into a stmt expression apparently.
15661 // More semantic analysis is needed.
15662
15663 // If there are sub-stmts in the compound stmt, take the type of the last one
15664 // as the type of the stmtexpr.
15665 QualType Ty = Context.VoidTy;
15666 bool StmtExprMayBindToTemp = false;
15667 if (!Compound->body_empty()) {
15668 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15669 if (const auto *LastStmt =
15670 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15671 if (const Expr *Value = LastStmt->getExprStmt()) {
15672 StmtExprMayBindToTemp = true;
15673 Ty = Value->getType();
15674 }
15675 }
15676 }
15677
15678 // FIXME: Check that expression type is complete/non-abstract; statement
15679 // expressions are not lvalues.
15680 Expr *ResStmtExpr =
15681 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15682 if (StmtExprMayBindToTemp)
15683 return MaybeBindToTemporary(ResStmtExpr);
15684 return ResStmtExpr;
15685}
15686
15688 if (ER.isInvalid())
15689 return ExprError();
15690
15691 // Do function/array conversion on the last expression, but not
15692 // lvalue-to-rvalue. However, initialize an unqualified type.
15694 if (ER.isInvalid())
15695 return ExprError();
15696 Expr *E = ER.get();
15697
15698 if (E->isTypeDependent())
15699 return E;
15700
15701 // In ARC, if the final expression ends in a consume, splice
15702 // the consume out and bind it later. In the alternate case
15703 // (when dealing with a retainable type), the result
15704 // initialization will create a produce. In both cases the
15705 // result will be +1, and we'll need to balance that out with
15706 // a bind.
15707 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15708 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15709 return Cast->getSubExpr();
15710
15711 // FIXME: Provide a better location for the initialization.
15715 SourceLocation(), E);
15716}
15717
15719 TypeSourceInfo *TInfo,
15720 ArrayRef<OffsetOfComponent> Components,
15721 SourceLocation RParenLoc) {
15722 QualType ArgTy = TInfo->getType();
15723 bool Dependent = ArgTy->isDependentType();
15724 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15725
15726 // We must have at least one component that refers to the type, and the first
15727 // one is known to be a field designator. Verify that the ArgTy represents
15728 // a struct/union/class.
15729 if (!Dependent && !ArgTy->isRecordType())
15730 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15731 << ArgTy << TypeRange);
15732
15733 // Type must be complete per C99 7.17p3 because a declaring a variable
15734 // with an incomplete type would be ill-formed.
15735 if (!Dependent
15736 && RequireCompleteType(BuiltinLoc, ArgTy,
15737 diag::err_offsetof_incomplete_type, TypeRange))
15738 return ExprError();
15739
15740 bool DidWarnAboutNonPOD = false;
15741 QualType CurrentType = ArgTy;
15744 for (const OffsetOfComponent &OC : Components) {
15745 if (OC.isBrackets) {
15746 // Offset of an array sub-field. TODO: Should we allow vector elements?
15747 if (!CurrentType->isDependentType()) {
15748 const ArrayType *AT = Context.getAsArrayType(CurrentType);
15749 if(!AT)
15750 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15751 << CurrentType);
15752 CurrentType = AT->getElementType();
15753 } else
15754 CurrentType = Context.DependentTy;
15755
15756 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15757 if (IdxRval.isInvalid())
15758 return ExprError();
15759 Expr *Idx = IdxRval.get();
15760
15761 // The expression must be an integral expression.
15762 // FIXME: An integral constant expression?
15763 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15764 !Idx->getType()->isIntegerType())
15765 return ExprError(
15766 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15767 << Idx->getSourceRange());
15768
15769 // Record this array index.
15770 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15771 Exprs.push_back(Idx);
15772 continue;
15773 }
15774
15775 // Offset of a field.
15776 if (CurrentType->isDependentType()) {
15777 // We have the offset of a field, but we can't look into the dependent
15778 // type. Just record the identifier of the field.
15779 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15780 CurrentType = Context.DependentTy;
15781 continue;
15782 }
15783
15784 // We need to have a complete type to look into.
15785 if (RequireCompleteType(OC.LocStart, CurrentType,
15786 diag::err_offsetof_incomplete_type))
15787 return ExprError();
15788
15789 // Look for the designated field.
15790 const RecordType *RC = CurrentType->getAs<RecordType>();
15791 if (!RC)
15792 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15793 << CurrentType);
15794 RecordDecl *RD = RC->getDecl();
15795
15796 // C++ [lib.support.types]p5:
15797 // The macro offsetof accepts a restricted set of type arguments in this
15798 // International Standard. type shall be a POD structure or a POD union
15799 // (clause 9).
15800 // C++11 [support.types]p4:
15801 // If type is not a standard-layout class (Clause 9), the results are
15802 // undefined.
15803 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15804 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15805 unsigned DiagID =
15806 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15807 : diag::ext_offsetof_non_pod_type;
15808
15809 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
15810 Diag(BuiltinLoc, DiagID)
15811 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
15812 DidWarnAboutNonPOD = true;
15813 }
15814 }
15815
15816 // Look for the field.
15817 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15818 LookupQualifiedName(R, RD);
15819 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15820 IndirectFieldDecl *IndirectMemberDecl = nullptr;
15821 if (!MemberDecl) {
15822 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15823 MemberDecl = IndirectMemberDecl->getAnonField();
15824 }
15825
15826 if (!MemberDecl) {
15827 // Lookup could be ambiguous when looking up a placeholder variable
15828 // __builtin_offsetof(S, _).
15829 // In that case we would already have emitted a diagnostic
15830 if (!R.isAmbiguous())
15831 Diag(BuiltinLoc, diag::err_no_member)
15832 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
15833 return ExprError();
15834 }
15835
15836 // C99 7.17p3:
15837 // (If the specified member is a bit-field, the behavior is undefined.)
15838 //
15839 // We diagnose this as an error.
15840 if (MemberDecl->isBitField()) {
15841 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15842 << MemberDecl->getDeclName()
15843 << SourceRange(BuiltinLoc, RParenLoc);
15844 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15845 return ExprError();
15846 }
15847
15848 RecordDecl *Parent = MemberDecl->getParent();
15849 if (IndirectMemberDecl)
15850 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15851
15852 // If the member was found in a base class, introduce OffsetOfNodes for
15853 // the base class indirections.
15854 CXXBasePaths Paths;
15855 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15856 Paths)) {
15857 if (Paths.getDetectedVirtual()) {
15858 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15859 << MemberDecl->getDeclName()
15860 << SourceRange(BuiltinLoc, RParenLoc);
15861 return ExprError();
15862 }
15863
15864 CXXBasePath &Path = Paths.front();
15865 for (const CXXBasePathElement &B : Path)
15866 Comps.push_back(OffsetOfNode(B.Base));
15867 }
15868
15869 if (IndirectMemberDecl) {
15870 for (auto *FI : IndirectMemberDecl->chain()) {
15871 assert(isa<FieldDecl>(FI));
15872 Comps.push_back(OffsetOfNode(OC.LocStart,
15873 cast<FieldDecl>(FI), OC.LocEnd));
15874 }
15875 } else
15876 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15877
15878 CurrentType = MemberDecl->getType().getNonReferenceType();
15879 }
15880
15881 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15882 Comps, Exprs, RParenLoc);
15883}
15884
15886 SourceLocation BuiltinLoc,
15888 ParsedType ParsedArgTy,
15889 ArrayRef<OffsetOfComponent> Components,
15890 SourceLocation RParenLoc) {
15891
15892 TypeSourceInfo *ArgTInfo;
15893 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15894 if (ArgTy.isNull())
15895 return ExprError();
15896
15897 if (!ArgTInfo)
15898 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15899
15900 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15901}
15902
15903
15905 Expr *CondExpr,
15906 Expr *LHSExpr, Expr *RHSExpr,
15907 SourceLocation RPLoc) {
15908 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15909
15912 QualType resType;
15913 bool CondIsTrue = false;
15914 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15915 resType = Context.DependentTy;
15916 } else {
15917 // The conditional expression is required to be a constant expression.
15918 llvm::APSInt condEval(32);
15920 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15921 if (CondICE.isInvalid())
15922 return ExprError();
15923 CondExpr = CondICE.get();
15924 CondIsTrue = condEval.getZExtValue();
15925
15926 // If the condition is > zero, then the AST type is the same as the LHSExpr.
15927 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15928
15929 resType = ActiveExpr->getType();
15930 VK = ActiveExpr->getValueKind();
15931 OK = ActiveExpr->getObjectKind();
15932 }
15933
15934 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15935 resType, VK, OK, RPLoc, CondIsTrue);
15936}
15937
15938//===----------------------------------------------------------------------===//
15939// Clang Extensions.
15940//===----------------------------------------------------------------------===//
15941
15942void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15944
15945 if (LangOpts.CPlusPlus) {
15947 Decl *ManglingContextDecl;
15948 std::tie(MCtx, ManglingContextDecl) =
15949 getCurrentMangleNumberContext(Block->getDeclContext());
15950 if (MCtx) {
15951 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15952 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15953 }
15954 }
15955
15956 PushBlockScope(CurScope, Block);
15958 if (CurScope)
15959 PushDeclContext(CurScope, Block);
15960 else
15961 CurContext = Block;
15962
15964
15965 // Enter a new evaluation context to insulate the block from any
15966 // cleanups from the enclosing full-expression.
15969}
15970
15972 Scope *CurScope) {
15973 assert(ParamInfo.getIdentifier() == nullptr &&
15974 "block-id should have no identifier!");
15975 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15976 BlockScopeInfo *CurBlock = getCurBlock();
15977
15978 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
15979 QualType T = Sig->getType();
15980
15981 // FIXME: We should allow unexpanded parameter packs here, but that would,
15982 // in turn, make the block expression contain unexpanded parameter packs.
15983 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15984 // Drop the parameters.
15986 EPI.HasTrailingReturn = false;
15987 EPI.TypeQuals.addConst();
15988 T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
15990 }
15991
15992 // GetTypeForDeclarator always produces a function type for a block
15993 // literal signature. Furthermore, it is always a FunctionProtoType
15994 // unless the function was written with a typedef.
15995 assert(T->isFunctionType() &&
15996 "GetTypeForDeclarator made a non-function block signature");
15997
15998 // Look for an explicit signature in that function type.
15999 FunctionProtoTypeLoc ExplicitSignature;
16000
16001 if ((ExplicitSignature = Sig->getTypeLoc()
16003
16004 // Check whether that explicit signature was synthesized by
16005 // GetTypeForDeclarator. If so, don't save that as part of the
16006 // written signature.
16007 if (ExplicitSignature.getLocalRangeBegin() ==
16008 ExplicitSignature.getLocalRangeEnd()) {
16009 // This would be much cheaper if we stored TypeLocs instead of
16010 // TypeSourceInfos.
16011 TypeLoc Result = ExplicitSignature.getReturnLoc();
16012 unsigned Size = Result.getFullDataSize();
16013 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16014 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16015
16016 ExplicitSignature = FunctionProtoTypeLoc();
16017 }
16018 }
16019
16020 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16021 CurBlock->FunctionType = T;
16022
16023 const auto *Fn = T->castAs<FunctionType>();
16024 QualType RetTy = Fn->getReturnType();
16025 bool isVariadic =
16026 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16027
16028 CurBlock->TheDecl->setIsVariadic(isVariadic);
16029
16030 // Context.DependentTy is used as a placeholder for a missing block
16031 // return type. TODO: what should we do with declarators like:
16032 // ^ * { ... }
16033 // If the answer is "apply template argument deduction"....
16034 if (RetTy != Context.DependentTy) {
16035 CurBlock->ReturnType = RetTy;
16036 CurBlock->TheDecl->setBlockMissingReturnType(false);
16037 CurBlock->HasImplicitReturnType = false;
16038 }
16039
16040 // Push block parameters from the declarator if we had them.
16042 if (ExplicitSignature) {
16043 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16044 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16045 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16046 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16047 // Diagnose this as an extension in C17 and earlier.
16048 if (!getLangOpts().C23)
16049 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16050 }
16051 Params.push_back(Param);
16052 }
16053
16054 // Fake up parameter variables if we have a typedef, like
16055 // ^ fntype { ... }
16056 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16057 for (const auto &I : Fn->param_types()) {
16059 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16060 Params.push_back(Param);
16061 }
16062 }
16063
16064 // Set the parameters on the block decl.
16065 if (!Params.empty()) {
16066 CurBlock->TheDecl->setParams(Params);
16068 /*CheckParameterNames=*/false);
16069 }
16070
16071 // Finally we can process decl attributes.
16072 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16073
16074 // Put the parameter variables in scope.
16075 for (auto *AI : CurBlock->TheDecl->parameters()) {
16076 AI->setOwningFunction(CurBlock->TheDecl);
16077
16078 // If this has an identifier, add it to the scope stack.
16079 if (AI->getIdentifier()) {
16080 CheckShadow(CurBlock->TheScope, AI);
16081
16082 PushOnScopeChains(AI, CurBlock->TheScope);
16083 }
16084
16085 if (AI->isInvalidDecl())
16086 CurBlock->TheDecl->setInvalidDecl();
16087 }
16088}
16089
16090void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16091 // Leave the expression-evaluation context.
16094
16095 // Pop off CurBlock, handle nested blocks.
16098}
16099
16101 Stmt *Body, Scope *CurScope) {
16102 // If blocks are disabled, emit an error.
16103 if (!LangOpts.Blocks)
16104 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16105
16106 // Leave the expression-evaluation context.
16109 assert(!Cleanup.exprNeedsCleanups() &&
16110 "cleanups within block not correctly bound!");
16112
16113 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16114 BlockDecl *BD = BSI->TheDecl;
16115
16116 if (BSI->HasImplicitReturnType)
16118
16119 QualType RetTy = Context.VoidTy;
16120 if (!BSI->ReturnType.isNull())
16121 RetTy = BSI->ReturnType;
16122
16123 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16124 QualType BlockTy;
16125
16126 // If the user wrote a function type in some form, try to use that.
16127 if (!BSI->FunctionType.isNull()) {
16128 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16129
16130 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16131 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16132
16133 // Turn protoless block types into nullary block types.
16134 if (isa<FunctionNoProtoType>(FTy)) {
16136 EPI.ExtInfo = Ext;
16137 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16138
16139 // Otherwise, if we don't need to change anything about the function type,
16140 // preserve its sugar structure.
16141 } else if (FTy->getReturnType() == RetTy &&
16142 (!NoReturn || FTy->getNoReturnAttr())) {
16143 BlockTy = BSI->FunctionType;
16144
16145 // Otherwise, make the minimal modifications to the function type.
16146 } else {
16147 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16149 EPI.TypeQuals = Qualifiers();
16150 EPI.ExtInfo = Ext;
16151 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16152 }
16153
16154 // If we don't have a function type, just build one from nothing.
16155 } else {
16157 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16158 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16159 }
16160
16162 BlockTy = Context.getBlockPointerType(BlockTy);
16163
16164 // If needed, diagnose invalid gotos and switches in the block.
16165 if (getCurFunction()->NeedsScopeChecking() &&
16167 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16168
16169 BD->setBody(cast<CompoundStmt>(Body));
16170
16171 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16173
16174 // Try to apply the named return value optimization. We have to check again
16175 // if we can do this, though, because blocks keep return statements around
16176 // to deduce an implicit return type.
16177 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16178 !BD->isDependentContext())
16179 computeNRVO(Body, BSI);
16180
16185
16187
16188 // Set the captured variables on the block.
16190 for (Capture &Cap : BSI->Captures) {
16191 if (Cap.isInvalid() || Cap.isThisCapture())
16192 continue;
16193 // Cap.getVariable() is always a VarDecl because
16194 // blocks cannot capture structured bindings or other ValueDecl kinds.
16195 auto *Var = cast<VarDecl>(Cap.getVariable());
16196 Expr *CopyExpr = nullptr;
16197 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16198 if (const RecordType *Record =
16199 Cap.getCaptureType()->getAs<RecordType>()) {
16200 // The capture logic needs the destructor, so make sure we mark it.
16201 // Usually this is unnecessary because most local variables have
16202 // their destructors marked at declaration time, but parameters are
16203 // an exception because it's technically only the call site that
16204 // actually requires the destructor.
16205 if (isa<ParmVarDecl>(Var))
16207
16208 // Enter a separate potentially-evaluated context while building block
16209 // initializers to isolate their cleanups from those of the block
16210 // itself.
16211 // FIXME: Is this appropriate even when the block itself occurs in an
16212 // unevaluated operand?
16215
16217
16219 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16220
16221 // According to the blocks spec, the capture of a variable from
16222 // the stack requires a const copy constructor. This is not true
16223 // of the copy/move done to move a __block variable to the heap.
16224 if (!Result.isInvalid() &&
16225 !Result.get()->getType().isConstQualified()) {
16227 Result.get()->getType().withConst(),
16228 CK_NoOp, VK_LValue);
16229 }
16230
16231 if (!Result.isInvalid()) {
16233 InitializedEntity::InitializeBlock(Var->getLocation(),
16234 Cap.getCaptureType()),
16235 Loc, Result.get());
16236 }
16237
16238 // Build a full-expression copy expression if initialization
16239 // succeeded and used a non-trivial constructor. Recover from
16240 // errors by pretending that the copy isn't necessary.
16241 if (!Result.isInvalid() &&
16242 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16243 ->isTrivial()) {
16245 CopyExpr = Result.get();
16246 }
16247 }
16248 }
16249
16250 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16251 CopyExpr);
16252 Captures.push_back(NewCap);
16253 }
16254 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16255
16256 // Pop the block scope now but keep it alive to the end of this function.
16258 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16259
16260 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16261
16262 // If the block isn't obviously global, i.e. it captures anything at
16263 // all, then we need to do a few things in the surrounding context:
16264 if (Result->getBlockDecl()->hasCaptures()) {
16265 // First, this expression has a new cleanup object.
16266 ExprCleanupObjects.push_back(Result->getBlockDecl());
16268
16269 // It also gets a branch-protected scope if any of the captured
16270 // variables needs destruction.
16271 for (const auto &CI : Result->getBlockDecl()->captures()) {
16272 const VarDecl *var = CI.getVariable();
16273 if (var->getType().isDestructedType() != QualType::DK_none) {
16275 break;
16276 }
16277 }
16278 }
16279
16280 if (getCurFunction())
16281 getCurFunction()->addBlock(BD);
16282
16283 if (BD->isInvalidDecl())
16284 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16285 {Result}, Result->getType());
16286 return Result;
16287}
16288
16290 SourceLocation RPLoc) {
16291 TypeSourceInfo *TInfo;
16292 GetTypeFromParser(Ty, &TInfo);
16293 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16294}
16295
16297 Expr *E, TypeSourceInfo *TInfo,
16298 SourceLocation RPLoc) {
16299 Expr *OrigExpr = E;
16300 bool IsMS = false;
16301
16302 // CUDA device code does not support varargs.
16303 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16304 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16308 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16309 }
16310 }
16311
16312 // NVPTX does not support va_arg expression.
16313 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16314 Context.getTargetInfo().getTriple().isNVPTX())
16315 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16316
16317 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16318 // as Microsoft ABI on an actual Microsoft platform, where
16319 // __builtin_ms_va_list and __builtin_va_list are the same.)
16322 QualType MSVaListType = Context.getBuiltinMSVaListType();
16323 if (Context.hasSameType(MSVaListType, E->getType())) {
16324 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16325 return ExprError();
16326 IsMS = true;
16327 }
16328 }
16329
16330 // Get the va_list type
16331 QualType VaListType = Context.getBuiltinVaListType();
16332 if (!IsMS) {
16333 if (VaListType->isArrayType()) {
16334 // Deal with implicit array decay; for example, on x86-64,
16335 // va_list is an array, but it's supposed to decay to
16336 // a pointer for va_arg.
16337 VaListType = Context.getArrayDecayedType(VaListType);
16338 // Make sure the input expression also decays appropriately.
16340 if (Result.isInvalid())
16341 return ExprError();
16342 E = Result.get();
16343 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16344 // If va_list is a record type and we are compiling in C++ mode,
16345 // check the argument using reference binding.
16347 Context, Context.getLValueReferenceType(VaListType), false);
16349 if (Init.isInvalid())
16350 return ExprError();
16351 E = Init.getAs<Expr>();
16352 } else {
16353 // Otherwise, the va_list argument must be an l-value because
16354 // it is modified by va_arg.
16355 if (!E->isTypeDependent() &&
16356 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16357 return ExprError();
16358 }
16359 }
16360
16361 if (!IsMS && !E->isTypeDependent() &&
16362 !Context.hasSameType(VaListType, E->getType()))
16363 return ExprError(
16364 Diag(E->getBeginLoc(),
16365 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16366 << OrigExpr->getType() << E->getSourceRange());
16367
16368 if (!TInfo->getType()->isDependentType()) {
16369 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16370 diag::err_second_parameter_to_va_arg_incomplete,
16371 TInfo->getTypeLoc()))
16372 return ExprError();
16373
16375 TInfo->getType(),
16376 diag::err_second_parameter_to_va_arg_abstract,
16377 TInfo->getTypeLoc()))
16378 return ExprError();
16379
16380 if (!TInfo->getType().isPODType(Context)) {
16381 Diag(TInfo->getTypeLoc().getBeginLoc(),
16382 TInfo->getType()->isObjCLifetimeType()
16383 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16384 : diag::warn_second_parameter_to_va_arg_not_pod)
16385 << TInfo->getType()
16386 << TInfo->getTypeLoc().getSourceRange();
16387 }
16388
16389 // Check for va_arg where arguments of the given type will be promoted
16390 // (i.e. this va_arg is guaranteed to have undefined behavior).
16391 QualType PromoteType;
16392 if (Context.isPromotableIntegerType(TInfo->getType())) {
16393 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16394 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16395 // and C23 7.16.1.1p2 says, in part:
16396 // If type is not compatible with the type of the actual next argument
16397 // (as promoted according to the default argument promotions), the
16398 // behavior is undefined, except for the following cases:
16399 // - both types are pointers to qualified or unqualified versions of
16400 // compatible types;
16401 // - one type is compatible with a signed integer type, the other
16402 // type is compatible with the corresponding unsigned integer type,
16403 // and the value is representable in both types;
16404 // - one type is pointer to qualified or unqualified void and the
16405 // other is a pointer to a qualified or unqualified character type;
16406 // - or, the type of the next argument is nullptr_t and type is a
16407 // pointer type that has the same representation and alignment
16408 // requirements as a pointer to a character type.
16409 // Given that type compatibility is the primary requirement (ignoring
16410 // qualifications), you would think we could call typesAreCompatible()
16411 // directly to test this. However, in C++, that checks for *same type*,
16412 // which causes false positives when passing an enumeration type to
16413 // va_arg. Instead, get the underlying type of the enumeration and pass
16414 // that.
16415 QualType UnderlyingType = TInfo->getType();
16416 if (const auto *ET = UnderlyingType->getAs<EnumType>())
16417 UnderlyingType = ET->getDecl()->getIntegerType();
16418 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16419 /*CompareUnqualified*/ true))
16420 PromoteType = QualType();
16421
16422 // If the types are still not compatible, we need to test whether the
16423 // promoted type and the underlying type are the same except for
16424 // signedness. Ask the AST for the correctly corresponding type and see
16425 // if that's compatible.
16426 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16427 PromoteType->isUnsignedIntegerType() !=
16428 UnderlyingType->isUnsignedIntegerType()) {
16429 UnderlyingType =
16430 UnderlyingType->isUnsignedIntegerType()
16431 ? Context.getCorrespondingSignedType(UnderlyingType)
16432 : Context.getCorrespondingUnsignedType(UnderlyingType);
16433 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16434 /*CompareUnqualified*/ true))
16435 PromoteType = QualType();
16436 }
16437 }
16438 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16439 PromoteType = Context.DoubleTy;
16440 if (!PromoteType.isNull())
16442 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16443 << TInfo->getType()
16444 << PromoteType
16445 << TInfo->getTypeLoc().getSourceRange());
16446 }
16447
16449 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16450}
16451
16453 // The type of __null will be int or long, depending on the size of
16454 // pointers on the target.
16455 QualType Ty;
16457 if (pw == Context.getTargetInfo().getIntWidth())
16458 Ty = Context.IntTy;
16459 else if (pw == Context.getTargetInfo().getLongWidth())
16460 Ty = Context.LongTy;
16461 else if (pw == Context.getTargetInfo().getLongLongWidth())
16462 Ty = Context.LongLongTy;
16463 else {
16464 llvm_unreachable("I don't know size of pointer!");
16465 }
16466
16467 return new (Context) GNUNullExpr(Ty, TokenLoc);
16468}
16469
16471 CXXRecordDecl *ImplDecl = nullptr;
16472
16473 // Fetch the std::source_location::__impl decl.
16474 if (NamespaceDecl *Std = S.getStdNamespace()) {
16475 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16477 if (S.LookupQualifiedName(ResultSL, Std)) {
16478 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16479 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16481 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16482 S.LookupQualifiedName(ResultImpl, SLDecl)) {
16483 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16484 }
16485 }
16486 }
16487 }
16488
16489 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16490 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16491 return nullptr;
16492 }
16493
16494 // Verify that __impl is a trivial struct type, with no base classes, and with
16495 // only the four expected fields.
16496 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16497 ImplDecl->getNumBases() != 0) {
16498 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16499 return nullptr;
16500 }
16501
16502 unsigned Count = 0;
16503 for (FieldDecl *F : ImplDecl->fields()) {
16504 StringRef Name = F->getName();
16505
16506 if (Name == "_M_file_name") {
16507 if (F->getType() !=
16509 break;
16510 Count++;
16511 } else if (Name == "_M_function_name") {
16512 if (F->getType() !=
16514 break;
16515 Count++;
16516 } else if (Name == "_M_line") {
16517 if (!F->getType()->isIntegerType())
16518 break;
16519 Count++;
16520 } else if (Name == "_M_column") {
16521 if (!F->getType()->isIntegerType())
16522 break;
16523 Count++;
16524 } else {
16525 Count = 100; // invalid
16526 break;
16527 }
16528 }
16529 if (Count != 4) {
16530 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16531 return nullptr;
16532 }
16533
16534 return ImplDecl;
16535}
16536
16538 SourceLocation BuiltinLoc,
16539 SourceLocation RPLoc) {
16540 QualType ResultTy;
16541 switch (Kind) {
16547 ResultTy =
16549 break;
16550 }
16553 ResultTy = Context.UnsignedIntTy;
16554 break;
16558 LookupStdSourceLocationImpl(*this, BuiltinLoc);
16560 return ExprError();
16561 }
16562 ResultTy = Context.getPointerType(
16564 break;
16565 }
16566
16567 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16568}
16569
16571 SourceLocation BuiltinLoc,
16572 SourceLocation RPLoc,
16573 DeclContext *ParentContext) {
16574 return new (Context)
16575 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16576}
16577
16579 StringLiteral *BinaryData) {
16581 Data->BinaryData = BinaryData;
16582 return new (Context)
16583 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
16584 Data->getDataElementCount());
16585}
16586
16588 const Expr *SrcExpr) {
16589 if (!DstType->isFunctionPointerType() ||
16590 !SrcExpr->getType()->isFunctionType())
16591 return false;
16592
16593 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16594 if (!DRE)
16595 return false;
16596
16597 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16598 if (!FD)
16599 return false;
16600
16602 /*Complain=*/true,
16603 SrcExpr->getBeginLoc());
16604}
16605
16608 QualType DstType, QualType SrcType,
16609 Expr *SrcExpr, AssignmentAction Action,
16610 bool *Complained) {
16611 if (Complained)
16612 *Complained = false;
16613
16614 // Decode the result (notice that AST's are still created for extensions).
16615 bool CheckInferredResultType = false;
16616 bool isInvalid = false;
16617 unsigned DiagKind = 0;
16618 ConversionFixItGenerator ConvHints;
16619 bool MayHaveConvFixit = false;
16620 bool MayHaveFunctionDiff = false;
16621 const ObjCInterfaceDecl *IFace = nullptr;
16622 const ObjCProtocolDecl *PDecl = nullptr;
16623
16624 switch (ConvTy) {
16625 case Compatible:
16626 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16627 return false;
16628
16629 case PointerToInt:
16630 if (getLangOpts().CPlusPlus) {
16631 DiagKind = diag::err_typecheck_convert_pointer_int;
16632 isInvalid = true;
16633 } else {
16634 DiagKind = diag::ext_typecheck_convert_pointer_int;
16635 }
16636 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16637 MayHaveConvFixit = true;
16638 break;
16639 case IntToPointer:
16640 if (getLangOpts().CPlusPlus) {
16641 DiagKind = diag::err_typecheck_convert_int_pointer;
16642 isInvalid = true;
16643 } else {
16644 DiagKind = diag::ext_typecheck_convert_int_pointer;
16645 }
16646 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16647 MayHaveConvFixit = true;
16648 break;
16650 DiagKind =
16651 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
16652 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16653 MayHaveConvFixit = true;
16654 break;
16656 if (getLangOpts().CPlusPlus) {
16657 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16658 isInvalid = true;
16659 } else {
16660 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16661 }
16662 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16663 MayHaveConvFixit = true;
16664 break;
16666 if (Action == AA_Passing_CFAudited) {
16667 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16668 } else if (getLangOpts().CPlusPlus) {
16669 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16670 isInvalid = true;
16671 } else {
16672 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16673 }
16674 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16675 SrcType->isObjCObjectPointerType();
16676 if (CheckInferredResultType) {
16677 SrcType = SrcType.getUnqualifiedType();
16678 DstType = DstType.getUnqualifiedType();
16679 } else {
16680 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16681 }
16682 MayHaveConvFixit = true;
16683 break;
16685 if (getLangOpts().CPlusPlus) {
16686 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16687 isInvalid = true;
16688 } else {
16689 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16690 }
16691 break;
16693 if (getLangOpts().CPlusPlus) {
16694 DiagKind = diag::err_typecheck_convert_pointer_void_func;
16695 isInvalid = true;
16696 } else {
16697 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16698 }
16699 break;
16701 // Perform array-to-pointer decay if necessary.
16702 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16703
16704 isInvalid = true;
16705
16706 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16707 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16708 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16709 DiagKind = diag::err_typecheck_incompatible_address_space;
16710 break;
16711 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16712 DiagKind = diag::err_typecheck_incompatible_ownership;
16713 break;
16714 }
16715
16716 llvm_unreachable("unknown error case for discarding qualifiers!");
16717 // fallthrough
16718 }
16720 // If the qualifiers lost were because we were applying the
16721 // (deprecated) C++ conversion from a string literal to a char*
16722 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16723 // Ideally, this check would be performed in
16724 // checkPointerTypesForAssignment. However, that would require a
16725 // bit of refactoring (so that the second argument is an
16726 // expression, rather than a type), which should be done as part
16727 // of a larger effort to fix checkPointerTypesForAssignment for
16728 // C++ semantics.
16729 if (getLangOpts().CPlusPlus &&
16731 return false;
16732 if (getLangOpts().CPlusPlus) {
16733 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
16734 isInvalid = true;
16735 } else {
16736 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
16737 }
16738
16739 break;
16741 if (getLangOpts().CPlusPlus) {
16742 isInvalid = true;
16743 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16744 } else {
16745 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16746 }
16747 break;
16749 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16750 isInvalid = true;
16751 break;
16752 case IntToBlockPointer:
16753 DiagKind = diag::err_int_to_block_pointer;
16754 isInvalid = true;
16755 break;
16757 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16758 isInvalid = true;
16759 break;
16761 if (SrcType->isObjCQualifiedIdType()) {
16762 const ObjCObjectPointerType *srcOPT =
16763 SrcType->castAs<ObjCObjectPointerType>();
16764 for (auto *srcProto : srcOPT->quals()) {
16765 PDecl = srcProto;
16766 break;
16767 }
16768 if (const ObjCInterfaceType *IFaceT =
16770 IFace = IFaceT->getDecl();
16771 }
16772 else if (DstType->isObjCQualifiedIdType()) {
16773 const ObjCObjectPointerType *dstOPT =
16774 DstType->castAs<ObjCObjectPointerType>();
16775 for (auto *dstProto : dstOPT->quals()) {
16776 PDecl = dstProto;
16777 break;
16778 }
16779 if (const ObjCInterfaceType *IFaceT =
16781 IFace = IFaceT->getDecl();
16782 }
16783 if (getLangOpts().CPlusPlus) {
16784 DiagKind = diag::err_incompatible_qualified_id;
16785 isInvalid = true;
16786 } else {
16787 DiagKind = diag::warn_incompatible_qualified_id;
16788 }
16789 break;
16790 }
16792 if (getLangOpts().CPlusPlus) {
16793 DiagKind = diag::err_incompatible_vectors;
16794 isInvalid = true;
16795 } else {
16796 DiagKind = diag::warn_incompatible_vectors;
16797 }
16798 break;
16800 DiagKind = diag::err_arc_weak_unavailable_assign;
16801 isInvalid = true;
16802 break;
16803 case Incompatible:
16804 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16805 if (Complained)
16806 *Complained = true;
16807 return true;
16808 }
16809
16810 DiagKind = diag::err_typecheck_convert_incompatible;
16811 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16812 MayHaveConvFixit = true;
16813 isInvalid = true;
16814 MayHaveFunctionDiff = true;
16815 break;
16816 }
16817
16818 QualType FirstType, SecondType;
16819 switch (Action) {
16820 case AA_Assigning:
16821 case AA_Initializing:
16822 // The destination type comes first.
16823 FirstType = DstType;
16824 SecondType = SrcType;
16825 break;
16826
16827 case AA_Returning:
16828 case AA_Passing:
16830 case AA_Converting:
16831 case AA_Sending:
16832 case AA_Casting:
16833 // The source type comes first.
16834 FirstType = SrcType;
16835 SecondType = DstType;
16836 break;
16837 }
16838
16839 PartialDiagnostic FDiag = PDiag(DiagKind);
16840 AssignmentAction ActionForDiag = Action;
16841 if (Action == AA_Passing_CFAudited)
16842 ActionForDiag = AA_Passing;
16843
16844 FDiag << FirstType << SecondType << ActionForDiag
16845 << SrcExpr->getSourceRange();
16846
16847 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16848 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16849 auto isPlainChar = [](const clang::Type *Type) {
16850 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16851 Type->isSpecificBuiltinType(BuiltinType::Char_U);
16852 };
16853 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16854 isPlainChar(SecondType->getPointeeOrArrayElementType()));
16855 }
16856
16857 // If we can fix the conversion, suggest the FixIts.
16858 if (!ConvHints.isNull()) {
16859 for (FixItHint &H : ConvHints.Hints)
16860 FDiag << H;
16861 }
16862
16863 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16864
16865 if (MayHaveFunctionDiff)
16866 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16867
16868 Diag(Loc, FDiag);
16869 if ((DiagKind == diag::warn_incompatible_qualified_id ||
16870 DiagKind == diag::err_incompatible_qualified_id) &&
16871 PDecl && IFace && !IFace->hasDefinition())
16872 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16873 << IFace << PDecl;
16874
16875 if (SecondType == Context.OverloadTy)
16877 FirstType, /*TakingAddress=*/true);
16878
16879 if (CheckInferredResultType)
16881
16882 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16884
16885 if (Complained)
16886 *Complained = true;
16887 return isInvalid;
16888}
16889
16891 llvm::APSInt *Result,
16892 AllowFoldKind CanFold) {
16893 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16894 public:
16895 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16896 QualType T) override {
16897 return S.Diag(Loc, diag::err_ice_not_integral)
16898 << T << S.LangOpts.CPlusPlus;
16899 }
16900 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16901 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16902 }
16903 } Diagnoser;
16904
16905 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16906}
16907
16909 llvm::APSInt *Result,
16910 unsigned DiagID,
16911 AllowFoldKind CanFold) {
16912 class IDDiagnoser : public VerifyICEDiagnoser {
16913 unsigned DiagID;
16914
16915 public:
16916 IDDiagnoser(unsigned DiagID)
16917 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16918
16919 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16920 return S.Diag(Loc, DiagID);
16921 }
16922 } Diagnoser(DiagID);
16923
16924 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16925}
16926
16929 QualType T) {
16930 return diagnoseNotICE(S, Loc);
16931}
16932
16935 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16936}
16937
16940 VerifyICEDiagnoser &Diagnoser,
16941 AllowFoldKind CanFold) {
16942 SourceLocation DiagLoc = E->getBeginLoc();
16943
16944 if (getLangOpts().CPlusPlus11) {
16945 // C++11 [expr.const]p5:
16946 // If an expression of literal class type is used in a context where an
16947 // integral constant expression is required, then that class type shall
16948 // have a single non-explicit conversion function to an integral or
16949 // unscoped enumeration type
16950 ExprResult Converted;
16951 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16952 VerifyICEDiagnoser &BaseDiagnoser;
16953 public:
16954 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16955 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16956 BaseDiagnoser.Suppress, true),
16957 BaseDiagnoser(BaseDiagnoser) {}
16958
16959 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16960 QualType T) override {
16961 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16962 }
16963
16964 SemaDiagnosticBuilder diagnoseIncomplete(
16965 Sema &S, SourceLocation Loc, QualType T) override {
16966 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16967 }
16968
16969 SemaDiagnosticBuilder diagnoseExplicitConv(
16970 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16971 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16972 }
16973
16974 SemaDiagnosticBuilder noteExplicitConv(
16975 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16976 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16977 << ConvTy->isEnumeralType() << ConvTy;
16978 }
16979
16980 SemaDiagnosticBuilder diagnoseAmbiguous(
16981 Sema &S, SourceLocation Loc, QualType T) override {
16982 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16983 }
16984
16985 SemaDiagnosticBuilder noteAmbiguous(
16986 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16987 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16988 << ConvTy->isEnumeralType() << ConvTy;
16989 }
16990
16991 SemaDiagnosticBuilder diagnoseConversion(
16992 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16993 llvm_unreachable("conversion functions are permitted");
16994 }
16995 } ConvertDiagnoser(Diagnoser);
16996
16997 Converted = PerformContextualImplicitConversion(DiagLoc, E,
16998 ConvertDiagnoser);
16999 if (Converted.isInvalid())
17000 return Converted;
17001 E = Converted.get();
17002 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17003 // don't try to evaluate it later. We also don't want to return the
17004 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17005 // this function will attempt to use 'Value'.
17006 if (isa<RecoveryExpr>(E))
17007 return ExprError();
17009 return ExprError();
17010 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17011 // An ICE must be of integral or unscoped enumeration type.
17012 if (!Diagnoser.Suppress)
17013 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17014 << E->getSourceRange();
17015 return ExprError();
17016 }
17017
17018 ExprResult RValueExpr = DefaultLvalueConversion(E);
17019 if (RValueExpr.isInvalid())
17020 return ExprError();
17021
17022 E = RValueExpr.get();
17023
17024 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17025 // in the non-ICE case.
17028 if (Result)
17030 if (!isa<ConstantExpr>(E))
17033
17034 if (Notes.empty())
17035 return E;
17036
17037 // If our only note is the usual "invalid subexpression" note, just point
17038 // the caret at its location rather than producing an essentially
17039 // redundant note.
17040 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17041 diag::note_invalid_subexpr_in_const_expr) {
17042 DiagLoc = Notes[0].first;
17043 Notes.clear();
17044 }
17045
17046 if (getLangOpts().CPlusPlus) {
17047 if (!Diagnoser.Suppress) {
17048 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17049 for (const PartialDiagnosticAt &Note : Notes)
17050 Diag(Note.first, Note.second);
17051 }
17052 return ExprError();
17053 }
17054
17055 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17056 for (const PartialDiagnosticAt &Note : Notes)
17057 Diag(Note.first, Note.second);
17058
17059 return E;
17060 }
17061
17062 Expr::EvalResult EvalResult;
17064 EvalResult.Diag = &Notes;
17065
17066 // Try to evaluate the expression, and produce diagnostics explaining why it's
17067 // not a constant expression as a side-effect.
17068 bool Folded =
17069 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17070 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17071 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17072
17073 if (!isa<ConstantExpr>(E))
17074 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17075
17076 // In C++11, we can rely on diagnostics being produced for any expression
17077 // which is not a constant expression. If no diagnostics were produced, then
17078 // this is a constant expression.
17079 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17080 if (Result)
17081 *Result = EvalResult.Val.getInt();
17082 return E;
17083 }
17084
17085 // If our only note is the usual "invalid subexpression" note, just point
17086 // the caret at its location rather than producing an essentially
17087 // redundant note.
17088 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17089 diag::note_invalid_subexpr_in_const_expr) {
17090 DiagLoc = Notes[0].first;
17091 Notes.clear();
17092 }
17093
17094 if (!Folded || !CanFold) {
17095 if (!Diagnoser.Suppress) {
17096 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17097 for (const PartialDiagnosticAt &Note : Notes)
17098 Diag(Note.first, Note.second);
17099 }
17100
17101 return ExprError();
17102 }
17103
17104 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17105 for (const PartialDiagnosticAt &Note : Notes)
17106 Diag(Note.first, Note.second);
17107
17108 if (Result)
17109 *Result = EvalResult.Val.getInt();
17110 return E;
17111}
17112
17113namespace {
17114 // Handle the case where we conclude a expression which we speculatively
17115 // considered to be unevaluated is actually evaluated.
17116 class TransformToPE : public TreeTransform<TransformToPE> {
17117 typedef TreeTransform<TransformToPE> BaseTransform;
17118
17119 public:
17120 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17121
17122 // Make sure we redo semantic analysis
17123 bool AlwaysRebuild() { return true; }
17124 bool ReplacingOriginal() { return true; }
17125
17126 // We need to special-case DeclRefExprs referring to FieldDecls which
17127 // are not part of a member pointer formation; normal TreeTransforming
17128 // doesn't catch this case because of the way we represent them in the AST.
17129 // FIXME: This is a bit ugly; is it really the best way to handle this
17130 // case?
17131 //
17132 // Error on DeclRefExprs referring to FieldDecls.
17133 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17134 if (isa<FieldDecl>(E->getDecl()) &&
17135 !SemaRef.isUnevaluatedContext())
17136 return SemaRef.Diag(E->getLocation(),
17137 diag::err_invalid_non_static_member_use)
17138 << E->getDecl() << E->getSourceRange();
17139
17140 return BaseTransform::TransformDeclRefExpr(E);
17141 }
17142
17143 // Exception: filter out member pointer formation
17144 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17145 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17146 return E;
17147
17148 return BaseTransform::TransformUnaryOperator(E);
17149 }
17150
17151 // The body of a lambda-expression is in a separate expression evaluation
17152 // context so never needs to be transformed.
17153 // FIXME: Ideally we wouldn't transform the closure type either, and would
17154 // just recreate the capture expressions and lambda expression.
17155 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17156 return SkipLambdaBody(E, Body);
17157 }
17158 };
17159}
17160
17162 assert(isUnevaluatedContext() &&
17163 "Should only transform unevaluated expressions");
17164 ExprEvalContexts.back().Context =
17165 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17167 return E;
17168 return TransformToPE(*this).TransformExpr(E);
17169}
17170
17172 assert(isUnevaluatedContext() &&
17173 "Should only transform unevaluated expressions");
17176 return TInfo;
17177 return TransformToPE(*this).TransformType(TInfo);
17178}
17179
17180void
17182 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17184 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17185 LambdaContextDecl, ExprContext);
17186
17187 // Discarded statements and immediate contexts nested in other
17188 // discarded statements or immediate context are themselves
17189 // a discarded statement or an immediate context, respectively.
17190 ExprEvalContexts.back().InDiscardedStatement =
17192
17193 // C++23 [expr.const]/p15
17194 // An expression or conversion is in an immediate function context if [...]
17195 // it is a subexpression of a manifestly constant-evaluated expression or
17196 // conversion.
17197 const auto &Prev = parentEvaluationContext();
17198 ExprEvalContexts.back().InImmediateFunctionContext =
17199 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17200
17201 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17202 Prev.InImmediateEscalatingFunctionContext;
17203
17204 Cleanup.reset();
17205 if (!MaybeODRUseExprs.empty())
17206 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17207}
17208
17209void
17213 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17214 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17215}
17216
17217namespace {
17218
17219const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17220 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17221 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17222 if (E->getOpcode() == UO_Deref)
17223 return CheckPossibleDeref(S, E->getSubExpr());
17224 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17225 return CheckPossibleDeref(S, E->getBase());
17226 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17227 return CheckPossibleDeref(S, E->getBase());
17228 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17229 QualType Inner;
17230 QualType Ty = E->getType();
17231 if (const auto *Ptr = Ty->getAs<PointerType>())
17232 Inner = Ptr->getPointeeType();
17233 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17234 Inner = Arr->getElementType();
17235 else
17236 return nullptr;
17237
17238 if (Inner->hasAttr(attr::NoDeref))
17239 return E;
17240 }
17241 return nullptr;
17242}
17243
17244} // namespace
17245
17247 for (const Expr *E : Rec.PossibleDerefs) {
17248 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17249 if (DeclRef) {
17250 const ValueDecl *Decl = DeclRef->getDecl();
17251 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17252 << Decl->getName() << E->getSourceRange();
17253 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17254 } else {
17255 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17256 << E->getSourceRange();
17257 }
17258 }
17259 Rec.PossibleDerefs.clear();
17260}
17261
17264 return;
17265
17266 // Note: ignoring parens here is not justified by the standard rules, but
17267 // ignoring parentheses seems like a more reasonable approach, and this only
17268 // drives a deprecation warning so doesn't affect conformance.
17269 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17270 if (BO->getOpcode() == BO_Assign) {
17271 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17272 llvm::erase(LHSs, BO->getLHS());
17273 }
17274 }
17275}
17276
17278 assert(getLangOpts().CPlusPlus20 &&
17279 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17280 "Cannot mark an immediate escalating expression outside of an "
17281 "immediate escalating context");
17282 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17283 Call && Call->getCallee()) {
17284 if (auto *DeclRef =
17285 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17286 DeclRef->setIsImmediateEscalating(true);
17287 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
17288 Ctr->setIsImmediateEscalating(true);
17289 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
17290 DeclRef->setIsImmediateEscalating(true);
17291 } else {
17292 assert(false && "expected an immediately escalating expression");
17293 }
17295 FI->FoundImmediateEscalatingExpression = true;
17296}
17297
17299 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17300 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17303 return E;
17304
17305 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17306 /// It's OK if this fails; we'll also remove this in
17307 /// HandleImmediateInvocations, but catching it here allows us to avoid
17308 /// walking the AST looking for it in simple cases.
17309 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17310 if (auto *DeclRef =
17311 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17312 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17313
17314 // C++23 [expr.const]/p16
17315 // An expression or conversion is immediate-escalating if it is not initially
17316 // in an immediate function context and it is [...] an immediate invocation
17317 // that is not a constant expression and is not a subexpression of an
17318 // immediate invocation.
17319 APValue Cached;
17320 auto CheckConstantExpressionAndKeepResult = [&]() {
17322 Expr::EvalResult Eval;
17323 Eval.Diag = &Notes;
17324 bool Res = E.get()->EvaluateAsConstantExpr(
17325 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
17326 if (Res && Notes.empty()) {
17327 Cached = std::move(Eval.Val);
17328 return true;
17329 }
17330 return false;
17331 };
17332
17333 if (!E.get()->isValueDependent() &&
17334 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17335 !CheckConstantExpressionAndKeepResult()) {
17337 return E;
17338 }
17339
17340 if (Cleanup.exprNeedsCleanups()) {
17341 // Since an immediate invocation is a full expression itself - it requires
17342 // an additional ExprWithCleanups node, but it can participate to a bigger
17343 // full expression which actually requires cleanups to be run after so
17344 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
17345 // may discard cleanups for outer expression too early.
17346
17347 // Note that ExprWithCleanups created here must always have empty cleanup
17348 // objects:
17349 // - compound literals do not create cleanup objects in C++ and immediate
17350 // invocations are C++-only.
17351 // - blocks are not allowed inside constant expressions and compiler will
17352 // issue an error if they appear there.
17353 //
17354 // Hence, in correct code any cleanup objects created inside current
17355 // evaluation context must be outside the immediate invocation.
17358 }
17359
17361 getASTContext(), E.get(),
17362 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17363 getASTContext()),
17364 /*IsImmediateInvocation*/ true);
17365 if (Cached.hasValue())
17366 Res->MoveIntoResult(Cached, getASTContext());
17367 /// Value-dependent constant expressions should not be immediately
17368 /// evaluated until they are instantiated.
17369 if (!Res->isValueDependent())
17370 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17371 return Res;
17372}
17373
17377 Expr::EvalResult Eval;
17378 Eval.Diag = &Notes;
17379 ConstantExpr *CE = Candidate.getPointer();
17380 bool Result = CE->EvaluateAsConstantExpr(
17381 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17382 if (!Result || !Notes.empty()) {
17384 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17385 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17386 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
17387 FunctionDecl *FD = nullptr;
17388 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17389 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17390 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17391 FD = Call->getConstructor();
17392 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
17393 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
17394
17395 assert(FD && FD->isImmediateFunction() &&
17396 "could not find an immediate function in this expression");
17397 if (FD->isInvalidDecl())
17398 return;
17399 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
17400 << FD << FD->isConsteval();
17401 if (auto Context =
17403 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17404 << Context->Decl;
17405 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17406 }
17407 if (!FD->isConsteval())
17409 for (auto &Note : Notes)
17410 SemaRef.Diag(Note.first, Note.second);
17411 return;
17412 }
17414}
17415
17419 struct ComplexRemove : TreeTransform<ComplexRemove> {
17421 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17424 CurrentII;
17425 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17428 4>::reverse_iterator Current)
17429 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17430 void RemoveImmediateInvocation(ConstantExpr* E) {
17431 auto It = std::find_if(CurrentII, IISet.rend(),
17433 return Elem.getPointer() == E;
17434 });
17435 // It is possible that some subexpression of the current immediate
17436 // invocation was handled from another expression evaluation context. Do
17437 // not handle the current immediate invocation if some of its
17438 // subexpressions failed before.
17439 if (It == IISet.rend()) {
17440 if (SemaRef.FailedImmediateInvocations.contains(E))
17441 CurrentII->setInt(1);
17442 } else {
17443 It->setInt(1); // Mark as deleted
17444 }
17445 }
17446 ExprResult TransformConstantExpr(ConstantExpr *E) {
17447 if (!E->isImmediateInvocation())
17448 return Base::TransformConstantExpr(E);
17449 RemoveImmediateInvocation(E);
17450 return Base::TransformExpr(E->getSubExpr());
17451 }
17452 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17453 /// we need to remove its DeclRefExpr from the DRSet.
17454 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17455 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17456 return Base::TransformCXXOperatorCallExpr(E);
17457 }
17458 /// Base::TransformUserDefinedLiteral doesn't preserve the
17459 /// UserDefinedLiteral node.
17460 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
17461 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
17462 /// here.
17463 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17464 if (!Init)
17465 return Init;
17466 /// ConstantExpr are the first layer of implicit node to be removed so if
17467 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17468 if (auto *CE = dyn_cast<ConstantExpr>(Init))
17469 if (CE->isImmediateInvocation())
17470 RemoveImmediateInvocation(CE);
17471 return Base::TransformInitializer(Init, NotCopyInit);
17472 }
17473 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17474 DRSet.erase(E);
17475 return E;
17476 }
17477 ExprResult TransformLambdaExpr(LambdaExpr *E) {
17478 // Do not rebuild lambdas to avoid creating a new type.
17479 // Lambdas have already been processed inside their eval context.
17480 return E;
17481 }
17482 bool AlwaysRebuild() { return false; }
17483 bool ReplacingOriginal() { return true; }
17484 bool AllowSkippingCXXConstructExpr() {
17485 bool Res = AllowSkippingFirstCXXConstructExpr;
17486 AllowSkippingFirstCXXConstructExpr = true;
17487 return Res;
17488 }
17489 bool AllowSkippingFirstCXXConstructExpr = true;
17490 } Transformer(SemaRef, Rec.ReferenceToConsteval,
17492
17493 /// CXXConstructExpr with a single argument are getting skipped by
17494 /// TreeTransform in some situtation because they could be implicit. This
17495 /// can only occur for the top-level CXXConstructExpr because it is used
17496 /// nowhere in the expression being transformed therefore will not be rebuilt.
17497 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17498 /// skipping the first CXXConstructExpr.
17499 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17500 Transformer.AllowSkippingFirstCXXConstructExpr = false;
17501
17502 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17503 // The result may not be usable in case of previous compilation errors.
17504 // In this case evaluation of the expression may result in crash so just
17505 // don't do anything further with the result.
17506 if (Res.isUsable()) {
17508 It->getPointer()->setSubExpr(Res.get());
17509 }
17510}
17511
17512static void
17515 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17516 Rec.ReferenceToConsteval.size() == 0) ||
17518 return;
17519
17520 /// When we have more than 1 ImmediateInvocationCandidates or previously
17521 /// failed immediate invocations, we need to check for nested
17522 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
17523 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
17524 /// invocation.
17525 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
17527
17528 /// Prevent sema calls during the tree transform from adding pointers that
17529 /// are already in the sets.
17530 llvm::SaveAndRestore DisableIITracking(
17532
17533 /// Prevent diagnostic during tree transfrom as they are duplicates
17535
17536 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17537 It != Rec.ImmediateInvocationCandidates.rend(); It++)
17538 if (!It->getInt())
17540 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17541 Rec.ReferenceToConsteval.size()) {
17542 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17543 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17544 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17545 bool VisitDeclRefExpr(DeclRefExpr *E) {
17546 DRSet.erase(E);
17547 return DRSet.size();
17548 }
17549 } Visitor(Rec.ReferenceToConsteval);
17550 Visitor.TraverseStmt(
17551 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17552 }
17553 for (auto CE : Rec.ImmediateInvocationCandidates)
17554 if (!CE.getInt())
17556 for (auto *DR : Rec.ReferenceToConsteval) {
17557 // If the expression is immediate escalating, it is not an error;
17558 // The outer context itself becomes immediate and further errors,
17559 // if any, will be handled by DiagnoseImmediateEscalatingReason.
17560 if (DR->isImmediateEscalating())
17561 continue;
17562 auto *FD = cast<FunctionDecl>(DR->getDecl());
17563 const NamedDecl *ND = FD;
17564 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
17565 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
17566 ND = MD->getParent();
17567
17568 // C++23 [expr.const]/p16
17569 // An expression or conversion is immediate-escalating if it is not
17570 // initially in an immediate function context and it is [...] a
17571 // potentially-evaluated id-expression that denotes an immediate function
17572 // that is not a subexpression of an immediate invocation.
17573 bool ImmediateEscalating = false;
17574 bool IsPotentiallyEvaluated =
17575 Rec.Context ==
17577 Rec.Context ==
17579 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
17580 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
17581
17583 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
17584 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17585 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
17586 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
17587 if (auto Context =
17589 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17590 << Context->Decl;
17591 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17592 }
17593 if (FD->isImmediateEscalating() && !FD->isConsteval())
17595
17596 } else {
17598 }
17599 }
17600}
17601
17604 unsigned NumTypos = Rec.NumTypos;
17605
17606 if (!Rec.Lambdas.empty()) {
17608 if (!getLangOpts().CPlusPlus20 &&
17609 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17610 Rec.isUnevaluated() ||
17612 unsigned D;
17613 if (Rec.isUnevaluated()) {
17614 // C++11 [expr.prim.lambda]p2:
17615 // A lambda-expression shall not appear in an unevaluated operand
17616 // (Clause 5).
17617 D = diag::err_lambda_unevaluated_operand;
17618 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17619 // C++1y [expr.const]p2:
17620 // A conditional-expression e is a core constant expression unless the
17621 // evaluation of e, following the rules of the abstract machine, would
17622 // evaluate [...] a lambda-expression.
17623 D = diag::err_lambda_in_constant_expression;
17624 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17625 // C++17 [expr.prim.lamda]p2:
17626 // A lambda-expression shall not appear [...] in a template-argument.
17627 D = diag::err_lambda_in_invalid_context;
17628 } else
17629 llvm_unreachable("Couldn't infer lambda error message.");
17630
17631 for (const auto *L : Rec.Lambdas)
17632 Diag(L->getBeginLoc(), D);
17633 }
17634 }
17635
17636 // Append the collected materialized temporaries into previous context before
17637 // exit if the previous also is a lifetime extending context.
17638 auto &PrevRecord = parentEvaluationContext();
17640 PrevRecord.InLifetimeExtendingContext &&
17641 !Rec.ForRangeLifetimeExtendTemps.empty()) {
17642 PrevRecord.ForRangeLifetimeExtendTemps.append(
17644 }
17645
17647 HandleImmediateInvocations(*this, Rec);
17648
17649 // Warn on any volatile-qualified simple-assignments that are not discarded-
17650 // value expressions nor unevaluated operands (those cases get removed from
17651 // this list by CheckUnusedVolatileAssignment).
17652 for (auto *BO : Rec.VolatileAssignmentLHSs)
17653 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17654 << BO->getType();
17655
17656 // When are coming out of an unevaluated context, clear out any
17657 // temporaries that we may have created as part of the evaluation of
17658 // the expression in that context: they aren't relevant because they
17659 // will never be constructed.
17660 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17662 ExprCleanupObjects.end());
17663 Cleanup = Rec.ParentCleanup;
17666 // Otherwise, merge the contexts together.
17667 } else {
17669 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17670 Rec.SavedMaybeODRUseExprs.end());
17671 }
17672
17673 // Pop the current expression evaluation context off the stack.
17674 ExprEvalContexts.pop_back();
17675
17676 // The global expression evaluation context record is never popped.
17677 ExprEvalContexts.back().NumTypos += NumTypos;
17678}
17679
17681 ExprCleanupObjects.erase(
17682 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17683 ExprCleanupObjects.end());
17684 Cleanup.reset();
17685 MaybeODRUseExprs.clear();
17686}
17687
17690 if (Result.isInvalid())
17691 return ExprError();
17692 E = Result.get();
17693 if (!E->getType()->isVariablyModifiedType())
17694 return E;
17696}
17697
17698/// Are we in a context that is potentially constant evaluated per C++20
17699/// [expr.const]p12?
17701 /// C++2a [expr.const]p12:
17702 // An expression or conversion is potentially constant evaluated if it is
17703 switch (SemaRef.ExprEvalContexts.back().Context) {
17706
17707 // -- a manifestly constant-evaluated expression,
17711 // -- a potentially-evaluated expression,
17713 // -- an immediate subexpression of a braced-init-list,
17714
17715 // -- [FIXME] an expression of the form & cast-expression that occurs
17716 // within a templated entity
17717 // -- a subexpression of one of the above that is not a subexpression of
17718 // a nested unevaluated operand.
17719 return true;
17720
17723 // Expressions in this context are never evaluated.
17724 return false;
17725 }
17726 llvm_unreachable("Invalid context");
17727}
17728
17729/// Return true if this function has a calling convention that requires mangling
17730/// in the size of the parameter pack.
17732 // These manglings don't do anything on non-Windows or non-x86 platforms, so
17733 // we don't need parameter type sizes.
17734 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17735 if (!TT.isOSWindows() || !TT.isX86())
17736 return false;
17737
17738 // If this is C++ and this isn't an extern "C" function, parameters do not
17739 // need to be complete. In this case, C++ mangling will apply, which doesn't
17740 // use the size of the parameters.
17741 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17742 return false;
17743
17744 // Stdcall, fastcall, and vectorcall need this special treatment.
17745 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17746 switch (CC) {
17747 case CC_X86StdCall:
17748 case CC_X86FastCall:
17749 case CC_X86VectorCall:
17750 return true;
17751 default:
17752 break;
17753 }
17754 return false;
17755}
17756
17757/// Require that all of the parameter types of function be complete. Normally,
17758/// parameter types are only required to be complete when a function is called
17759/// or defined, but to mangle functions with certain calling conventions, the
17760/// mangler needs to know the size of the parameter list. In this situation,
17761/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17762/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17763/// result in a linker error. Clang doesn't implement this behavior, and instead
17764/// attempts to error at compile time.
17767 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17768 FunctionDecl *FD;
17769 ParmVarDecl *Param;
17770
17771 public:
17772 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17773 : FD(FD), Param(Param) {}
17774
17775 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17776 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17777 StringRef CCName;
17778 switch (CC) {
17779 case CC_X86StdCall:
17780 CCName = "stdcall";
17781 break;
17782 case CC_X86FastCall:
17783 CCName = "fastcall";
17784 break;
17785 case CC_X86VectorCall:
17786 CCName = "vectorcall";
17787 break;
17788 default:
17789 llvm_unreachable("CC does not need mangling");
17790 }
17791
17792 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17793 << Param->getDeclName() << FD->getDeclName() << CCName;
17794 }
17795 };
17796
17797 for (ParmVarDecl *Param : FD->parameters()) {
17798 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17799 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17800 }
17801}
17802
17803namespace {
17804enum class OdrUseContext {
17805 /// Declarations in this context are not odr-used.
17806 None,
17807 /// Declarations in this context are formally odr-used, but this is a
17808 /// dependent context.
17809 Dependent,
17810 /// Declarations in this context are odr-used but not actually used (yet).
17811 FormallyOdrUsed,
17812 /// Declarations in this context are used.
17813 Used
17814};
17815}
17816
17817/// Are we within a context in which references to resolved functions or to
17818/// variables result in odr-use?
17819static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17820 OdrUseContext Result;
17821
17822 switch (SemaRef.ExprEvalContexts.back().Context) {
17826 return OdrUseContext::None;
17827
17831 Result = OdrUseContext::Used;
17832 break;
17833
17835 Result = OdrUseContext::FormallyOdrUsed;
17836 break;
17837
17839 // A default argument formally results in odr-use, but doesn't actually
17840 // result in a use in any real sense until it itself is used.
17841 Result = OdrUseContext::FormallyOdrUsed;
17842 break;
17843 }
17844
17846 return OdrUseContext::Dependent;
17847
17848 return Result;
17849}
17850
17852 if (!Func->isConstexpr())
17853 return false;
17854
17855 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17856 return true;
17857 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17858 return CCD && CCD->getInheritedConstructor();
17859}
17860
17862 bool MightBeOdrUse) {
17863 assert(Func && "No function?");
17864
17865 Func->setReferenced();
17866
17867 // Recursive functions aren't really used until they're used from some other
17868 // context.
17869 bool IsRecursiveCall = CurContext == Func;
17870
17871 // C++11 [basic.def.odr]p3:
17872 // A function whose name appears as a potentially-evaluated expression is
17873 // odr-used if it is the unique lookup result or the selected member of a
17874 // set of overloaded functions [...].
17875 //
17876 // We (incorrectly) mark overload resolution as an unevaluated context, so we
17877 // can just check that here.
17878 OdrUseContext OdrUse =
17879 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17880 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17881 OdrUse = OdrUseContext::FormallyOdrUsed;
17882
17883 // Trivial default constructors and destructors are never actually used.
17884 // FIXME: What about other special members?
17885 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17886 OdrUse == OdrUseContext::Used) {
17887 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17888 if (Constructor->isDefaultConstructor())
17889 OdrUse = OdrUseContext::FormallyOdrUsed;
17890 if (isa<CXXDestructorDecl>(Func))
17891 OdrUse = OdrUseContext::FormallyOdrUsed;
17892 }
17893
17894 // C++20 [expr.const]p12:
17895 // A function [...] is needed for constant evaluation if it is [...] a
17896 // constexpr function that is named by an expression that is potentially
17897 // constant evaluated
17898 bool NeededForConstantEvaluation =
17901
17902 // Determine whether we require a function definition to exist, per
17903 // C++11 [temp.inst]p3:
17904 // Unless a function template specialization has been explicitly
17905 // instantiated or explicitly specialized, the function template
17906 // specialization is implicitly instantiated when the specialization is
17907 // referenced in a context that requires a function definition to exist.
17908 // C++20 [temp.inst]p7:
17909 // The existence of a definition of a [...] function is considered to
17910 // affect the semantics of the program if the [...] function is needed for
17911 // constant evaluation by an expression
17912 // C++20 [basic.def.odr]p10:
17913 // Every program shall contain exactly one definition of every non-inline
17914 // function or variable that is odr-used in that program outside of a
17915 // discarded statement
17916 // C++20 [special]p1:
17917 // The implementation will implicitly define [defaulted special members]
17918 // if they are odr-used or needed for constant evaluation.
17919 //
17920 // Note that we skip the implicit instantiation of templates that are only
17921 // used in unused default arguments or by recursive calls to themselves.
17922 // This is formally non-conforming, but seems reasonable in practice.
17923 bool NeedDefinition =
17924 !IsRecursiveCall &&
17925 (OdrUse == OdrUseContext::Used ||
17926 (NeededForConstantEvaluation && !Func->isPureVirtual()));
17927
17928 // C++14 [temp.expl.spec]p6:
17929 // If a template [...] is explicitly specialized then that specialization
17930 // shall be declared before the first use of that specialization that would
17931 // cause an implicit instantiation to take place, in every translation unit
17932 // in which such a use occurs
17933 if (NeedDefinition &&
17934 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17935 Func->getMemberSpecializationInfo()))
17937
17938 if (getLangOpts().CUDA)
17939 CUDA().CheckCall(Loc, Func);
17940
17941 // If we need a definition, try to create one.
17942 if (NeedDefinition && !Func->getBody()) {
17944 if (CXXConstructorDecl *Constructor =
17945 dyn_cast<CXXConstructorDecl>(Func)) {
17946 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17947 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17948 if (Constructor->isDefaultConstructor()) {
17949 if (Constructor->isTrivial() &&
17950 !Constructor->hasAttr<DLLExportAttr>())
17951 return;
17953 } else if (Constructor->isCopyConstructor()) {
17954 DefineImplicitCopyConstructor(Loc, Constructor);
17955 } else if (Constructor->isMoveConstructor()) {
17956 DefineImplicitMoveConstructor(Loc, Constructor);
17957 }
17958 } else if (Constructor->getInheritedConstructor()) {
17959 DefineInheritingConstructor(Loc, Constructor);
17960 }
17961 } else if (CXXDestructorDecl *Destructor =
17962 dyn_cast<CXXDestructorDecl>(Func)) {
17963 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17964 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17965 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17966 return;
17968 }
17969 if (Destructor->isVirtual() && getLangOpts().AppleKext)
17970 MarkVTableUsed(Loc, Destructor->getParent());
17971 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17972 if (MethodDecl->isOverloadedOperator() &&
17973 MethodDecl->getOverloadedOperator() == OO_Equal) {
17974 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17975 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17976 if (MethodDecl->isCopyAssignmentOperator())
17977 DefineImplicitCopyAssignment(Loc, MethodDecl);
17978 else if (MethodDecl->isMoveAssignmentOperator())
17979 DefineImplicitMoveAssignment(Loc, MethodDecl);
17980 }
17981 } else if (isa<CXXConversionDecl>(MethodDecl) &&
17982 MethodDecl->getParent()->isLambda()) {
17983 CXXConversionDecl *Conversion =
17984 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17985 if (Conversion->isLambdaToBlockPointerConversion())
17987 else
17989 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17990 MarkVTableUsed(Loc, MethodDecl->getParent());
17991 }
17992
17993 if (Func->isDefaulted() && !Func->isDeleted()) {
17997 }
17998
17999 // Implicit instantiation of function templates and member functions of
18000 // class templates.
18001 if (Func->isImplicitlyInstantiable()) {
18003 Func->getTemplateSpecializationKindForInstantiation();
18004 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18005 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18006 if (FirstInstantiation) {
18007 PointOfInstantiation = Loc;
18008 if (auto *MSI = Func->getMemberSpecializationInfo())
18009 MSI->setPointOfInstantiation(Loc);
18010 // FIXME: Notify listener.
18011 else
18012 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18013 } else if (TSK != TSK_ImplicitInstantiation) {
18014 // Use the point of use as the point of instantiation, instead of the
18015 // point of explicit instantiation (which we track as the actual point
18016 // of instantiation). This gives better backtraces in diagnostics.
18017 PointOfInstantiation = Loc;
18018 }
18019
18020 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18021 Func->isConstexpr()) {
18022 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18023 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18024 CodeSynthesisContexts.size())
18026 std::make_pair(Func, PointOfInstantiation));
18027 else if (Func->isConstexpr())
18028 // Do not defer instantiations of constexpr functions, to avoid the
18029 // expression evaluator needing to call back into Sema if it sees a
18030 // call to such a function.
18031 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18032 else {
18033 Func->setInstantiationIsPending(true);
18034 PendingInstantiations.push_back(
18035 std::make_pair(Func, PointOfInstantiation));
18036 // Notify the consumer that a function was implicitly instantiated.
18038 }
18039 }
18040 } else {
18041 // Walk redefinitions, as some of them may be instantiable.
18042 for (auto *i : Func->redecls()) {
18043 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18044 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18045 }
18046 }
18047 });
18048 }
18049
18050 // If a constructor was defined in the context of a default parameter
18051 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18052 // context), its initializers may not be referenced yet.
18053 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18055 *this,
18056 Constructor->isImmediateFunction()
18059 Constructor);
18060 for (CXXCtorInitializer *Init : Constructor->inits()) {
18061 if (Init->isInClassMemberInitializer())
18062 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18063 MarkDeclarationsReferencedInExpr(Init->getInit());
18064 });
18065 }
18066 }
18067
18068 // C++14 [except.spec]p17:
18069 // An exception-specification is considered to be needed when:
18070 // - the function is odr-used or, if it appears in an unevaluated operand,
18071 // would be odr-used if the expression were potentially-evaluated;
18072 //
18073 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18074 // function is a pure virtual function we're calling, and in that case the
18075 // function was selected by overload resolution and we need to resolve its
18076 // exception specification for a different reason.
18077 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18080
18081 // A callee could be called by a host function then by a device function.
18082 // If we only try recording once, we will miss recording the use on device
18083 // side. Therefore keep trying until it is recorded.
18084 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18087
18088 // If this is the first "real" use, act on that.
18089 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18090 // Keep track of used but undefined functions.
18091 if (!Func->isDefined()) {
18092 if (mightHaveNonExternalLinkage(Func))
18093 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18094 else if (Func->getMostRecentDecl()->isInlined() &&
18095 !LangOpts.GNUInline &&
18096 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18097 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18099 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18100 }
18101
18102 // Some x86 Windows calling conventions mangle the size of the parameter
18103 // pack into the name. Computing the size of the parameters requires the
18104 // parameter types to be complete. Check that now.
18107
18108 // In the MS C++ ABI, the compiler emits destructor variants where they are
18109 // used. If the destructor is used here but defined elsewhere, mark the
18110 // virtual base destructors referenced. If those virtual base destructors
18111 // are inline, this will ensure they are defined when emitting the complete
18112 // destructor variant. This checking may be redundant if the destructor is
18113 // provided later in this TU.
18115 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18116 CXXRecordDecl *Parent = Dtor->getParent();
18117 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18119 }
18120 }
18121
18122 Func->markUsed(Context);
18123 }
18124}
18125
18126/// Directly mark a variable odr-used. Given a choice, prefer to use
18127/// MarkVariableReferenced since it does additional checks and then
18128/// calls MarkVarDeclODRUsed.
18129/// If the variable must be captured:
18130/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18131/// - else capture it in the DeclContext that maps to the
18132/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18133static void
18135 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18136 // Keep track of used but undefined variables.
18137 // FIXME: We shouldn't suppress this warning for static data members.
18138 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18139 assert(Var && "expected a capturable variable");
18140
18142 (!Var->isExternallyVisible() || Var->isInline() ||
18144 !(Var->isStaticDataMember() && Var->hasInit())) {
18146 if (old.isInvalid())
18147 old = Loc;
18148 }
18149 QualType CaptureType, DeclRefType;
18150 if (SemaRef.LangOpts.OpenMP)
18153 /*EllipsisLoc*/ SourceLocation(),
18154 /*BuildAndDiagnose*/ true, CaptureType,
18155 DeclRefType, FunctionScopeIndexToStopAt);
18156
18157 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18158 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18159 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18160 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18161 if (VarTarget == SemaCUDA::CVT_Host &&
18162 (UserTarget == CUDAFunctionTarget::Device ||
18163 UserTarget == CUDAFunctionTarget::HostDevice ||
18164 UserTarget == CUDAFunctionTarget::Global)) {
18165 // Diagnose ODR-use of host global variables in device functions.
18166 // Reference of device global variables in host functions is allowed
18167 // through shadow variables therefore it is not diagnosed.
18168 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18169 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18170 << /*host*/ 2 << /*variable*/ 1 << Var
18171 << llvm::to_underlying(UserTarget);
18173 Var->getType().isConstQualified()
18174 ? diag::note_cuda_const_var_unpromoted
18175 : diag::note_cuda_host_var);
18176 }
18177 } else if (VarTarget == SemaCUDA::CVT_Device &&
18178 !Var->hasAttr<CUDASharedAttr>() &&
18179 (UserTarget == CUDAFunctionTarget::Host ||
18180 UserTarget == CUDAFunctionTarget::HostDevice)) {
18181 // Record a CUDA/HIP device side variable if it is ODR-used
18182 // by host code. This is done conservatively, when the variable is
18183 // referenced in any of the following contexts:
18184 // - a non-function context
18185 // - a host function
18186 // - a host device function
18187 // This makes the ODR-use of the device side variable by host code to
18188 // be visible in the device compilation for the compiler to be able to
18189 // emit template variables instantiated by host code only and to
18190 // externalize the static device side variable ODR-used by host code.
18191 if (!Var->hasExternalStorage())
18193 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18194 (!FD || (!FD->getDescribedFunctionTemplate() &&
18198 }
18199 }
18200
18201 V->markUsed(SemaRef.Context);
18202}
18203
18206 unsigned CapturingScopeIndex) {
18207 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18208}
18209
18211 ValueDecl *var) {
18212 DeclContext *VarDC = var->getDeclContext();
18213
18214 // If the parameter still belongs to the translation unit, then
18215 // we're actually just using one parameter in the declaration of
18216 // the next.
18217 if (isa<ParmVarDecl>(var) &&
18218 isa<TranslationUnitDecl>(VarDC))
18219 return;
18220
18221 // For C code, don't diagnose about capture if we're not actually in code
18222 // right now; it's impossible to write a non-constant expression outside of
18223 // function context, so we'll get other (more useful) diagnostics later.
18224 //
18225 // For C++, things get a bit more nasty... it would be nice to suppress this
18226 // diagnostic for certain cases like using a local variable in an array bound
18227 // for a member of a local class, but the correct predicate is not obvious.
18228 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18229 return;
18230
18231 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18232 unsigned ContextKind = 3; // unknown
18233 if (isa<CXXMethodDecl>(VarDC) &&
18234 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18235 ContextKind = 2;
18236 } else if (isa<FunctionDecl>(VarDC)) {
18237 ContextKind = 0;
18238 } else if (isa<BlockDecl>(VarDC)) {
18239 ContextKind = 1;
18240 }
18241
18242 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18243 << var << ValueKind << ContextKind << VarDC;
18244 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18245 << var;
18246
18247 // FIXME: Add additional diagnostic info about class etc. which prevents
18248 // capture.
18249}
18250
18252 ValueDecl *Var,
18253 bool &SubCapturesAreNested,
18254 QualType &CaptureType,
18255 QualType &DeclRefType) {
18256 // Check whether we've already captured it.
18257 if (CSI->CaptureMap.count(Var)) {
18258 // If we found a capture, any subcaptures are nested.
18259 SubCapturesAreNested = true;
18260
18261 // Retrieve the capture type for this variable.
18262 CaptureType = CSI->getCapture(Var).getCaptureType();
18263
18264 // Compute the type of an expression that refers to this variable.
18265 DeclRefType = CaptureType.getNonReferenceType();
18266
18267 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18268 // are mutable in the sense that user can change their value - they are
18269 // private instances of the captured declarations.
18270 const Capture &Cap = CSI->getCapture(Var);
18271 if (Cap.isCopyCapture() &&
18272 !(isa<LambdaScopeInfo>(CSI) &&
18273 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
18274 !(isa<CapturedRegionScopeInfo>(CSI) &&
18275 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18276 DeclRefType.addConst();
18277 return true;
18278 }
18279 return false;
18280}
18281
18282// Only block literals, captured statements, and lambda expressions can
18283// capture; other scopes don't work.
18285 ValueDecl *Var,
18287 const bool Diagnose,
18288 Sema &S) {
18289 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18291
18292 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18293 if (Underlying) {
18294 if (Underlying->hasLocalStorage() && Diagnose)
18296 }
18297 return nullptr;
18298}
18299
18300// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18301// certain types of variables (unnamed, variably modified types etc.)
18302// so check for eligibility.
18304 SourceLocation Loc, const bool Diagnose,
18305 Sema &S) {
18306
18307 assert((isa<VarDecl, BindingDecl>(Var)) &&
18308 "Only variables and structured bindings can be captured");
18309
18310 bool IsBlock = isa<BlockScopeInfo>(CSI);
18311 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18312
18313 // Lambdas are not allowed to capture unnamed variables
18314 // (e.g. anonymous unions).
18315 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18316 // assuming that's the intent.
18317 if (IsLambda && !Var->getDeclName()) {
18318 if (Diagnose) {
18319 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18320 S.Diag(Var->getLocation(), diag::note_declared_at);
18321 }
18322 return false;
18323 }
18324
18325 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18326 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18327 if (Diagnose) {
18328 S.Diag(Loc, diag::err_ref_vm_type);
18329 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18330 }
18331 return false;
18332 }
18333 // Prohibit structs with flexible array members too.
18334 // We cannot capture what is in the tail end of the struct.
18335 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18336 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18337 if (Diagnose) {
18338 if (IsBlock)
18339 S.Diag(Loc, diag::err_ref_flexarray_type);
18340 else
18341 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18342 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18343 }
18344 return false;
18345 }
18346 }
18347 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18348 // Lambdas and captured statements are not allowed to capture __block
18349 // variables; they don't support the expected semantics.
18350 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18351 if (Diagnose) {
18352 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18353 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18354 }
18355 return false;
18356 }
18357 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18358 if (S.getLangOpts().OpenCL && IsBlock &&
18359 Var->getType()->isBlockPointerType()) {
18360 if (Diagnose)
18361 S.Diag(Loc, diag::err_opencl_block_ref_block);
18362 return false;
18363 }
18364
18365 if (isa<BindingDecl>(Var)) {
18366 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18367 if (Diagnose)
18369 return false;
18370 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18371 S.Diag(Loc, S.LangOpts.CPlusPlus20
18372 ? diag::warn_cxx17_compat_capture_binding
18373 : diag::ext_capture_binding)
18374 << Var;
18375 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18376 }
18377 }
18378
18379 return true;
18380}
18381
18382// Returns true if the capture by block was successful.
18384 SourceLocation Loc, const bool BuildAndDiagnose,
18385 QualType &CaptureType, QualType &DeclRefType,
18386 const bool Nested, Sema &S, bool Invalid) {
18387 bool ByRef = false;
18388
18389 // Blocks are not allowed to capture arrays, excepting OpenCL.
18390 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18391 // (decayed to pointers).
18392 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18393 if (BuildAndDiagnose) {
18394 S.Diag(Loc, diag::err_ref_array_type);
18395 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18396 Invalid = true;
18397 } else {
18398 return false;
18399 }
18400 }
18401
18402 // Forbid the block-capture of autoreleasing variables.
18403 if (!Invalid &&
18405 if (BuildAndDiagnose) {
18406 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18407 << /*block*/ 0;
18408 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18409 Invalid = true;
18410 } else {
18411 return false;
18412 }
18413 }
18414
18415 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18416 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18417 QualType PointeeTy = PT->getPointeeType();
18418
18419 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18421 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18422 if (BuildAndDiagnose) {
18423 SourceLocation VarLoc = Var->getLocation();
18424 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18425 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18426 }
18427 }
18428 }
18429
18430 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18431 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18432 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
18433 // Block capture by reference does not change the capture or
18434 // declaration reference types.
18435 ByRef = true;
18436 } else {
18437 // Block capture by copy introduces 'const'.
18438 CaptureType = CaptureType.getNonReferenceType().withConst();
18439 DeclRefType = CaptureType;
18440 }
18441
18442 // Actually capture the variable.
18443 if (BuildAndDiagnose)
18444 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18445 CaptureType, Invalid);
18446
18447 return !Invalid;
18448}
18449
18450/// Capture the given variable in the captured region.
18453 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18454 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18455 bool IsTopScope, Sema &S, bool Invalid) {
18456 // By default, capture variables by reference.
18457 bool ByRef = true;
18458 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18459 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18460 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18461 // Using an LValue reference type is consistent with Lambdas (see below).
18462 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
18463 bool HasConst = DeclRefType.isConstQualified();
18464 DeclRefType = DeclRefType.getUnqualifiedType();
18465 // Don't lose diagnostics about assignments to const.
18466 if (HasConst)
18467 DeclRefType.addConst();
18468 }
18469 // Do not capture firstprivates in tasks.
18470 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
18471 RSI->OpenMPCaptureLevel) != OMPC_unknown)
18472 return true;
18473 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18474 RSI->OpenMPCaptureLevel);
18475 }
18476
18477 if (ByRef)
18478 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18479 else
18480 CaptureType = DeclRefType;
18481
18482 // Actually capture the variable.
18483 if (BuildAndDiagnose)
18484 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18485 Loc, SourceLocation(), CaptureType, Invalid);
18486
18487 return !Invalid;
18488}
18489
18490/// Capture the given variable in the lambda.
18492 SourceLocation Loc, const bool BuildAndDiagnose,
18493 QualType &CaptureType, QualType &DeclRefType,
18494 const bool RefersToCapturedVariable,
18495 const Sema::TryCaptureKind Kind,
18496 SourceLocation EllipsisLoc, const bool IsTopScope,
18497 Sema &S, bool Invalid) {
18498 // Determine whether we are capturing by reference or by value.
18499 bool ByRef = false;
18500 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18501 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18502 } else {
18503 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18504 }
18505
18506 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
18508 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
18509 Invalid = true;
18510 }
18511
18512 // Compute the type of the field that will capture this variable.
18513 if (ByRef) {
18514 // C++11 [expr.prim.lambda]p15:
18515 // An entity is captured by reference if it is implicitly or
18516 // explicitly captured but not captured by copy. It is
18517 // unspecified whether additional unnamed non-static data
18518 // members are declared in the closure type for entities
18519 // captured by reference.
18520 //
18521 // FIXME: It is not clear whether we want to build an lvalue reference
18522 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18523 // to do the former, while EDG does the latter. Core issue 1249 will
18524 // clarify, but for now we follow GCC because it's a more permissive and
18525 // easily defensible position.
18526 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18527 } else {
18528 // C++11 [expr.prim.lambda]p14:
18529 // For each entity captured by copy, an unnamed non-static
18530 // data member is declared in the closure type. The
18531 // declaration order of these members is unspecified. The type
18532 // of such a data member is the type of the corresponding
18533 // captured entity if the entity is not a reference to an
18534 // object, or the referenced type otherwise. [Note: If the
18535 // captured entity is a reference to a function, the
18536 // corresponding data member is also a reference to a
18537 // function. - end note ]
18538 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18539 if (!RefType->getPointeeType()->isFunctionType())
18540 CaptureType = RefType->getPointeeType();
18541 }
18542
18543 // Forbid the lambda copy-capture of autoreleasing variables.
18544 if (!Invalid &&
18546 if (BuildAndDiagnose) {
18547 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18548 S.Diag(Var->getLocation(), diag::note_previous_decl)
18549 << Var->getDeclName();
18550 Invalid = true;
18551 } else {
18552 return false;
18553 }
18554 }
18555
18556 // Make sure that by-copy captures are of a complete and non-abstract type.
18557 if (!Invalid && BuildAndDiagnose) {
18558 if (!CaptureType->isDependentType() &&
18560 Loc, CaptureType,
18561 diag::err_capture_of_incomplete_or_sizeless_type,
18562 Var->getDeclName()))
18563 Invalid = true;
18564 else if (S.RequireNonAbstractType(Loc, CaptureType,
18565 diag::err_capture_of_abstract_type))
18566 Invalid = true;
18567 }
18568 }
18569
18570 // Compute the type of a reference to this captured variable.
18571 if (ByRef)
18572 DeclRefType = CaptureType.getNonReferenceType();
18573 else {
18574 // C++ [expr.prim.lambda]p5:
18575 // The closure type for a lambda-expression has a public inline
18576 // function call operator [...]. This function call operator is
18577 // declared const (9.3.1) if and only if the lambda-expression's
18578 // parameter-declaration-clause is not followed by mutable.
18579 DeclRefType = CaptureType.getNonReferenceType();
18580 bool Const = LSI->lambdaCaptureShouldBeConst();
18581 if (Const && !CaptureType->isReferenceType())
18582 DeclRefType.addConst();
18583 }
18584
18585 // Add the capture.
18586 if (BuildAndDiagnose)
18587 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18588 Loc, EllipsisLoc, CaptureType, Invalid);
18589
18590 return !Invalid;
18591}
18592
18594 const ASTContext &Context) {
18595 // Offer a Copy fix even if the type is dependent.
18596 if (Var->getType()->isDependentType())
18597 return true;
18599 if (T.isTriviallyCopyableType(Context))
18600 return true;
18601 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18602
18603 if (!(RD = RD->getDefinition()))
18604 return false;
18605 if (RD->hasSimpleCopyConstructor())
18606 return true;
18607 if (RD->hasUserDeclaredCopyConstructor())
18608 for (CXXConstructorDecl *Ctor : RD->ctors())
18609 if (Ctor->isCopyConstructor())
18610 return !Ctor->isDeleted();
18611 }
18612 return false;
18613}
18614
18615/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18616/// default capture. Fixes may be omitted if they aren't allowed by the
18617/// standard, for example we can't emit a default copy capture fix-it if we
18618/// already explicitly copy capture capture another variable.
18620 ValueDecl *Var) {
18622 // Don't offer Capture by copy of default capture by copy fixes if Var is
18623 // known not to be copy constructible.
18624 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18625
18626 SmallString<32> FixBuffer;
18627 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18628 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18629 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18630 if (ShouldOfferCopyFix) {
18631 // Offer fixes to insert an explicit capture for the variable.
18632 // [] -> [VarName]
18633 // [OtherCapture] -> [OtherCapture, VarName]
18634 FixBuffer.assign({Separator, Var->getName()});
18635 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18636 << Var << /*value*/ 0
18637 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18638 }
18639 // As above but capture by reference.
18640 FixBuffer.assign({Separator, "&", Var->getName()});
18641 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18642 << Var << /*reference*/ 1
18643 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18644 }
18645
18646 // Only try to offer default capture if there are no captures excluding this
18647 // and init captures.
18648 // [this]: OK.
18649 // [X = Y]: OK.
18650 // [&A, &B]: Don't offer.
18651 // [A, B]: Don't offer.
18652 if (llvm::any_of(LSI->Captures, [](Capture &C) {
18653 return !C.isThisCapture() && !C.isInitCapture();
18654 }))
18655 return;
18656
18657 // The default capture specifiers, '=' or '&', must appear first in the
18658 // capture body.
18659 SourceLocation DefaultInsertLoc =
18661
18662 if (ShouldOfferCopyFix) {
18663 bool CanDefaultCopyCapture = true;
18664 // [=, *this] OK since c++17
18665 // [=, this] OK since c++20
18666 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18667 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18669 : false;
18670 // We can't use default capture by copy if any captures already specified
18671 // capture by copy.
18672 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18673 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18674 })) {
18675 FixBuffer.assign({"=", Separator});
18676 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18677 << /*value*/ 0
18678 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18679 }
18680 }
18681
18682 // We can't use default capture by reference if any captures already specified
18683 // capture by reference.
18684 if (llvm::none_of(LSI->Captures, [](Capture &C) {
18685 return !C.isInitCapture() && C.isReferenceCapture() &&
18686 !C.isThisCapture();
18687 })) {
18688 FixBuffer.assign({"&", Separator});
18689 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18690 << /*reference*/ 1
18691 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18692 }
18693}
18694
18696 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18697 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18698 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18699 // An init-capture is notionally from the context surrounding its
18700 // declaration, but its parent DC is the lambda class.
18701 DeclContext *VarDC = Var->getDeclContext();
18702 DeclContext *DC = CurContext;
18703
18704 // Skip past RequiresExprBodys because they don't constitute function scopes.
18705 while (DC->isRequiresExprBody())
18706 DC = DC->getParent();
18707
18708 // tryCaptureVariable is called every time a DeclRef is formed,
18709 // it can therefore have non-negigible impact on performances.
18710 // For local variables and when there is no capturing scope,
18711 // we can bailout early.
18712 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
18713 return true;
18714
18715 // Exception: Function parameters are not tied to the function's DeclContext
18716 // until we enter the function definition. Capturing them anyway would result
18717 // in an out-of-bounds error while traversing DC and its parents.
18718 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
18719 return true;
18720
18721 const auto *VD = dyn_cast<VarDecl>(Var);
18722 if (VD) {
18723 if (VD->isInitCapture())
18724 VarDC = VarDC->getParent();
18725 } else {
18727 }
18728 assert(VD && "Cannot capture a null variable");
18729
18730 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18731 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18732 // We need to sync up the Declaration Context with the
18733 // FunctionScopeIndexToStopAt
18734 if (FunctionScopeIndexToStopAt) {
18735 unsigned FSIndex = FunctionScopes.size() - 1;
18736 while (FSIndex != MaxFunctionScopesIndex) {
18738 --FSIndex;
18739 }
18740 }
18741
18742 // Capture global variables if it is required to use private copy of this
18743 // variable.
18744 bool IsGlobal = !VD->hasLocalStorage();
18745 if (IsGlobal && !(LangOpts.OpenMP &&
18746 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18747 MaxFunctionScopesIndex)))
18748 return true;
18749
18750 if (isa<VarDecl>(Var))
18751 Var = cast<VarDecl>(Var->getCanonicalDecl());
18752
18753 // Walk up the stack to determine whether we can capture the variable,
18754 // performing the "simple" checks that don't depend on type. We stop when
18755 // we've either hit the declared scope of the variable or find an existing
18756 // capture of that variable. We start from the innermost capturing-entity
18757 // (the DC) and ensure that all intervening capturing-entities
18758 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18759 // declcontext can either capture the variable or have already captured
18760 // the variable.
18761 CaptureType = Var->getType();
18762 DeclRefType = CaptureType.getNonReferenceType();
18763 bool Nested = false;
18764 bool Explicit = (Kind != TryCapture_Implicit);
18765 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18766 do {
18767
18768 LambdaScopeInfo *LSI = nullptr;
18769 if (!FunctionScopes.empty())
18770 LSI = dyn_cast_or_null<LambdaScopeInfo>(
18771 FunctionScopes[FunctionScopesIndex]);
18772
18773 bool IsInScopeDeclarationContext =
18774 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
18775
18776 if (LSI && !LSI->AfterParameterList) {
18777 // This allows capturing parameters from a default value which does not
18778 // seems correct
18779 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
18780 return true;
18781 }
18782 // If the variable is declared in the current context, there is no need to
18783 // capture it.
18784 if (IsInScopeDeclarationContext &&
18785 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
18786 return true;
18787
18788 // Only block literals, captured statements, and lambda expressions can
18789 // capture; other scopes don't work.
18790 DeclContext *ParentDC =
18791 !IsInScopeDeclarationContext
18792 ? DC->getParent()
18793 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
18794 BuildAndDiagnose, *this);
18795 // We need to check for the parent *first* because, if we *have*
18796 // private-captured a global variable, we need to recursively capture it in
18797 // intermediate blocks, lambdas, etc.
18798 if (!ParentDC) {
18799 if (IsGlobal) {
18800 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18801 break;
18802 }
18803 return true;
18804 }
18805
18806 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
18807 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18808
18809 // Check whether we've already captured it.
18810 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18811 DeclRefType)) {
18812 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18813 break;
18814 }
18815
18816 // When evaluating some attributes (like enable_if) we might refer to a
18817 // function parameter appertaining to the same declaration as that
18818 // attribute.
18819 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
18820 Parm && Parm->getDeclContext() == DC)
18821 return true;
18822
18823 // If we are instantiating a generic lambda call operator body,
18824 // we do not want to capture new variables. What was captured
18825 // during either a lambdas transformation or initial parsing
18826 // should be used.
18828 if (BuildAndDiagnose) {
18829 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18831 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18832 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18833 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18834 buildLambdaCaptureFixit(*this, LSI, Var);
18835 } else
18837 }
18838 return true;
18839 }
18840
18841 // Try to capture variable-length arrays types.
18842 if (Var->getType()->isVariablyModifiedType()) {
18843 // We're going to walk down into the type and look for VLA
18844 // expressions.
18845 QualType QTy = Var->getType();
18846 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18847 QTy = PVD->getOriginalType();
18849 }
18850
18851 if (getLangOpts().OpenMP) {
18852 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18853 // OpenMP private variables should not be captured in outer scope, so
18854 // just break here. Similarly, global variables that are captured in a
18855 // target region should not be captured outside the scope of the region.
18856 if (RSI->CapRegionKind == CR_OpenMP) {
18857 // FIXME: We should support capturing structured bindings in OpenMP.
18858 if (isa<BindingDecl>(Var)) {
18859 if (BuildAndDiagnose) {
18860 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
18861 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18862 }
18863 return true;
18864 }
18865 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
18866 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18867 // If the variable is private (i.e. not captured) and has variably
18868 // modified type, we still need to capture the type for correct
18869 // codegen in all regions, associated with the construct. Currently,
18870 // it is captured in the innermost captured region only.
18871 if (IsOpenMPPrivateDecl != OMPC_unknown &&
18872 Var->getType()->isVariablyModifiedType()) {
18873 QualType QTy = Var->getType();
18874 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18875 QTy = PVD->getOriginalType();
18876 for (int I = 1,
18877 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
18878 I < E; ++I) {
18879 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18880 FunctionScopes[FunctionScopesIndex - I]);
18881 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
18882 "Wrong number of captured regions associated with the "
18883 "OpenMP construct.");
18884 captureVariablyModifiedType(Context, QTy, OuterRSI);
18885 }
18886 }
18887 bool IsTargetCap =
18888 IsOpenMPPrivateDecl != OMPC_private &&
18889 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18890 RSI->OpenMPCaptureLevel);
18891 // Do not capture global if it is not privatized in outer regions.
18892 bool IsGlobalCap =
18893 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
18894 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18895
18896 // When we detect target captures we are looking from inside the
18897 // target region, therefore we need to propagate the capture from the
18898 // enclosing region. Therefore, the capture is not initially nested.
18899 if (IsTargetCap)
18900 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
18901 RSI->OpenMPLevel);
18902
18903 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18904 (IsGlobal && !IsGlobalCap)) {
18905 Nested = !IsTargetCap;
18906 bool HasConst = DeclRefType.isConstQualified();
18907 DeclRefType = DeclRefType.getUnqualifiedType();
18908 // Don't lose diagnostics about assignments to const.
18909 if (HasConst)
18910 DeclRefType.addConst();
18911 CaptureType = Context.getLValueReferenceType(DeclRefType);
18912 break;
18913 }
18914 }
18915 }
18916 }
18917 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18918 // No capture-default, and this is not an explicit capture
18919 // so cannot capture this variable.
18920 if (BuildAndDiagnose) {
18921 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18922 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18923 auto *LSI = cast<LambdaScopeInfo>(CSI);
18924 if (LSI->Lambda) {
18925 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18926 buildLambdaCaptureFixit(*this, LSI, Var);
18927 }
18928 // FIXME: If we error out because an outer lambda can not implicitly
18929 // capture a variable that an inner lambda explicitly captures, we
18930 // should have the inner lambda do the explicit capture - because
18931 // it makes for cleaner diagnostics later. This would purely be done
18932 // so that the diagnostic does not misleadingly claim that a variable
18933 // can not be captured by a lambda implicitly even though it is captured
18934 // explicitly. Suggestion:
18935 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18936 // at the function head
18937 // - cache the StartingDeclContext - this must be a lambda
18938 // - captureInLambda in the innermost lambda the variable.
18939 }
18940 return true;
18941 }
18942 Explicit = false;
18943 FunctionScopesIndex--;
18944 if (IsInScopeDeclarationContext)
18945 DC = ParentDC;
18946 } while (!VarDC->Equals(DC));
18947
18948 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18949 // computing the type of the capture at each step, checking type-specific
18950 // requirements, and adding captures if requested.
18951 // If the variable had already been captured previously, we start capturing
18952 // at the lambda nested within that one.
18953 bool Invalid = false;
18954 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18955 ++I) {
18956 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18957
18958 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18959 // certain types of variables (unnamed, variably modified types etc.)
18960 // so check for eligibility.
18961 if (!Invalid)
18962 Invalid =
18963 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18964
18965 // After encountering an error, if we're actually supposed to capture, keep
18966 // capturing in nested contexts to suppress any follow-on diagnostics.
18967 if (Invalid && !BuildAndDiagnose)
18968 return true;
18969
18970 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18971 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18972 DeclRefType, Nested, *this, Invalid);
18973 Nested = true;
18974 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18976 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18977 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18978 Nested = true;
18979 } else {
18980 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18981 Invalid =
18982 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18983 DeclRefType, Nested, Kind, EllipsisLoc,
18984 /*IsTopScope*/ I == N - 1, *this, Invalid);
18985 Nested = true;
18986 }
18987
18988 if (Invalid && !BuildAndDiagnose)
18989 return true;
18990 }
18991 return Invalid;
18992}
18993
18995 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18996 QualType CaptureType;
18997 QualType DeclRefType;
18998 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18999 /*BuildAndDiagnose=*/true, CaptureType,
19000 DeclRefType, nullptr);
19001}
19002
19004 QualType CaptureType;
19005 QualType DeclRefType;
19007 /*BuildAndDiagnose=*/false, CaptureType,
19008 DeclRefType, nullptr);
19009}
19010
19012 QualType CaptureType;
19013 QualType DeclRefType;
19014
19015 // Determine whether we can capture this variable.
19017 /*BuildAndDiagnose=*/false, CaptureType,
19018 DeclRefType, nullptr))
19019 return QualType();
19020
19021 return DeclRefType;
19022}
19023
19024namespace {
19025// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19026// The produced TemplateArgumentListInfo* points to data stored within this
19027// object, so should only be used in contexts where the pointer will not be
19028// used after the CopiedTemplateArgs object is destroyed.
19029class CopiedTemplateArgs {
19030 bool HasArgs;
19031 TemplateArgumentListInfo TemplateArgStorage;
19032public:
19033 template<typename RefExpr>
19034 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19035 if (HasArgs)
19036 E->copyTemplateArgumentsInto(TemplateArgStorage);
19037 }
19038 operator TemplateArgumentListInfo*()
19039#ifdef __has_cpp_attribute
19040#if __has_cpp_attribute(clang::lifetimebound)
19041 [[clang::lifetimebound]]
19042#endif
19043#endif
19044 {
19045 return HasArgs ? &TemplateArgStorage : nullptr;
19046 }
19047};
19048}
19049
19050/// Walk the set of potential results of an expression and mark them all as
19051/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19052///
19053/// \return A new expression if we found any potential results, ExprEmpty() if
19054/// not, and ExprError() if we diagnosed an error.
19056 NonOdrUseReason NOUR) {
19057 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19058 // an object that satisfies the requirements for appearing in a
19059 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19060 // is immediately applied." This function handles the lvalue-to-rvalue
19061 // conversion part.
19062 //
19063 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19064 // transform it into the relevant kind of non-odr-use node and rebuild the
19065 // tree of nodes leading to it.
19066 //
19067 // This is a mini-TreeTransform that only transforms a restricted subset of
19068 // nodes (and only certain operands of them).
19069
19070 // Rebuild a subexpression.
19071 auto Rebuild = [&](Expr *Sub) {
19072 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19073 };
19074
19075 // Check whether a potential result satisfies the requirements of NOUR.
19076 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19077 // Any entity other than a VarDecl is always odr-used whenever it's named
19078 // in a potentially-evaluated expression.
19079 auto *VD = dyn_cast<VarDecl>(D);
19080 if (!VD)
19081 return true;
19082
19083 // C++2a [basic.def.odr]p4:
19084 // A variable x whose name appears as a potentially-evalauted expression
19085 // e is odr-used by e unless
19086 // -- x is a reference that is usable in constant expressions, or
19087 // -- x is a variable of non-reference type that is usable in constant
19088 // expressions and has no mutable subobjects, and e is an element of
19089 // the set of potential results of an expression of
19090 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19091 // conversion is applied, or
19092 // -- x is a variable of non-reference type, and e is an element of the
19093 // set of potential results of a discarded-value expression to which
19094 // the lvalue-to-rvalue conversion is not applied
19095 //
19096 // We check the first bullet and the "potentially-evaluated" condition in
19097 // BuildDeclRefExpr. We check the type requirements in the second bullet
19098 // in CheckLValueToRValueConversionOperand below.
19099 switch (NOUR) {
19100 case NOUR_None:
19101 case NOUR_Unevaluated:
19102 llvm_unreachable("unexpected non-odr-use-reason");
19103
19104 case NOUR_Constant:
19105 // Constant references were handled when they were built.
19106 if (VD->getType()->isReferenceType())
19107 return true;
19108 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19109 if (RD->hasMutableFields())
19110 return true;
19111 if (!VD->isUsableInConstantExpressions(S.Context))
19112 return true;
19113 break;
19114
19115 case NOUR_Discarded:
19116 if (VD->getType()->isReferenceType())
19117 return true;
19118 break;
19119 }
19120 return false;
19121 };
19122
19123 // Mark that this expression does not constitute an odr-use.
19124 auto MarkNotOdrUsed = [&] {
19125 S.MaybeODRUseExprs.remove(E);
19126 if (LambdaScopeInfo *LSI = S.getCurLambda())
19127 LSI->markVariableExprAsNonODRUsed(E);
19128 };
19129
19130 // C++2a [basic.def.odr]p2:
19131 // The set of potential results of an expression e is defined as follows:
19132 switch (E->getStmtClass()) {
19133 // -- If e is an id-expression, ...
19134 case Expr::DeclRefExprClass: {
19135 auto *DRE = cast<DeclRefExpr>(E);
19136 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19137 break;
19138
19139 // Rebuild as a non-odr-use DeclRefExpr.
19140 MarkNotOdrUsed();
19141 return DeclRefExpr::Create(
19142 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19143 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19144 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19145 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19146 }
19147
19148 case Expr::FunctionParmPackExprClass: {
19149 auto *FPPE = cast<FunctionParmPackExpr>(E);
19150 // If any of the declarations in the pack is odr-used, then the expression
19151 // as a whole constitutes an odr-use.
19152 for (VarDecl *D : *FPPE)
19153 if (IsPotentialResultOdrUsed(D))
19154 return ExprEmpty();
19155
19156 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19157 // nothing cares about whether we marked this as an odr-use, but it might
19158 // be useful for non-compiler tools.
19159 MarkNotOdrUsed();
19160 break;
19161 }
19162
19163 // -- If e is a subscripting operation with an array operand...
19164 case Expr::ArraySubscriptExprClass: {
19165 auto *ASE = cast<ArraySubscriptExpr>(E);
19166 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19167 if (!OldBase->getType()->isArrayType())
19168 break;
19169 ExprResult Base = Rebuild(OldBase);
19170 if (!Base.isUsable())
19171 return Base;
19172 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19173 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19174 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19175 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19176 ASE->getRBracketLoc());
19177 }
19178
19179 case Expr::MemberExprClass: {
19180 auto *ME = cast<MemberExpr>(E);
19181 // -- If e is a class member access expression [...] naming a non-static
19182 // data member...
19183 if (isa<FieldDecl>(ME->getMemberDecl())) {
19184 ExprResult Base = Rebuild(ME->getBase());
19185 if (!Base.isUsable())
19186 return Base;
19187 return MemberExpr::Create(
19188 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19189 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19190 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19191 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19192 ME->getObjectKind(), ME->isNonOdrUse());
19193 }
19194
19195 if (ME->getMemberDecl()->isCXXInstanceMember())
19196 break;
19197
19198 // -- If e is a class member access expression naming a static data member,
19199 // ...
19200 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19201 break;
19202
19203 // Rebuild as a non-odr-use MemberExpr.
19204 MarkNotOdrUsed();
19205 return MemberExpr::Create(
19206 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19207 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19208 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19209 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19210 }
19211
19212 case Expr::BinaryOperatorClass: {
19213 auto *BO = cast<BinaryOperator>(E);
19214 Expr *LHS = BO->getLHS();
19215 Expr *RHS = BO->getRHS();
19216 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19217 if (BO->getOpcode() == BO_PtrMemD) {
19218 ExprResult Sub = Rebuild(LHS);
19219 if (!Sub.isUsable())
19220 return Sub;
19221 BO->setLHS(Sub.get());
19222 // -- If e is a comma expression, ...
19223 } else if (BO->getOpcode() == BO_Comma) {
19224 ExprResult Sub = Rebuild(RHS);
19225 if (!Sub.isUsable())
19226 return Sub;
19227 BO->setRHS(Sub.get());
19228 } else {
19229 break;
19230 }
19231 return ExprResult(BO);
19232 }
19233
19234 // -- If e has the form (e1)...
19235 case Expr::ParenExprClass: {
19236 auto *PE = cast<ParenExpr>(E);
19237 ExprResult Sub = Rebuild(PE->getSubExpr());
19238 if (!Sub.isUsable())
19239 return Sub;
19240 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19241 }
19242
19243 // -- If e is a glvalue conditional expression, ...
19244 // We don't apply this to a binary conditional operator. FIXME: Should we?
19245 case Expr::ConditionalOperatorClass: {
19246 auto *CO = cast<ConditionalOperator>(E);
19247 ExprResult LHS = Rebuild(CO->getLHS());
19248 if (LHS.isInvalid())
19249 return ExprError();
19250 ExprResult RHS = Rebuild(CO->getRHS());
19251 if (RHS.isInvalid())
19252 return ExprError();
19253 if (!LHS.isUsable() && !RHS.isUsable())
19254 return ExprEmpty();
19255 if (!LHS.isUsable())
19256 LHS = CO->getLHS();
19257 if (!RHS.isUsable())
19258 RHS = CO->getRHS();
19259 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19260 CO->getCond(), LHS.get(), RHS.get());
19261 }
19262
19263 // [Clang extension]
19264 // -- If e has the form __extension__ e1...
19265 case Expr::UnaryOperatorClass: {
19266 auto *UO = cast<UnaryOperator>(E);
19267 if (UO->getOpcode() != UO_Extension)
19268 break;
19269 ExprResult Sub = Rebuild(UO->getSubExpr());
19270 if (!Sub.isUsable())
19271 return Sub;
19272 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19273 Sub.get());
19274 }
19275
19276 // [Clang extension]
19277 // -- If e has the form _Generic(...), the set of potential results is the
19278 // union of the sets of potential results of the associated expressions.
19279 case Expr::GenericSelectionExprClass: {
19280 auto *GSE = cast<GenericSelectionExpr>(E);
19281
19282 SmallVector<Expr *, 4> AssocExprs;
19283 bool AnyChanged = false;
19284 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19285 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19286 if (AssocExpr.isInvalid())
19287 return ExprError();
19288 if (AssocExpr.isUsable()) {
19289 AssocExprs.push_back(AssocExpr.get());
19290 AnyChanged = true;
19291 } else {
19292 AssocExprs.push_back(OrigAssocExpr);
19293 }
19294 }
19295
19296 void *ExOrTy = nullptr;
19297 bool IsExpr = GSE->isExprPredicate();
19298 if (IsExpr)
19299 ExOrTy = GSE->getControllingExpr();
19300 else
19301 ExOrTy = GSE->getControllingType();
19302 return AnyChanged ? S.CreateGenericSelectionExpr(
19303 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19304 GSE->getRParenLoc(), IsExpr, ExOrTy,
19305 GSE->getAssocTypeSourceInfos(), AssocExprs)
19306 : ExprEmpty();
19307 }
19308
19309 // [Clang extension]
19310 // -- If e has the form __builtin_choose_expr(...), the set of potential
19311 // results is the union of the sets of potential results of the
19312 // second and third subexpressions.
19313 case Expr::ChooseExprClass: {
19314 auto *CE = cast<ChooseExpr>(E);
19315
19316 ExprResult LHS = Rebuild(CE->getLHS());
19317 if (LHS.isInvalid())
19318 return ExprError();
19319
19320 ExprResult RHS = Rebuild(CE->getLHS());
19321 if (RHS.isInvalid())
19322 return ExprError();
19323
19324 if (!LHS.get() && !RHS.get())
19325 return ExprEmpty();
19326 if (!LHS.isUsable())
19327 LHS = CE->getLHS();
19328 if (!RHS.isUsable())
19329 RHS = CE->getRHS();
19330
19331 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19332 RHS.get(), CE->getRParenLoc());
19333 }
19334
19335 // Step through non-syntactic nodes.
19336 case Expr::ConstantExprClass: {
19337 auto *CE = cast<ConstantExpr>(E);
19338 ExprResult Sub = Rebuild(CE->getSubExpr());
19339 if (!Sub.isUsable())
19340 return Sub;
19341 return ConstantExpr::Create(S.Context, Sub.get());
19342 }
19343
19344 // We could mostly rely on the recursive rebuilding to rebuild implicit
19345 // casts, but not at the top level, so rebuild them here.
19346 case Expr::ImplicitCastExprClass: {
19347 auto *ICE = cast<ImplicitCastExpr>(E);
19348 // Only step through the narrow set of cast kinds we expect to encounter.
19349 // Anything else suggests we've left the region in which potential results
19350 // can be found.
19351 switch (ICE->getCastKind()) {
19352 case CK_NoOp:
19353 case CK_DerivedToBase:
19354 case CK_UncheckedDerivedToBase: {
19355 ExprResult Sub = Rebuild(ICE->getSubExpr());
19356 if (!Sub.isUsable())
19357 return Sub;
19358 CXXCastPath Path(ICE->path());
19359 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19360 ICE->getValueKind(), &Path);
19361 }
19362
19363 default:
19364 break;
19365 }
19366 break;
19367 }
19368
19369 default:
19370 break;
19371 }
19372
19373 // Can't traverse through this node. Nothing to do.
19374 return ExprEmpty();
19375}
19376
19378 // Check whether the operand is or contains an object of non-trivial C union
19379 // type.
19380 if (E->getType().isVolatileQualified() &&
19386
19387 // C++2a [basic.def.odr]p4:
19388 // [...] an expression of non-volatile-qualified non-class type to which
19389 // the lvalue-to-rvalue conversion is applied [...]
19391 return E;
19392
19395 if (Result.isInvalid())
19396 return ExprError();
19397 return Result.get() ? Result : E;
19398}
19399
19401 Res = CorrectDelayedTyposInExpr(Res);
19402
19403 if (!Res.isUsable())
19404 return Res;
19405
19406 // If a constant-expression is a reference to a variable where we delay
19407 // deciding whether it is an odr-use, just assume we will apply the
19408 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19409 // (a non-type template argument), we have special handling anyway.
19411}
19412
19414 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19415 // call.
19416 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19417 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19418
19419 for (Expr *E : LocalMaybeODRUseExprs) {
19420 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19421 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19422 DRE->getLocation(), *this);
19423 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19424 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19425 *this);
19426 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19427 for (VarDecl *VD : *FP)
19428 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19429 } else {
19430 llvm_unreachable("Unexpected expression");
19431 }
19432 }
19433
19434 assert(MaybeODRUseExprs.empty() &&
19435 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19436}
19437
19439 ValueDecl *Var, Expr *E) {
19441 if (!VD)
19442 return;
19443
19444 const bool RefersToEnclosingScope =
19445 (SemaRef.CurContext != VD->getDeclContext() &&
19447 if (RefersToEnclosingScope) {
19448 LambdaScopeInfo *const LSI =
19449 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19450 if (LSI && (!LSI->CallOperator ||
19451 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19452 // If a variable could potentially be odr-used, defer marking it so
19453 // until we finish analyzing the full expression for any
19454 // lvalue-to-rvalue
19455 // or discarded value conversions that would obviate odr-use.
19456 // Add it to the list of potential captures that will be analyzed
19457 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19458 // unless the variable is a reference that was initialized by a constant
19459 // expression (this will never need to be captured or odr-used).
19460 //
19461 // FIXME: We can simplify this a lot after implementing P0588R1.
19462 assert(E && "Capture variable should be used in an expression.");
19463 if (!Var->getType()->isReferenceType() ||
19466 }
19467 }
19468}
19469
19472 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19473 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19474 isa<FunctionParmPackExpr>(E)) &&
19475 "Invalid Expr argument to DoMarkVarDeclReferenced");
19476 Var->setReferenced();
19477
19478 if (Var->isInvalidDecl())
19479 return;
19480
19481 auto *MSI = Var->getMemberSpecializationInfo();
19484
19485 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19486 bool UsableInConstantExpr =
19488
19489 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19490 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19491 }
19492
19493 // C++20 [expr.const]p12:
19494 // A variable [...] is needed for constant evaluation if it is [...] a
19495 // variable whose name appears as a potentially constant evaluated
19496 // expression that is either a contexpr variable or is of non-volatile
19497 // const-qualified integral type or of reference type
19498 bool NeededForConstantEvaluation =
19499 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19500
19501 bool NeedDefinition =
19502 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19503
19504 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19505 "Can't instantiate a partial template specialization.");
19506
19507 // If this might be a member specialization of a static data member, check
19508 // the specialization is visible. We already did the checks for variable
19509 // template specializations when we created them.
19510 if (NeedDefinition && TSK != TSK_Undeclared &&
19511 !isa<VarTemplateSpecializationDecl>(Var))
19513
19514 // Perform implicit instantiation of static data members, static data member
19515 // templates of class templates, and variable template specializations. Delay
19516 // instantiations of variable templates, except for those that could be used
19517 // in a constant expression.
19518 if (NeedDefinition && isTemplateInstantiation(TSK)) {
19519 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19520 // instantiation declaration if a variable is usable in a constant
19521 // expression (among other cases).
19522 bool TryInstantiating =
19524 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19525
19526 if (TryInstantiating) {
19527 SourceLocation PointOfInstantiation =
19528 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19529 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19530 if (FirstInstantiation) {
19531 PointOfInstantiation = Loc;
19532 if (MSI)
19533 MSI->setPointOfInstantiation(PointOfInstantiation);
19534 // FIXME: Notify listener.
19535 else
19536 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19537 }
19538
19539 if (UsableInConstantExpr) {
19540 // Do not defer instantiations of variables that could be used in a
19541 // constant expression.
19542 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19543 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19544 });
19545
19546 // Re-set the member to trigger a recomputation of the dependence bits
19547 // for the expression.
19548 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19549 DRE->setDecl(DRE->getDecl());
19550 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19551 ME->setMemberDecl(ME->getMemberDecl());
19552 } else if (FirstInstantiation) {
19554 .push_back(std::make_pair(Var, PointOfInstantiation));
19555 } else {
19556 bool Inserted = false;
19557 for (auto &I : SemaRef.SavedPendingInstantiations) {
19558 auto Iter = llvm::find_if(
19559 I, [Var](const Sema::PendingImplicitInstantiation &P) {
19560 return P.first == Var;
19561 });
19562 if (Iter != I.end()) {
19564 I.erase(Iter);
19565 Inserted = true;
19566 break;
19567 }
19568 }
19569
19570 // FIXME: For a specialization of a variable template, we don't
19571 // distinguish between "declaration and type implicitly instantiated"
19572 // and "implicit instantiation of definition requested", so we have
19573 // no direct way to avoid enqueueing the pending instantiation
19574 // multiple times.
19575 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
19577 .push_back(std::make_pair(Var, PointOfInstantiation));
19578 }
19579 }
19580 }
19581
19582 // C++2a [basic.def.odr]p4:
19583 // A variable x whose name appears as a potentially-evaluated expression e
19584 // is odr-used by e unless
19585 // -- x is a reference that is usable in constant expressions
19586 // -- x is a variable of non-reference type that is usable in constant
19587 // expressions and has no mutable subobjects [FIXME], and e is an
19588 // element of the set of potential results of an expression of
19589 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19590 // conversion is applied
19591 // -- x is a variable of non-reference type, and e is an element of the set
19592 // of potential results of a discarded-value expression to which the
19593 // lvalue-to-rvalue conversion is not applied [FIXME]
19594 //
19595 // We check the first part of the second bullet here, and
19596 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19597 // FIXME: To get the third bullet right, we need to delay this even for
19598 // variables that are not usable in constant expressions.
19599
19600 // If we already know this isn't an odr-use, there's nothing more to do.
19601 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19602 if (DRE->isNonOdrUse())
19603 return;
19604 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19605 if (ME->isNonOdrUse())
19606 return;
19607
19608 switch (OdrUse) {
19609 case OdrUseContext::None:
19610 // In some cases, a variable may not have been marked unevaluated, if it
19611 // appears in a defaukt initializer.
19612 assert((!E || isa<FunctionParmPackExpr>(E) ||
19614 "missing non-odr-use marking for unevaluated decl ref");
19615 break;
19616
19617 case OdrUseContext::FormallyOdrUsed:
19618 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19619 // behavior.
19620 break;
19621
19622 case OdrUseContext::Used:
19623 // If we might later find that this expression isn't actually an odr-use,
19624 // delay the marking.
19626 SemaRef.MaybeODRUseExprs.insert(E);
19627 else
19629 break;
19630
19631 case OdrUseContext::Dependent:
19632 // If this is a dependent context, we don't need to mark variables as
19633 // odr-used, but we may still need to track them for lambda capture.
19634 // FIXME: Do we also need to do this inside dependent typeid expressions
19635 // (which are modeled as unevaluated at this point)?
19637 break;
19638 }
19639}
19640
19642 BindingDecl *BD, Expr *E) {
19643 BD->setReferenced();
19644
19645 if (BD->isInvalidDecl())
19646 return;
19647
19648 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19649 if (OdrUse == OdrUseContext::Used) {
19650 QualType CaptureType, DeclRefType;
19652 /*EllipsisLoc*/ SourceLocation(),
19653 /*BuildAndDiagnose*/ true, CaptureType,
19654 DeclRefType,
19655 /*FunctionScopeIndexToStopAt*/ nullptr);
19656 } else if (OdrUse == OdrUseContext::Dependent) {
19658 }
19659}
19660
19662 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19663}
19664
19665// C++ [temp.dep.expr]p3:
19666// An id-expression is type-dependent if it contains:
19667// - an identifier associated by name lookup with an entity captured by copy
19668// in a lambda-expression that has an explicit object parameter whose type
19669// is dependent ([dcl.fct]),
19671 Sema &SemaRef, ValueDecl *D, Expr *E) {
19672 auto *ID = dyn_cast<DeclRefExpr>(E);
19673 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
19674 return;
19675
19676 // If any enclosing lambda with a dependent explicit object parameter either
19677 // explicitly captures the variable by value, or has a capture default of '='
19678 // and does not capture the variable by reference, then the type of the DRE
19679 // is dependent on the type of that lambda's explicit object parameter.
19680 auto IsDependent = [&]() {
19681 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
19682 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
19683 if (!LSI)
19684 continue;
19685
19686 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
19687 LSI->AfterParameterList)
19688 return false;
19689
19690 const auto *MD = LSI->CallOperator;
19691 if (MD->getType().isNull())
19692 continue;
19693
19694 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
19695 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
19696 !Ty->getParamType(0)->isDependentType())
19697 continue;
19698
19699 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
19700 if (C->isCopyCapture())
19701 return true;
19702 continue;
19703 }
19704
19705 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
19706 return true;
19707 }
19708 return false;
19709 }();
19710
19711 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
19712 IsDependent, SemaRef.getASTContext());
19713}
19714
19715static void
19717 bool MightBeOdrUse,
19718 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19721
19722 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19724 if (SemaRef.getLangOpts().CPlusPlus)
19726 Var, E);
19727 return;
19728 }
19729
19730 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
19732 if (SemaRef.getLangOpts().CPlusPlus)
19734 Decl, E);
19735 return;
19736 }
19737 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19738
19739 // If this is a call to a method via a cast, also mark the method in the
19740 // derived class used in case codegen can devirtualize the call.
19741 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19742 if (!ME)
19743 return;
19744 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19745 if (!MD)
19746 return;
19747 // Only attempt to devirtualize if this is truly a virtual call.
19748 bool IsVirtualCall = MD->isVirtual() &&
19750 if (!IsVirtualCall)
19751 return;
19752
19753 // If it's possible to devirtualize the call, mark the called function
19754 // referenced.
19756 ME->getBase(), SemaRef.getLangOpts().AppleKext);
19757 if (DM)
19758 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19759}
19760
19762 // TODO: update this with DR# once a defect report is filed.
19763 // C++11 defect. The address of a pure member should not be an ODR use, even
19764 // if it's a qualified reference.
19765 bool OdrUse = true;
19766 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19767 if (Method->isVirtual() &&
19768 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19769 OdrUse = false;
19770
19771 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
19775 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
19776 !FD->isDependentContext())
19777 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19778 }
19779 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19781}
19782
19784 // C++11 [basic.def.odr]p2:
19785 // A non-overloaded function whose name appears as a potentially-evaluated
19786 // expression or a member of a set of candidate functions, if selected by
19787 // overload resolution when referred to from a potentially-evaluated
19788 // expression, is odr-used, unless it is a pure virtual function and its
19789 // name is not explicitly qualified.
19790 bool MightBeOdrUse = true;
19791 if (E->performsVirtualDispatch(getLangOpts())) {
19792 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
19793 if (Method->isPureVirtual())
19794 MightBeOdrUse = false;
19795 }
19797 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19798 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19800}
19801
19803 for (VarDecl *VD : *E)
19804 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19806}
19807
19808/// Perform marking for a reference to an arbitrary declaration. It
19809/// marks the declaration referenced, and performs odr-use checking for
19810/// functions and variables. This method should not be used when building a
19811/// normal expression which refers to a variable.
19813 bool MightBeOdrUse) {
19814 if (MightBeOdrUse) {
19815 if (auto *VD = dyn_cast<VarDecl>(D)) {
19817 return;
19818 }
19819 }
19820 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19821 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19822 return;
19823 }
19824 D->setReferenced();
19825}
19826
19827namespace {
19828 // Mark all of the declarations used by a type as referenced.
19829 // FIXME: Not fully implemented yet! We need to have a better understanding
19830 // of when we're entering a context we should not recurse into.
19831 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19832 // TreeTransforms rebuilding the type in a new context. Rather than
19833 // duplicating the TreeTransform logic, we should consider reusing it here.
19834 // Currently that causes problems when rebuilding LambdaExprs.
19835 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19836 Sema &S;
19838
19839 public:
19841
19842 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19843
19844 bool TraverseTemplateArgument(const TemplateArgument &Arg);
19845 };
19846}
19847
19848bool MarkReferencedDecls::TraverseTemplateArgument(
19849 const TemplateArgument &Arg) {
19850 {
19851 // A non-type template argument is a constant-evaluated context.
19855 if (Decl *D = Arg.getAsDecl())
19856 S.MarkAnyDeclReferenced(Loc, D, true);
19857 } else if (Arg.getKind() == TemplateArgument::Expression) {
19859 }
19860 }
19861
19862 return Inherited::TraverseTemplateArgument(Arg);
19863}
19864
19866 MarkReferencedDecls Marker(*this, Loc);
19867 Marker.TraverseType(T);
19868}
19869
19870namespace {
19871/// Helper class that marks all of the declarations referenced by
19872/// potentially-evaluated subexpressions as "referenced".
19873class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19874public:
19875 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19876 bool SkipLocalVariables;
19878
19879 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
19881 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
19882
19883 void visitUsedDecl(SourceLocation Loc, Decl *D) {
19884 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
19885 }
19886
19887 void Visit(Expr *E) {
19888 if (llvm::is_contained(StopAt, E))
19889 return;
19890 Inherited::Visit(E);
19891 }
19892
19893 void VisitConstantExpr(ConstantExpr *E) {
19894 // Don't mark declarations within a ConstantExpression, as this expression
19895 // will be evaluated and folded to a value.
19896 }
19897
19898 void VisitDeclRefExpr(DeclRefExpr *E) {
19899 // If we were asked not to visit local variables, don't.
19900 if (SkipLocalVariables) {
19901 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
19902 if (VD->hasLocalStorage())
19903 return;
19904 }
19905
19906 // FIXME: This can trigger the instantiation of the initializer of a
19907 // variable, which can cause the expression to become value-dependent
19908 // or error-dependent. Do we need to propagate the new dependence bits?
19910 }
19911
19912 void VisitMemberExpr(MemberExpr *E) {
19914 Visit(E->getBase());
19915 }
19916};
19917} // namespace
19918
19920 bool SkipLocalVariables,
19921 ArrayRef<const Expr*> StopAt) {
19922 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
19923}
19924
19925/// Emit a diagnostic when statements are reachable.
19926/// FIXME: check for reachability even in expressions for which we don't build a
19927/// CFG (eg, in the initializer of a global or in a constant expression).
19928/// For example,
19929/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
19931 const PartialDiagnostic &PD) {
19932 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
19933 if (!FunctionScopes.empty())
19934 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
19936 return true;
19937 }
19938
19939 // The initializer of a constexpr variable or of the first declaration of a
19940 // static data member is not syntactically a constant evaluated constant,
19941 // but nonetheless is always required to be a constant expression, so we
19942 // can skip diagnosing.
19943 // FIXME: Using the mangling context here is a hack.
19944 if (auto *VD = dyn_cast_or_null<VarDecl>(
19945 ExprEvalContexts.back().ManglingContextDecl)) {
19946 if (VD->isConstexpr() ||
19947 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19948 return false;
19949 // FIXME: For any other kind of variable, we should build a CFG for its
19950 // initializer and check whether the context in question is reachable.
19951 }
19952
19953 Diag(Loc, PD);
19954 return true;
19955}
19956
19957/// Emit a diagnostic that describes an effect on the run-time behavior
19958/// of the program being compiled.
19959///
19960/// This routine emits the given diagnostic when the code currently being
19961/// type-checked is "potentially evaluated", meaning that there is a
19962/// possibility that the code will actually be executable. Code in sizeof()
19963/// expressions, code used only during overload resolution, etc., are not
19964/// potentially evaluated. This routine will suppress such diagnostics or,
19965/// in the absolutely nutty case of potentially potentially evaluated
19966/// expressions (C++ typeid), queue the diagnostic to potentially emit it
19967/// later.
19968///
19969/// This routine should be used for all diagnostics that describe the run-time
19970/// behavior of a program, such as passing a non-POD value through an ellipsis.
19971/// Failure to do so will likely result in spurious diagnostics or failures
19972/// during overload resolution or within sizeof/alignof/typeof/typeid.
19974 const PartialDiagnostic &PD) {
19975
19976 if (ExprEvalContexts.back().isDiscardedStatementContext())
19977 return false;
19978
19979 switch (ExprEvalContexts.back().Context) {
19984 // The argument will never be evaluated, so don't complain.
19985 break;
19986
19989 // Relevant diagnostics should be produced by constant evaluation.
19990 break;
19991
19994 return DiagIfReachable(Loc, Stmts, PD);
19995 }
19996
19997 return false;
19998}
19999
20001 const PartialDiagnostic &PD) {
20002 return DiagRuntimeBehavior(
20003 Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
20004}
20005
20007 CallExpr *CE, FunctionDecl *FD) {
20008 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20009 return false;
20010
20011 // If we're inside a decltype's expression, don't check for a valid return
20012 // type or construct temporaries until we know whether this is the last call.
20013 if (ExprEvalContexts.back().ExprContext ==
20015 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20016 return false;
20017 }
20018
20019 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20020 FunctionDecl *FD;
20021 CallExpr *CE;
20022
20023 public:
20024 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20025 : FD(FD), CE(CE) { }
20026
20027 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20028 if (!FD) {
20029 S.Diag(Loc, diag::err_call_incomplete_return)
20030 << T << CE->getSourceRange();
20031 return;
20032 }
20033
20034 S.Diag(Loc, diag::err_call_function_incomplete_return)
20035 << CE->getSourceRange() << FD << T;
20036 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20037 << FD->getDeclName();
20038 }
20039 } Diagnoser(FD, CE);
20040
20041 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20042 return true;
20043
20044 return false;
20045}
20046
20047// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20048// will prevent this condition from triggering, which is what we want.
20051
20052 unsigned diagnostic = diag::warn_condition_is_assignment;
20053 bool IsOrAssign = false;
20054
20055 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20056 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20057 return;
20058
20059 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20060
20061 // Greylist some idioms by putting them into a warning subcategory.
20062 if (ObjCMessageExpr *ME
20063 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20064 Selector Sel = ME->getSelector();
20065
20066 // self = [<foo> init...]
20067 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20068 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20069
20070 // <foo> = [<bar> nextObject]
20071 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20072 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20073 }
20074
20075 Loc = Op->getOperatorLoc();
20076 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20077 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20078 return;
20079
20080 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20081 Loc = Op->getOperatorLoc();
20082 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20083 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20084 else {
20085 // Not an assignment.
20086 return;
20087 }
20088
20089 Diag(Loc, diagnostic) << E->getSourceRange();
20090
20093 Diag(Loc, diag::note_condition_assign_silence)
20095 << FixItHint::CreateInsertion(Close, ")");
20096
20097 if (IsOrAssign)
20098 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20100 else
20101 Diag(Loc, diag::note_condition_assign_to_comparison)
20103}
20104
20106 // Don't warn if the parens came from a macro.
20107 SourceLocation parenLoc = ParenE->getBeginLoc();
20108 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20109 return;
20110 // Don't warn for dependent expressions.
20111 if (ParenE->isTypeDependent())
20112 return;
20113
20114 Expr *E = ParenE->IgnoreParens();
20115
20116 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20117 if (opE->getOpcode() == BO_EQ &&
20118 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20119 == Expr::MLV_Valid) {
20120 SourceLocation Loc = opE->getOperatorLoc();
20121
20122 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20123 SourceRange ParenERange = ParenE->getSourceRange();
20124 Diag(Loc, diag::note_equality_comparison_silence)
20125 << FixItHint::CreateRemoval(ParenERange.getBegin())
20126 << FixItHint::CreateRemoval(ParenERange.getEnd());
20127 Diag(Loc, diag::note_equality_comparison_to_assign)
20129 }
20130}
20131
20133 bool IsConstexpr) {
20135 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20137
20139 if (result.isInvalid()) return ExprError();
20140 E = result.get();
20141
20142 if (!E->isTypeDependent()) {
20143 if (getLangOpts().CPlusPlus)
20144 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20145
20147 if (ERes.isInvalid())
20148 return ExprError();
20149 E = ERes.get();
20150
20151 QualType T = E->getType();
20152 if (!T->isScalarType()) { // C99 6.8.4.1p1
20153 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20154 << T << E->getSourceRange();
20155 return ExprError();
20156 }
20157 CheckBoolLikeConversion(E, Loc);
20158 }
20159
20160 return E;
20161}
20162
20164 Expr *SubExpr, ConditionKind CK,
20165 bool MissingOK) {
20166 // MissingOK indicates whether having no condition expression is valid
20167 // (for loop) or invalid (e.g. while loop).
20168 if (!SubExpr)
20169 return MissingOK ? ConditionResult() : ConditionError();
20170
20171 ExprResult Cond;
20172 switch (CK) {
20174 Cond = CheckBooleanCondition(Loc, SubExpr);
20175 break;
20176
20178 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20179 break;
20180
20182 Cond = CheckSwitchCondition(Loc, SubExpr);
20183 break;
20184 }
20185 if (Cond.isInvalid()) {
20186 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20187 {SubExpr}, PreferredConditionType(CK));
20188 if (!Cond.get())
20189 return ConditionError();
20190 }
20191 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20193 if (!FullExpr.get())
20194 return ConditionError();
20195
20196 return ConditionResult(*this, nullptr, FullExpr,
20198}
20199
20200namespace {
20201 /// A visitor for rebuilding a call to an __unknown_any expression
20202 /// to have an appropriate type.
20203 struct RebuildUnknownAnyFunction
20204 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20205
20206 Sema &S;
20207
20208 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20209
20210 ExprResult VisitStmt(Stmt *S) {
20211 llvm_unreachable("unexpected statement!");
20212 }
20213
20214 ExprResult VisitExpr(Expr *E) {
20215 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20216 << E->getSourceRange();
20217 return ExprError();
20218 }
20219
20220 /// Rebuild an expression which simply semantically wraps another
20221 /// expression which it shares the type and value kind of.
20222 template <class T> ExprResult rebuildSugarExpr(T *E) {
20223 ExprResult SubResult = Visit(E->getSubExpr());
20224 if (SubResult.isInvalid()) return ExprError();
20225
20226 Expr *SubExpr = SubResult.get();
20227 E->setSubExpr(SubExpr);
20228 E->setType(SubExpr->getType());
20229 E->setValueKind(SubExpr->getValueKind());
20230 assert(E->getObjectKind() == OK_Ordinary);
20231 return E;
20232 }
20233
20234 ExprResult VisitParenExpr(ParenExpr *E) {
20235 return rebuildSugarExpr(E);
20236 }
20237
20238 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20239 return rebuildSugarExpr(E);
20240 }
20241
20242 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20243 ExprResult SubResult = Visit(E->getSubExpr());
20244 if (SubResult.isInvalid()) return ExprError();
20245
20246 Expr *SubExpr = SubResult.get();
20247 E->setSubExpr(SubExpr);
20248 E->setType(S.Context.getPointerType(SubExpr->getType()));
20249 assert(E->isPRValue());
20250 assert(E->getObjectKind() == OK_Ordinary);
20251 return E;
20252 }
20253
20254 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20255 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20256
20257 E->setType(VD->getType());
20258
20259 assert(E->isPRValue());
20260 if (S.getLangOpts().CPlusPlus &&
20261 !(isa<CXXMethodDecl>(VD) &&
20262 cast<CXXMethodDecl>(VD)->isInstance()))
20264
20265 return E;
20266 }
20267
20268 ExprResult VisitMemberExpr(MemberExpr *E) {
20269 return resolveDecl(E, E->getMemberDecl());
20270 }
20271
20272 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20273 return resolveDecl(E, E->getDecl());
20274 }
20275 };
20276}
20277
20278/// Given a function expression of unknown-any type, try to rebuild it
20279/// to have a function type.
20281 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20282 if (Result.isInvalid()) return ExprError();
20283 return S.DefaultFunctionArrayConversion(Result.get());
20284}
20285
20286namespace {
20287 /// A visitor for rebuilding an expression of type __unknown_anytype
20288 /// into one which resolves the type directly on the referring
20289 /// expression. Strict preservation of the original source
20290 /// structure is not a goal.
20291 struct RebuildUnknownAnyExpr
20292 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20293
20294 Sema &S;
20295
20296 /// The current destination type.
20297 QualType DestType;
20298
20299 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20300 : S(S), DestType(CastType) {}
20301
20302 ExprResult VisitStmt(Stmt *S) {
20303 llvm_unreachable("unexpected statement!");
20304 }
20305
20306 ExprResult VisitExpr(Expr *E) {
20307 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20308 << E->getSourceRange();
20309 return ExprError();
20310 }
20311
20312 ExprResult VisitCallExpr(CallExpr *E);
20313 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20314
20315 /// Rebuild an expression which simply semantically wraps another
20316 /// expression which it shares the type and value kind of.
20317 template <class T> ExprResult rebuildSugarExpr(T *E) {
20318 ExprResult SubResult = Visit(E->getSubExpr());
20319 if (SubResult.isInvalid()) return ExprError();
20320 Expr *SubExpr = SubResult.get();
20321 E->setSubExpr(SubExpr);
20322 E->setType(SubExpr->getType());
20323 E->setValueKind(SubExpr->getValueKind());
20324 assert(E->getObjectKind() == OK_Ordinary);
20325 return E;
20326 }
20327
20328 ExprResult VisitParenExpr(ParenExpr *E) {
20329 return rebuildSugarExpr(E);
20330 }
20331
20332 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20333 return rebuildSugarExpr(E);
20334 }
20335
20336 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20337 const PointerType *Ptr = DestType->getAs<PointerType>();
20338 if (!Ptr) {
20339 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20340 << E->getSourceRange();
20341 return ExprError();
20342 }
20343
20344 if (isa<CallExpr>(E->getSubExpr())) {
20345 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20346 << E->getSourceRange();
20347 return ExprError();
20348 }
20349
20350 assert(E->isPRValue());
20351 assert(E->getObjectKind() == OK_Ordinary);
20352 E->setType(DestType);
20353
20354 // Build the sub-expression as if it were an object of the pointee type.
20355 DestType = Ptr->getPointeeType();
20356 ExprResult SubResult = Visit(E->getSubExpr());
20357 if (SubResult.isInvalid()) return ExprError();
20358 E->setSubExpr(SubResult.get());
20359 return E;
20360 }
20361
20362 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20363
20364 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20365
20366 ExprResult VisitMemberExpr(MemberExpr *E) {
20367 return resolveDecl(E, E->getMemberDecl());
20368 }
20369
20370 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20371 return resolveDecl(E, E->getDecl());
20372 }
20373 };
20374}
20375
20376/// Rebuilds a call expression which yielded __unknown_anytype.
20377ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20378 Expr *CalleeExpr = E->getCallee();
20379
20380 enum FnKind {
20381 FK_MemberFunction,
20382 FK_FunctionPointer,
20383 FK_BlockPointer
20384 };
20385
20386 FnKind Kind;
20387 QualType CalleeType = CalleeExpr->getType();
20388 if (CalleeType == S.Context.BoundMemberTy) {
20389 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20390 Kind = FK_MemberFunction;
20391 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20392 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20393 CalleeType = Ptr->getPointeeType();
20394 Kind = FK_FunctionPointer;
20395 } else {
20396 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20397 Kind = FK_BlockPointer;
20398 }
20399 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20400
20401 // Verify that this is a legal result type of a function.
20402 if (DestType->isArrayType() || DestType->isFunctionType()) {
20403 unsigned diagID = diag::err_func_returning_array_function;
20404 if (Kind == FK_BlockPointer)
20405 diagID = diag::err_block_returning_array_function;
20406
20407 S.Diag(E->getExprLoc(), diagID)
20408 << DestType->isFunctionType() << DestType;
20409 return ExprError();
20410 }
20411
20412 // Otherwise, go ahead and set DestType as the call's result.
20413 E->setType(DestType.getNonLValueExprType(S.Context));
20415 assert(E->getObjectKind() == OK_Ordinary);
20416
20417 // Rebuild the function type, replacing the result type with DestType.
20418 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20419 if (Proto) {
20420 // __unknown_anytype(...) is a special case used by the debugger when
20421 // it has no idea what a function's signature is.
20422 //
20423 // We want to build this call essentially under the K&R
20424 // unprototyped rules, but making a FunctionNoProtoType in C++
20425 // would foul up all sorts of assumptions. However, we cannot
20426 // simply pass all arguments as variadic arguments, nor can we
20427 // portably just call the function under a non-variadic type; see
20428 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20429 // However, it turns out that in practice it is generally safe to
20430 // call a function declared as "A foo(B,C,D);" under the prototype
20431 // "A foo(B,C,D,...);". The only known exception is with the
20432 // Windows ABI, where any variadic function is implicitly cdecl
20433 // regardless of its normal CC. Therefore we change the parameter
20434 // types to match the types of the arguments.
20435 //
20436 // This is a hack, but it is far superior to moving the
20437 // corresponding target-specific code from IR-gen to Sema/AST.
20438
20439 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20440 SmallVector<QualType, 8> ArgTypes;
20441 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20442 ArgTypes.reserve(E->getNumArgs());
20443 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20444 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20445 }
20446 ParamTypes = ArgTypes;
20447 }
20448 DestType = S.Context.getFunctionType(DestType, ParamTypes,
20449 Proto->getExtProtoInfo());
20450 } else {
20451 DestType = S.Context.getFunctionNoProtoType(DestType,
20452 FnType->getExtInfo());
20453 }
20454
20455 // Rebuild the appropriate pointer-to-function type.
20456 switch (Kind) {
20457 case FK_MemberFunction:
20458 // Nothing to do.
20459 break;
20460
20461 case FK_FunctionPointer:
20462 DestType = S.Context.getPointerType(DestType);
20463 break;
20464
20465 case FK_BlockPointer:
20466 DestType = S.Context.getBlockPointerType(DestType);
20467 break;
20468 }
20469
20470 // Finally, we can recurse.
20471 ExprResult CalleeResult = Visit(CalleeExpr);
20472 if (!CalleeResult.isUsable()) return ExprError();
20473 E->setCallee(CalleeResult.get());
20474
20475 // Bind a temporary if necessary.
20476 return S.MaybeBindToTemporary(E);
20477}
20478
20479ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20480 // Verify that this is a legal result type of a call.
20481 if (DestType->isArrayType() || DestType->isFunctionType()) {
20482 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20483 << DestType->isFunctionType() << DestType;
20484 return ExprError();
20485 }
20486
20487 // Rewrite the method result type if available.
20488 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20489 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20490 Method->setReturnType(DestType);
20491 }
20492
20493 // Change the type of the message.
20494 E->setType(DestType.getNonReferenceType());
20496
20497 return S.MaybeBindToTemporary(E);
20498}
20499
20500ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20501 // The only case we should ever see here is a function-to-pointer decay.
20502 if (E->getCastKind() == CK_FunctionToPointerDecay) {
20503 assert(E->isPRValue());
20504 assert(E->getObjectKind() == OK_Ordinary);
20505
20506 E->setType(DestType);
20507
20508 // Rebuild the sub-expression as the pointee (function) type.
20509 DestType = DestType->castAs<PointerType>()->getPointeeType();
20510
20511 ExprResult Result = Visit(E->getSubExpr());
20512 if (!Result.isUsable()) return ExprError();
20513
20514 E->setSubExpr(Result.get());
20515 return E;
20516 } else if (E->getCastKind() == CK_LValueToRValue) {
20517 assert(E->isPRValue());
20518 assert(E->getObjectKind() == OK_Ordinary);
20519
20520 assert(isa<BlockPointerType>(E->getType()));
20521
20522 E->setType(DestType);
20523
20524 // The sub-expression has to be a lvalue reference, so rebuild it as such.
20525 DestType = S.Context.getLValueReferenceType(DestType);
20526
20527 ExprResult Result = Visit(E->getSubExpr());
20528 if (!Result.isUsable()) return ExprError();
20529
20530 E->setSubExpr(Result.get());
20531 return E;
20532 } else {
20533 llvm_unreachable("Unhandled cast type!");
20534 }
20535}
20536
20537ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20538 ExprValueKind ValueKind = VK_LValue;
20539 QualType Type = DestType;
20540
20541 // We know how to make this work for certain kinds of decls:
20542
20543 // - functions
20544 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20545 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20546 DestType = Ptr->getPointeeType();
20547 ExprResult Result = resolveDecl(E, VD);
20548 if (Result.isInvalid()) return ExprError();
20549 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20550 VK_PRValue);
20551 }
20552
20553 if (!Type->isFunctionType()) {
20554 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20555 << VD << E->getSourceRange();
20556 return ExprError();
20557 }
20558 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20559 // We must match the FunctionDecl's type to the hack introduced in
20560 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20561 // type. See the lengthy commentary in that routine.
20562 QualType FDT = FD->getType();
20563 const FunctionType *FnType = FDT->castAs<FunctionType>();
20564 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20565 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20566 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20567 SourceLocation Loc = FD->getLocation();
20569 S.Context, FD->getDeclContext(), Loc, Loc,
20570 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20572 false /*isInlineSpecified*/, FD->hasPrototype(),
20573 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20574
20575 if (FD->getQualifier())
20576 NewFD->setQualifierInfo(FD->getQualifierLoc());
20577
20579 for (const auto &AI : FT->param_types()) {
20580 ParmVarDecl *Param =
20582 Param->setScopeInfo(0, Params.size());
20583 Params.push_back(Param);
20584 }
20585 NewFD->setParams(Params);
20586 DRE->setDecl(NewFD);
20587 VD = DRE->getDecl();
20588 }
20589 }
20590
20591 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20592 if (MD->isInstance()) {
20593 ValueKind = VK_PRValue;
20595 }
20596
20597 // Function references aren't l-values in C.
20598 if (!S.getLangOpts().CPlusPlus)
20599 ValueKind = VK_PRValue;
20600
20601 // - variables
20602 } else if (isa<VarDecl>(VD)) {
20603 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20604 Type = RefTy->getPointeeType();
20605 } else if (Type->isFunctionType()) {
20606 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20607 << VD << E->getSourceRange();
20608 return ExprError();
20609 }
20610
20611 // - nothing else
20612 } else {
20613 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20614 << VD << E->getSourceRange();
20615 return ExprError();
20616 }
20617
20618 // Modifying the declaration like this is friendly to IR-gen but
20619 // also really dangerous.
20620 VD->setType(DestType);
20621 E->setType(Type);
20622 E->setValueKind(ValueKind);
20623 return E;
20624}
20625
20629 // The type we're casting to must be either void or complete.
20630 if (!CastType->isVoidType() &&
20632 diag::err_typecheck_cast_to_incomplete))
20633 return ExprError();
20634
20635 // Rewrite the casted expression from scratch.
20636 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20637 if (!result.isUsable()) return ExprError();
20638
20639 CastExpr = result.get();
20640 VK = CastExpr->getValueKind();
20641 CastKind = CK_NoOp;
20642
20643 return CastExpr;
20644}
20645
20647 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20648}
20649
20651 Expr *arg, QualType &paramType) {
20652 // If the syntactic form of the argument is not an explicit cast of
20653 // any sort, just do default argument promotion.
20654 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20655 if (!castArg) {
20657 if (result.isInvalid()) return ExprError();
20658 paramType = result.get()->getType();
20659 return result;
20660 }
20661
20662 // Otherwise, use the type that was written in the explicit cast.
20663 assert(!arg->hasPlaceholderType());
20664 paramType = castArg->getTypeAsWritten();
20665
20666 // Copy-initialize a parameter of that type.
20667 InitializedEntity entity =
20669 /*consumed*/ false);
20670 return PerformCopyInitialization(entity, callLoc, arg);
20671}
20672
20674 Expr *orig = E;
20675 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20676 while (true) {
20677 E = E->IgnoreParenImpCasts();
20678 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20679 E = call->getCallee();
20680 diagID = diag::err_uncasted_call_of_unknown_any;
20681 } else {
20682 break;
20683 }
20684 }
20685
20686 SourceLocation loc;
20687 NamedDecl *d;
20688 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20689 loc = ref->getLocation();
20690 d = ref->getDecl();
20691 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20692 loc = mem->getMemberLoc();
20693 d = mem->getMemberDecl();
20694 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20695 diagID = diag::err_uncasted_call_of_unknown_any;
20696 loc = msg->getSelectorStartLoc();
20697 d = msg->getMethodDecl();
20698 if (!d) {
20699 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20700 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20701 << orig->getSourceRange();
20702 return ExprError();
20703 }
20704 } else {
20705 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20706 << E->getSourceRange();
20707 return ExprError();
20708 }
20709
20710 S.Diag(loc, diagID) << d << orig->getSourceRange();
20711
20712 // Never recoverable.
20713 return ExprError();
20714}
20715
20718 // C cannot handle TypoExpr nodes on either side of a binop because it
20719 // doesn't handle dependent types properly, so make sure any TypoExprs have
20720 // been dealt with before checking the operands.
20722 if (!Result.isUsable()) return ExprError();
20723 E = Result.get();
20724 }
20725
20726 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20727 if (!placeholderType) return E;
20728
20729 switch (placeholderType->getKind()) {
20730 case BuiltinType::UnresolvedTemplate: {
20731 auto *ULE = cast<UnresolvedLookupExpr>(E);
20732 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
20733 // There's only one FoundDecl for UnresolvedTemplate type. See
20734 // BuildTemplateIdExpr.
20735 NamedDecl *Temp = *ULE->decls_begin();
20736 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
20737
20738 if (NestedNameSpecifierLoc Loc = ULE->getQualifierLoc(); Loc.hasQualifier())
20739 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
20740 << Loc.getNestedNameSpecifier() << NameInfo.getName().getAsString()
20741 << Loc.getSourceRange() << IsTypeAliasTemplateDecl;
20742 else
20743 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
20744 << "" << NameInfo.getName().getAsString() << ULE->getSourceRange()
20745 << IsTypeAliasTemplateDecl;
20746 Diag(Temp->getLocation(), diag::note_referenced_type_template)
20747 << IsTypeAliasTemplateDecl;
20748
20749 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
20750 }
20751
20752 // Overloaded expressions.
20753 case BuiltinType::Overload: {
20754 // Try to resolve a single function template specialization.
20755 // This is obligatory.
20758 return Result;
20759
20760 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20761 // leaves Result unchanged on failure.
20762 Result = E;
20764 return Result;
20765
20766 // If that failed, try to recover with a call.
20767 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20768 /*complain*/ true);
20769 return Result;
20770 }
20771
20772 // Bound member functions.
20773 case BuiltinType::BoundMember: {
20774 ExprResult result = E;
20775 const Expr *BME = E->IgnoreParens();
20776 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20777 // Try to give a nicer diagnostic if it is a bound member that we recognize.
20778 if (isa<CXXPseudoDestructorExpr>(BME)) {
20779 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20780 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20781 if (ME->getMemberNameInfo().getName().getNameKind() ==
20783 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20784 }
20785 tryToRecoverWithCall(result, PD,
20786 /*complain*/ true);
20787 return result;
20788 }
20789
20790 // ARC unbridged casts.
20791 case BuiltinType::ARCUnbridgedCast: {
20792 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
20793 ObjC().diagnoseARCUnbridgedCast(realCast);
20794 return realCast;
20795 }
20796
20797 // Expressions of unknown type.
20798 case BuiltinType::UnknownAny:
20799 return diagnoseUnknownAnyExpr(*this, E);
20800
20801 // Pseudo-objects.
20802 case BuiltinType::PseudoObject:
20803 return PseudoObject().checkRValue(E);
20804
20805 case BuiltinType::BuiltinFn: {
20806 // Accept __noop without parens by implicitly converting it to a call expr.
20807 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20808 if (DRE) {
20809 auto *FD = cast<FunctionDecl>(DRE->getDecl());
20810 unsigned BuiltinID = FD->getBuiltinID();
20811 if (BuiltinID == Builtin::BI__noop) {
20812 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20813 CK_BuiltinFnToFnPtr)
20814 .get();
20815 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20818 }
20819
20820 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
20821 // Any use of these other than a direct call is ill-formed as of C++20,
20822 // because they are not addressable functions. In earlier language
20823 // modes, warn and force an instantiation of the real body.
20824 Diag(E->getBeginLoc(),
20826 ? diag::err_use_of_unaddressable_function
20827 : diag::warn_cxx20_compat_use_of_unaddressable_function);
20828 if (FD->isImplicitlyInstantiable()) {
20829 // Require a definition here because a normal attempt at
20830 // instantiation for a builtin will be ignored, and we won't try
20831 // again later. We assume that the definition of the template
20832 // precedes this use.
20834 /*Recursive=*/false,
20835 /*DefinitionRequired=*/true,
20836 /*AtEndOfTU=*/false);
20837 }
20838 // Produce a properly-typed reference to the function.
20839 CXXScopeSpec SS;
20840 SS.Adopt(DRE->getQualifierLoc());
20841 TemplateArgumentListInfo TemplateArgs;
20842 DRE->copyTemplateArgumentsInto(TemplateArgs);
20843 return BuildDeclRefExpr(
20844 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
20845 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
20846 DRE->getTemplateKeywordLoc(),
20847 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
20848 }
20849 }
20850
20851 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
20852 return ExprError();
20853 }
20854
20855 case BuiltinType::IncompleteMatrixIdx:
20856 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
20857 ->getRowIdx()
20858 ->getBeginLoc(),
20859 diag::err_matrix_incomplete_index);
20860 return ExprError();
20861
20862 // Expressions of unknown type.
20863 case BuiltinType::ArraySection:
20864 Diag(E->getBeginLoc(), diag::err_array_section_use)
20865 << cast<ArraySectionExpr>(E)->isOMPArraySection();
20866 return ExprError();
20867
20868 // Expressions of unknown type.
20869 case BuiltinType::OMPArrayShaping:
20870 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
20871
20872 case BuiltinType::OMPIterator:
20873 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
20874
20875 // Everything else should be impossible.
20876#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
20877 case BuiltinType::Id:
20878#include "clang/Basic/OpenCLImageTypes.def"
20879#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
20880 case BuiltinType::Id:
20881#include "clang/Basic/OpenCLExtensionTypes.def"
20882#define SVE_TYPE(Name, Id, SingletonId) \
20883 case BuiltinType::Id:
20884#include "clang/Basic/AArch64SVEACLETypes.def"
20885#define PPC_VECTOR_TYPE(Name, Id, Size) \
20886 case BuiltinType::Id:
20887#include "clang/Basic/PPCTypes.def"
20888#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20889#include "clang/Basic/RISCVVTypes.def"
20890#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20891#include "clang/Basic/WebAssemblyReferenceTypes.def"
20892#define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20893#include "clang/Basic/AMDGPUTypes.def"
20894#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20895#include "clang/Basic/HLSLIntangibleTypes.def"
20896#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
20897#define PLACEHOLDER_TYPE(Id, SingletonId)
20898#include "clang/AST/BuiltinTypes.def"
20899 break;
20900 }
20901
20902 llvm_unreachable("invalid placeholder type!");
20903}
20904
20906 if (E->isTypeDependent())
20907 return true;
20910 return false;
20911}
20912
20914 ArrayRef<Expr *> SubExprs, QualType T) {
20915 if (!Context.getLangOpts().RecoveryAST)
20916 return ExprError();
20917
20918 if (isSFINAEContext())
20919 return ExprError();
20920
20921 if (T.isNull() || T->isUndeducedType() ||
20922 !Context.getLangOpts().RecoveryASTType)
20923 // We don't know the concrete type, fallback to dependent type.
20925
20926 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
20927}
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:9048
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
Definition: SemaExpr.cpp:17513
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:15098
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:9927
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:18451
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:10678
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:14889
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
Definition: SemaExpr.cpp:6064
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:10597
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:8618
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:8072
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:8278
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:11643
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:10642
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:11593
static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn)
Definition: SemaExpr.cpp:5734
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
Definition: SemaExpr.cpp:2219
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:14365
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:17851
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:13128
@ NCCK_Block
Definition: SemaExpr.cpp:13128
@ NCCK_None
Definition: SemaExpr.cpp:13128
@ NCCK_Lambda
Definition: SemaExpr.cpp:13128
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:9821
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:9097
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:5996
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:19670
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18303
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:16587
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:8522
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:16470
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
Definition: SemaExpr.cpp:13690
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:11995
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
Definition: SemaExpr.cpp:14265
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:8597
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
Definition: SemaExpr.cpp:17700
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:14421
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:10763
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:7915
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19470
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:7881
static bool checkForArray(const Expr *E)
Definition: SemaExpr.cpp:11685
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
Definition: SemaExpr.cpp:6339
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:13312
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19716
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:9868
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
Definition: SemaExpr.cpp:19438
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:14247
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
Definition: SemaExpr.cpp:17374
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:11870
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:8552
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:14519
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:6229
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:9485
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:8196
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:7902
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
Definition: SemaExpr.cpp:10609
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:14504
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:8824
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
Definition: SemaExpr.cpp:17416
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:14980
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:13795
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:8141
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:8250
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10436
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:11699
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:10484
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:5693
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:11132
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:8997
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:18134
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:10793
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:13376
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:13897
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:17731
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:11494
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:15037
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:13957
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:9971
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:18491
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
Definition: SemaExpr.cpp:14944
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:8652
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:17819
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:13187
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:13165
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:18251
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:10656
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:11327
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:11913
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:20673
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:8316
OriginalExprKind
Definition: SemaExpr.cpp:13306
@ OEK_Variable
Definition: SemaExpr.cpp:13307
@ OEK_LValue
Definition: SemaExpr.cpp:13309
@ OEK_Member
Definition: SemaExpr.cpp:13308
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:18383
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:10584
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:11233
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
Definition: SemaExpr.cpp:18210
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:10400
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:13115
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:18619
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:6298
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:8845
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:14965
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:10844
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:6256
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:10626
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:8111
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:11831
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
Definition: SemaExpr.cpp:12694
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:8230
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:8537
@ ConstMethod
Definition: SemaExpr.cpp:13178
@ ConstUnknown
Definition: SemaExpr.cpp:13180
@ ConstVariable
Definition: SemaExpr.cpp:13176
@ NestedConstMember
Definition: SemaExpr.cpp:13179
@ ConstMember
Definition: SemaExpr.cpp:13177
@ ConstFunction
Definition: SemaExpr.cpp:13175
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:14552
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:14463
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:20280
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:11546
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:6156
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
Definition: SemaExpr.cpp:19641
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:13759
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
Definition: SemaExpr.cpp:18593
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:10574
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:11483
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:14575
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:11533
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:13129
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:8046
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15009
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:14995
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:11523
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
Definition: SemaExpr.cpp:14932
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:9889
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18284
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:15277
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:13504
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12924
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:19055
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
Definition: SemaExpr.cpp:17765
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:11126
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:10710
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:7426
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:3571
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3585
QualType getElementType() const
Definition: Type.h:3583
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:6080
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6380
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:3402
This class is used for builtin types like 'int'.
Definition: Type.h:3028
bool isSVEBool() const
Definition: Type.h:3105
Kind getKind() const
Definition: Type.h:3076
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:3139
QualType getElementType() const
Definition: Type.h:3149
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:3609
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3665
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3685
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:4224
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4245
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4242
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:5996
EnumDecl * getDecl() const
Definition: Type.h:6003
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:4118
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:4648
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5007
QualType desugar() const
Definition: Type.h:5551
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5473
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5287
bool isParamConsumed(unsigned I) const
Definition: Type.h:5487
unsigned getNumParams() const
Definition: Type.h:5260
QualType getParamType(unsigned i) const
Definition: Type.h:5262
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5384
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5271
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5267
ArrayRef< QualType > param_types() const
Definition: Type.h:5416
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:4424
bool getCmseNSCall() const
Definition: Type.h:4474
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4498
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4313
ExtInfo getExtInfo() const
Definition: Type.h:4647
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4643
QualType getReturnType() const
Definition: Type.h:4635
bool getCmseNSCallAttr() const
Definition: Type.h:4645
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4659
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:7522
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:4188
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4202
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:7348
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:7404
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:7523
Represents a class type in Objective C.
Definition: Type.h:7150
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:2983
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3044
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:3192
QualType getPointeeType() const
Definition: Type.h:3202
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:7839
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7844
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:7902
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:7937
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:7755
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7881
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:7896
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7795
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:7956
QualType getCanonicalType() const
Definition: Type.h:7807
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7849
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:7963
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7828
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7876
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:7812
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:7787
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:7890
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:5970
RecordDecl * getDecl() const
Definition: Type.h:5980
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:3433
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:16928
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:16934
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:14386
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:13146
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:15610
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:15287
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:15060
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:19400
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13002
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:6967
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:7471
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:15629
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:17246
void ActOnStmtExprError()
Definition: SemaExpr.cpp:15635
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:12022
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:16280
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:17181
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:20132
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:12580
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:18204
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:16939
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
Definition: SemaExpr.cpp:6608
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:10063
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:7445
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:19919
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth)
Definition: SemaExpr.cpp:15648
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:16296
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:13710
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:7555
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:13990
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15047
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:9761
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:19930
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:11419
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:7820
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:20905
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:12841
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:19413
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:15566
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:18695
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:19661
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
Definition: SemaExpr.cpp:15084
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:17602
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9504
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:6131
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:6981
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:15616
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:7836
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:12887
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:15904
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:20163
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:84
@ UPPC_Block
Block expression.
Definition: Sema.h:13957
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:12049
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:7219
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12816
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:17277
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:19802
Preprocessor & PP
Definition: Sema.h:961
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:10854
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5649
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:6407
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
Definition: SemaExpr.cpp:13962
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
Definition: SemaExpr.cpp:16570
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:7460
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:15718
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:6658
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17298
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7485
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:17262
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:19812
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:9785
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:13534
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:15529
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:10322
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:9556
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:7206
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:16090
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7596
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:7466
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:20626
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, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
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:13543
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:16452
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:7842
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:19865
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:8361
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:19761
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:16537
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:20716
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17161
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:13497
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:6636
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:8704
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:12592
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:10497
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
Definition: SemaExpr.cpp:19377
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13549
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:20000
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5452
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:7490
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:7527
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:8204
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:14945
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:15071
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:7629
@ 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:12464
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:13526
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5101
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:16578
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
Definition: SemaExpr.cpp:12537
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:8330
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:6629
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:20006
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:16289
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:20646
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:19011
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:7664
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:17680
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:19003
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:7576
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:7737
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:7513
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9656
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5526
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
Definition: SemaExpr.cpp:20049
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:12938
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:15643
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:6006
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12653
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8807
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:13010
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:16100
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:19783
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:16606
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:17861
ExprResult ActOnStmtExprResult(ExprResult E)
Definition: SemaExpr.cpp:15687
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:5892
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:20105
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:20913
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15134
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:7181
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:15942
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:14599
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9082
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:6369
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:15971
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:10536
@ 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:13522
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:15688
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:13262
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:10977
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:6650
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:20650
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:5752
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:15885
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"...
bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy)
Definition: SemaCast.cpp:2704
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:17688
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7113
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:5313
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:7726
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:7737
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:2439
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:8385
bool isBlockPointerType() const
Definition: Type.h:8022
bool isVoidType() const
Definition: Type.h:8324
bool isBooleanType() const
Definition: Type.h:8452
bool isFunctionReferenceType() const
Definition: Type.h:8055
bool isObjCBuiltinType() const
Definition: Type.h:8201
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:8502
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:740
bool isIncompleteArrayType() const
Definition: Type.h:8088
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:8300
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:8482
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:8080
bool isCharType() const
Definition: Type.cpp:2089
bool isFunctionPointerType() const
Definition: Type.h:8048
bool isArithmeticType() const
Definition: Type.cpp:2281
bool isConstantMatrixType() const
Definition: Type.h:8142
bool isPointerType() const
Definition: Type.h:8008
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8364
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:8612
bool isReferenceType() const
Definition: Type.h:8026
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:8405
bool isEnumeralType() const
Definition: Type.h:8112
bool isScalarType() const
Definition: Type.h:8423
bool isVariableArrayType() const
Definition: Type.h:8092
bool isSizelessBuiltinType() const
Definition: Type.cpp:2441
bool isClkEventT() const
Definition: Type.h:8223
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:8171
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:8439
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:8124
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:8128
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:8235
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:8318
bool isPipeType() const
Definition: Type.h:8242
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2708
bool isBitIntType() const
Definition: Type.h:8246
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8293
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8104
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2700
bool isAnyComplexType() const
Definition: Type.h:8116
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8377
bool isHalfType() const
Definition: Type.h:8328
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8393
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2359
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:2296
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:8306
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:8227
bool isMemberPointerType() const
Definition: Type.h:8062
bool isAtomicType() const
Definition: Type.h:8163
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:8465
bool isObjCIdType() const
Definition: Type.h:8183
bool isMatrixType() const
Definition: Type.h:8138
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2718
bool isComplexIntegerType() const
Definition: Type.cpp:683
bool isUnscopedEnumerationType() const
Definition: Type.cpp:2082
bool isObjCObjectType() const
Definition: Type.h:8154
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:8598
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:8458
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:8004
bool isObjCObjectPointerType() const
Definition: Type.h:8150
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:8066
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:8419
bool isVectorType() const
Definition: Type.h:8120
bool isObjCQualifiedClassType() const
Definition: Type.h:8177
bool isObjCClassType() const
Definition: Type.h:8189
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:2673
@ STK_FloatingComplex
Definition: Type.h:2682
@ STK_Floating
Definition: Type.h:2680
@ STK_BlockPointer
Definition: Type.h:2675
@ STK_Bool
Definition: Type.h:2678
@ STK_ObjCObjectPointer
Definition: Type.h:2676
@ STK_FixedPoint
Definition: Type.h:2683
@ STK_IntegralComplex
Definition: Type.h:2681
@ STK_CPointer
Definition: Type.h:2674
@ STK_Integral
Definition: Type.h:2679
@ STK_MemberPointer
Definition: Type.h:2677
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:8016
bool isRealType() const
Definition: Type.cpp:2272
TypeClass getTypeClass() const
Definition: Type.h:2339
bool isSubscriptableVectorType() const
Definition: Type.h:8134
bool isSamplerT() const
Definition: Type.h:8215
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8545
bool isNullPtrType() const
Definition: Type.h:8357
bool isRecordType() const
Definition: Type.h:8108
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:3203
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:3943
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:3800
Expr * getSizeExpr() const
Definition: Type.h:3819
Represents a GCC generic vector type.
Definition: Type.h:4026
unsigned getNumElements() const
Definition: Type.h:4041
VectorKind getVectorKind() const
Definition: Type.h:4046
QualType getElementType() const
Definition: Type.h:4040
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:5443
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
Definition: SemaExpr.cpp:5440
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
Definition: SemaExpr.cpp:5427
ExprResult TransformBlockExpr(BlockExpr *E)
Definition: SemaExpr.cpp:5435
ExprResult TransformLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5434
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E)
Definition: SemaExpr.cpp:5420
bool VisitCallExpr(CallExpr *E)
Definition: SemaExpr.cpp:5385
bool VisitCXXConstructExpr(CXXConstructExpr *E)
Definition: SemaExpr.cpp:5391
const ASTContext & Context
Definition: SemaExpr.cpp:5379
bool VisitLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5412
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E)
Definition: SemaExpr.cpp:5416
bool VisitSourceLocExpr(SourceLocExpr *E)
Definition: SemaExpr.cpp:5401
bool shouldVisitImplicitCode() const
Definition: SemaExpr.cpp:5383
ImmediateCallVisitor(const ASTContext &Ctx)
Definition: SemaExpr.cpp:5380
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:5092
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5093
@ 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.