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"
31#include "clang/AST/Type.h"
32#include "clang/AST/TypeLoc.h"
43#include "clang/Sema/DeclSpec.h"
48#include "clang/Sema/Lookup.h"
49#include "clang/Sema/Overload.h"
51#include "clang/Sema/Scope.h"
53#include "clang/Sema/SemaCUDA.h"
56#include "clang/Sema/SemaObjC.h"
59#include "clang/Sema/Template.h"
60#include "llvm/ADT/STLExtras.h"
61#include "llvm/ADT/STLForwardCompat.h"
62#include "llvm/ADT/StringExtras.h"
63#include "llvm/Support/Casting.h"
64#include "llvm/Support/ConvertUTF.h"
65#include "llvm/Support/SaveAndRestore.h"
66#include "llvm/Support/TypeSize.h"
67#include <optional>
68
69using namespace clang;
70using namespace sema;
71
72bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
73 // See if this is an auto-typed variable whose initializer we are parsing.
74 if (ParsingInitForAutoVars.count(D))
75 return false;
76
77 // See if this is a deleted function.
78 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
79 if (FD->isDeleted())
80 return false;
81
82 // If the function has a deduced return type, and we can't deduce it,
83 // then we can't use it either.
84 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
85 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
86 return false;
87
88 // See if this is an aligned allocation/deallocation function that is
89 // unavailable.
90 if (TreatUnavailableAsInvalid &&
92 return false;
93 }
94
95 // See if this function is unavailable.
96 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
97 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
98 return false;
99
100 if (isa<UnresolvedUsingIfExistsDecl>(D))
101 return false;
102
103 return true;
104}
105
107 // Warn if this is used but marked unused.
108 if (const auto *A = D->getAttr<UnusedAttr>()) {
109 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
110 // should diagnose them.
111 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
112 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
113 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
114 if (DC && !DC->hasAttr<UnusedAttr>())
115 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
116 }
117 }
118}
119
121 assert(Decl && Decl->isDeleted());
122
123 if (Decl->isDefaulted()) {
124 // If the method was explicitly defaulted, point at that declaration.
125 if (!Decl->isImplicit())
126 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
127
128 // Try to diagnose why this special member function was implicitly
129 // deleted. This might fail, if that reason no longer applies.
131 return;
132 }
133
134 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
135 if (Ctor && Ctor->isInheritingConstructor())
137
138 Diag(Decl->getLocation(), diag::note_availability_specified_here)
139 << Decl << 1;
140}
141
142/// Determine whether a FunctionDecl was ever declared with an
143/// explicit storage class.
145 for (auto *I : D->redecls()) {
146 if (I->getStorageClass() != SC_None)
147 return true;
148 }
149 return false;
150}
151
152/// Check whether we're in an extern inline function and referring to a
153/// variable or function with internal linkage (C11 6.7.4p3).
154///
155/// This is only a warning because we used to silently accept this code, but
156/// in many cases it will not behave correctly. This is not enabled in C++ mode
157/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
158/// and so while there may still be user mistakes, most of the time we can't
159/// prove that there are errors.
161 const NamedDecl *D,
163 // This is disabled under C++; there are too many ways for this to fire in
164 // contexts where the warning is a false positive, or where it is technically
165 // correct but benign.
166 if (S.getLangOpts().CPlusPlus)
167 return;
168
169 // Check if this is an inlined function or method.
170 FunctionDecl *Current = S.getCurFunctionDecl();
171 if (!Current)
172 return;
173 if (!Current->isInlined())
174 return;
175 if (!Current->isExternallyVisible())
176 return;
177
178 // Check if the decl has internal linkage.
179 if (D->getFormalLinkage() != Linkage::Internal)
180 return;
181
182 // Downgrade from ExtWarn to Extension if
183 // (1) the supposedly external inline function is in the main file,
184 // and probably won't be included anywhere else.
185 // (2) the thing we're referencing is a pure function.
186 // (3) the thing we're referencing is another inline function.
187 // This last can give us false negatives, but it's better than warning on
188 // wrappers for simple C library functions.
189 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
190 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
191 if (!DowngradeWarning && UsedFn)
192 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
193
194 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
195 : diag::ext_internal_in_extern_inline)
196 << /*IsVar=*/!UsedFn << D;
197
199
200 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
201 << D;
202}
203
205 const FunctionDecl *First = Cur->getFirstDecl();
206
207 // Suggest "static" on the function, if possible.
209 SourceLocation DeclBegin = First->getSourceRange().getBegin();
210 Diag(DeclBegin, diag::note_convert_inline_to_static)
211 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
212 }
213}
214
216 const ObjCInterfaceDecl *UnknownObjCClass,
217 bool ObjCPropertyAccess,
218 bool AvoidPartialAvailabilityChecks,
219 ObjCInterfaceDecl *ClassReceiver,
220 bool SkipTrailingRequiresClause) {
221 SourceLocation Loc = Locs.front();
222 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
223 // If there were any diagnostics suppressed by template argument deduction,
224 // emit them now.
225 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
226 if (Pos != SuppressedDiagnostics.end()) {
227 for (const PartialDiagnosticAt &Suppressed : Pos->second)
228 Diag(Suppressed.first, Suppressed.second);
229
230 // Clear out the list of suppressed diagnostics, so that we don't emit
231 // them again for this specialization. However, we don't obsolete this
232 // entry from the table, because we want to avoid ever emitting these
233 // diagnostics again.
234 Pos->second.clear();
235 }
236
237 // C++ [basic.start.main]p3:
238 // The function 'main' shall not be used within a program.
239 if (cast<FunctionDecl>(D)->isMain())
240 Diag(Loc, diag::ext_main_used);
241
242 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
243 }
244
245 // See if this is an auto-typed variable whose initializer we are parsing.
246 if (ParsingInitForAutoVars.count(D)) {
247 if (isa<BindingDecl>(D)) {
248 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
249 << D->getDeclName();
250 } else {
251 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
252 << D->getDeclName() << cast<VarDecl>(D)->getType();
253 }
254 return true;
255 }
256
257 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
258 // See if this is a deleted function.
259 if (FD->isDeleted()) {
260 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
261 if (Ctor && Ctor->isInheritingConstructor())
262 Diag(Loc, diag::err_deleted_inherited_ctor_use)
263 << Ctor->getParent()
264 << Ctor->getInheritedConstructor().getConstructor()->getParent();
265 else {
266 StringLiteral *Msg = FD->getDeletedMessage();
267 Diag(Loc, diag::err_deleted_function_use)
268 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
269 }
271 return true;
272 }
273
274 // [expr.prim.id]p4
275 // A program that refers explicitly or implicitly to a function with a
276 // trailing requires-clause whose constraint-expression is not satisfied,
277 // other than to declare it, is ill-formed. [...]
278 //
279 // See if this is a function with constraints that need to be satisfied.
280 // Check this before deducing the return type, as it might instantiate the
281 // definition.
282 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
283 ConstraintSatisfaction Satisfaction;
284 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
285 /*ForOverloadResolution*/ true))
286 // A diagnostic will have already been generated (non-constant
287 // constraint expression, for example)
288 return true;
289 if (!Satisfaction.IsSatisfied) {
290 Diag(Loc,
291 diag::err_reference_to_function_with_unsatisfied_constraints)
292 << D;
293 DiagnoseUnsatisfiedConstraint(Satisfaction);
294 return true;
295 }
296 }
297
298 // If the function has a deduced return type, and we can't deduce it,
299 // then we can't use it either.
300 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
302 return true;
303
304 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
305 return true;
306
307 }
308
309 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
310 // Lambdas are only default-constructible or assignable in C++2a onwards.
311 if (MD->getParent()->isLambda() &&
312 ((isa<CXXConstructorDecl>(MD) &&
313 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
314 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
315 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
316 << !isa<CXXConstructorDecl>(MD);
317 }
318 }
319
320 auto getReferencedObjCProp = [](const NamedDecl *D) ->
321 const ObjCPropertyDecl * {
322 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
323 return MD->findPropertyDecl();
324 return nullptr;
325 };
326 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
328 return true;
330 return true;
331 }
332
333 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
334 // Only the variables omp_in and omp_out are allowed in the combiner.
335 // Only the variables omp_priv and omp_orig are allowed in the
336 // initializer-clause.
337 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
338 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
339 isa<VarDecl>(D)) {
340 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
342 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
343 return true;
344 }
345
346 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
347 // List-items in map clauses on this construct may only refer to the declared
348 // variable var and entities that could be referenced by a procedure defined
349 // at the same location.
350 // [OpenMP 5.2] Also allow iterator declared variables.
351 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
352 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
353 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
355 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
356 return true;
357 }
358
359 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
360 Diag(Loc, diag::err_use_of_empty_using_if_exists);
361 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
362 return true;
363 }
364
365 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
366 AvoidPartialAvailabilityChecks, ClassReceiver);
367
368 DiagnoseUnusedOfDecl(*this, D, Loc);
369
371
372 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
373 if (getLangOpts().getFPEvalMethod() !=
376 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
377 Diag(D->getLocation(),
378 diag::err_type_available_only_in_default_eval_method)
379 << D->getName();
380 }
381
382 if (auto *VD = dyn_cast<ValueDecl>(D))
383 checkTypeSupport(VD->getType(), Loc, VD);
384
385 if (LangOpts.SYCLIsDevice ||
386 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
388 if (const auto *VD = dyn_cast<VarDecl>(D))
389 if (VD->getTLSKind() != VarDecl::TLS_None)
390 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
391 }
392
393 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
395 // C++ [expr.prim.req.nested] p3
396 // A local parameter shall only appear as an unevaluated operand
397 // (Clause 8) within the constraint-expression.
398 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
399 << D;
400 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
401 return true;
402 }
403
404 return false;
405}
406
408 ArrayRef<Expr *> Args) {
409 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
410 if (!Attr)
411 return;
412
413 // The number of formal parameters of the declaration.
414 unsigned NumFormalParams;
415
416 // The kind of declaration. This is also an index into a %select in
417 // the diagnostic.
418 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
419
420 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
421 NumFormalParams = MD->param_size();
422 CalleeKind = CK_Method;
423 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
424 NumFormalParams = FD->param_size();
425 CalleeKind = CK_Function;
426 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
427 QualType Ty = VD->getType();
428 const FunctionType *Fn = nullptr;
429 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
430 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
431 if (!Fn)
432 return;
433 CalleeKind = CK_Function;
434 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
435 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
436 CalleeKind = CK_Block;
437 } else {
438 return;
439 }
440
441 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
442 NumFormalParams = proto->getNumParams();
443 else
444 NumFormalParams = 0;
445 } else {
446 return;
447 }
448
449 // "NullPos" is the number of formal parameters at the end which
450 // effectively count as part of the variadic arguments. This is
451 // useful if you would prefer to not have *any* formal parameters,
452 // but the language forces you to have at least one.
453 unsigned NullPos = Attr->getNullPos();
454 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
455 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
456
457 // The number of arguments which should follow the sentinel.
458 unsigned NumArgsAfterSentinel = Attr->getSentinel();
459
460 // If there aren't enough arguments for all the formal parameters,
461 // the sentinel, and the args after the sentinel, complain.
462 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
463 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
464 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
465 return;
466 }
467
468 // Otherwise, find the sentinel expression.
469 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
470 if (!SentinelExpr)
471 return;
472 if (SentinelExpr->isValueDependent())
473 return;
474 if (Context.isSentinelNullExpr(SentinelExpr))
475 return;
476
477 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
478 // or 'NULL' if those are actually defined in the context. Only use
479 // 'nil' for ObjC methods, where it's much more likely that the
480 // variadic arguments form a list of object pointers.
481 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
482 std::string NullValue;
483 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
484 NullValue = "nil";
485 else if (getLangOpts().CPlusPlus11)
486 NullValue = "nullptr";
487 else if (PP.isMacroDefined("NULL"))
488 NullValue = "NULL";
489 else
490 NullValue = "(void*) 0";
491
492 if (MissingNilLoc.isInvalid())
493 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
494 else
495 Diag(MissingNilLoc, diag::warn_missing_sentinel)
496 << int(CalleeKind)
497 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
498 Diag(D->getLocation(), diag::note_sentinel_here)
499 << int(CalleeKind) << Attr->getRange();
500}
501
503 return E ? E->getSourceRange() : SourceRange();
504}
505
506//===----------------------------------------------------------------------===//
507// Standard Promotions and Conversions
508//===----------------------------------------------------------------------===//
509
510/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
512 // Handle any placeholder expressions which made it here.
513 if (E->hasPlaceholderType()) {
515 if (result.isInvalid()) return ExprError();
516 E = result.get();
517 }
518
519 QualType Ty = E->getType();
520 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
521
522 if (Ty->isFunctionType()) {
523 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
524 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
526 return ExprError();
527
529 CK_FunctionToPointerDecay).get();
530 } else if (Ty->isArrayType()) {
531 // In C90 mode, arrays only promote to pointers if the array expression is
532 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
533 // type 'array of type' is converted to an expression that has type 'pointer
534 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
535 // that has type 'array of type' ...". The relevant change is "an lvalue"
536 // (C90) to "an expression" (C99).
537 //
538 // C++ 4.2p1:
539 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
540 // T" can be converted to an rvalue of type "pointer to T".
541 //
542 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
544 CK_ArrayToPointerDecay);
545 if (Res.isInvalid())
546 return ExprError();
547 E = Res.get();
548 }
549 }
550 return E;
551}
552
554 // Check to see if we are dereferencing a null pointer. If so,
555 // and if not volatile-qualified, this is undefined behavior that the
556 // optimizer will delete, so warn about it. People sometimes try to use this
557 // to get a deterministic trap and are surprised by clang's behavior. This
558 // only handles the pattern "*null", which is a very syntactic check.
559 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
560 if (UO && UO->getOpcode() == UO_Deref &&
561 UO->getSubExpr()->getType()->isPointerType()) {
562 const LangAS AS =
563 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
564 if ((!isTargetAddressSpace(AS) ||
565 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
566 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
568 !UO->getType().isVolatileQualified()) {
569 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
570 S.PDiag(diag::warn_indirection_through_null)
571 << UO->getSubExpr()->getSourceRange());
572 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
573 S.PDiag(diag::note_indirection_through_null));
574 }
575 }
576}
577
578static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
579 SourceLocation AssignLoc,
580 const Expr* RHS) {
581 const ObjCIvarDecl *IV = OIRE->getDecl();
582 if (!IV)
583 return;
584
585 DeclarationName MemberName = IV->getDeclName();
587 if (!Member || !Member->isStr("isa"))
588 return;
589
590 const Expr *Base = OIRE->getBase();
591 QualType BaseType = Base->getType();
592 if (OIRE->isArrow())
593 BaseType = BaseType->getPointeeType();
594 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
595 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
596 ObjCInterfaceDecl *ClassDeclared = nullptr;
597 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
598 if (!ClassDeclared->getSuperClass()
599 && (*ClassDeclared->ivar_begin()) == IV) {
600 if (RHS) {
601 NamedDecl *ObjectSetClass =
603 &S.Context.Idents.get("object_setClass"),
605 if (ObjectSetClass) {
606 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
607 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
609 "object_setClass(")
611 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
612 << FixItHint::CreateInsertion(RHSLocEnd, ")");
613 }
614 else
615 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
616 } else {
617 NamedDecl *ObjectGetClass =
619 &S.Context.Idents.get("object_getClass"),
621 if (ObjectGetClass)
622 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
624 "object_getClass(")
626 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
627 else
628 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
629 }
630 S.Diag(IV->getLocation(), diag::note_ivar_decl);
631 }
632 }
633}
634
636 // Handle any placeholder expressions which made it here.
637 if (E->hasPlaceholderType()) {
639 if (result.isInvalid()) return ExprError();
640 E = result.get();
641 }
642
643 // C++ [conv.lval]p1:
644 // A glvalue of a non-function, non-array type T can be
645 // converted to a prvalue.
646 if (!E->isGLValue()) return E;
647
648 QualType T = E->getType();
649 assert(!T.isNull() && "r-value conversion on typeless expression?");
650
651 // lvalue-to-rvalue conversion cannot be applied to types that decay to
652 // pointers (i.e. function or array types).
654 return E;
655
656 // We don't want to throw lvalue-to-rvalue casts on top of
657 // expressions of certain types in C++.
658 if (getLangOpts().CPlusPlus) {
659 if (T == Context.OverloadTy || T->isRecordType() ||
660 (T->isDependentType() && !T->isAnyPointerType() &&
662 return E;
663 }
664
665 // The C standard is actually really unclear on this point, and
666 // DR106 tells us what the result should be but not why. It's
667 // generally best to say that void types just doesn't undergo
668 // lvalue-to-rvalue at all. Note that expressions of unqualified
669 // 'void' type are never l-values, but qualified void can be.
670 if (T->isVoidType())
671 return E;
672
673 // OpenCL usually rejects direct accesses to values of 'half' type.
674 if (getLangOpts().OpenCL &&
675 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
676 T->isHalfType()) {
677 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
678 << 0 << T;
679 return ExprError();
680 }
681
683 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
684 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
685 &Context.Idents.get("object_getClass"),
687 if (ObjectGetClass)
688 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
689 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
691 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
692 else
693 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
694 }
695 else if (const ObjCIvarRefExpr *OIRE =
696 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
697 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
698
699 // C++ [conv.lval]p1:
700 // [...] If T is a non-class type, the type of the prvalue is the
701 // cv-unqualified version of T. Otherwise, the type of the
702 // rvalue is T.
703 //
704 // C99 6.3.2.1p2:
705 // If the lvalue has qualified type, the value has the unqualified
706 // version of the type of the lvalue; otherwise, the value has the
707 // type of the lvalue.
708 if (T.hasQualifiers())
709 T = T.getUnqualifiedType();
710
711 // Under the MS ABI, lock down the inheritance model now.
712 if (T->isMemberPointerType() &&
714 (void)isCompleteType(E->getExprLoc(), T);
715
717 if (Res.isInvalid())
718 return Res;
719 E = Res.get();
720
721 // Loading a __weak object implicitly retains the value, so we need a cleanup to
722 // balance that.
725
728
729 // C++ [conv.lval]p3:
730 // If T is cv std::nullptr_t, the result is a null pointer constant.
731 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
732 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
734
735 // C11 6.3.2.1p2:
736 // ... if the lvalue has atomic type, the value has the non-atomic version
737 // of the type of the lvalue ...
738 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
739 T = Atomic->getValueType().getUnqualifiedType();
740 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
741 nullptr, VK_PRValue, FPOptionsOverride());
742 }
743
744 return Res;
745}
746
749 if (Res.isInvalid())
750 return ExprError();
751 Res = DefaultLvalueConversion(Res.get());
752 if (Res.isInvalid())
753 return ExprError();
754 return Res;
755}
756
758 QualType Ty = E->getType();
759 ExprResult Res = E;
760 // Only do implicit cast for a function type, but not for a pointer
761 // to function type.
762 if (Ty->isFunctionType()) {
764 CK_FunctionToPointerDecay);
765 if (Res.isInvalid())
766 return ExprError();
767 }
768 Res = DefaultLvalueConversion(Res.get());
769 if (Res.isInvalid())
770 return ExprError();
771 return Res.get();
772}
773
774/// UsualUnaryConversions - Performs various conversions that are common to most
775/// operators (C99 6.3). The conversions of array and function types are
776/// sometimes suppressed. For example, the array->pointer conversion doesn't
777/// apply if the array is an argument to the sizeof or address (&) operators.
778/// In these instances, this routine should *not* be called.
780 // First, convert to an r-value.
782 if (Res.isInvalid())
783 return ExprError();
784 E = Res.get();
785
786 QualType Ty = E->getType();
787 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
788
789 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
790 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
791 (getLangOpts().getFPEvalMethod() !=
794 switch (EvalMethod) {
795 default:
796 llvm_unreachable("Unrecognized float evaluation method");
797 break;
799 llvm_unreachable("Float evaluation method should be set by now");
800 break;
803 // Widen the expression to double.
804 return Ty->isComplexType()
807 CK_FloatingComplexCast)
808 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
809 break;
812 // Widen the expression to long double.
813 return Ty->isComplexType()
816 CK_FloatingComplexCast)
818 CK_FloatingCast);
819 break;
820 }
821 }
822
823 // Half FP have to be promoted to float unless it is natively supported
824 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
825 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
826
827 // Try to perform integral promotions if the object has a theoretically
828 // promotable type.
830 // C99 6.3.1.1p2:
831 //
832 // The following may be used in an expression wherever an int or
833 // unsigned int may be used:
834 // - an object or expression with an integer type whose integer
835 // conversion rank is less than or equal to the rank of int
836 // and unsigned int.
837 // - A bit-field of type _Bool, int, signed int, or unsigned int.
838 //
839 // If an int can represent all values of the original type, the
840 // value is converted to an int; otherwise, it is converted to an
841 // unsigned int. These are called the integer promotions. All
842 // other types are unchanged by the integer promotions.
843
845 if (!PTy.isNull()) {
846 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
847 return E;
848 }
851 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
852 return E;
853 }
854 }
855 return E;
856}
857
858/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
859/// do not have a prototype. Arguments that have type float or __fp16
860/// are promoted to double. All other argument types are converted by
861/// UsualUnaryConversions().
863 QualType Ty = E->getType();
864 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
865
867 if (Res.isInvalid())
868 return ExprError();
869 E = Res.get();
870
871 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
872 // promote to double.
873 // Note that default argument promotion applies only to float (and
874 // half/fp16); it does not apply to _Float16.
875 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
876 if (BTy && (BTy->getKind() == BuiltinType::Half ||
877 BTy->getKind() == BuiltinType::Float)) {
878 if (getLangOpts().OpenCL &&
879 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
880 if (BTy->getKind() == BuiltinType::Half) {
881 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
882 }
883 } else {
884 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
885 }
886 }
887 if (BTy &&
888 getLangOpts().getExtendIntArgs() ==
893 E = (Ty->isUnsignedIntegerType())
894 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
895 .get()
896 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
898 "Unexpected typesize for LongLongTy");
899 }
900
901 // C++ performs lvalue-to-rvalue conversion as a default argument
902 // promotion, even on class types, but note:
903 // C++11 [conv.lval]p2:
904 // When an lvalue-to-rvalue conversion occurs in an unevaluated
905 // operand or a subexpression thereof the value contained in the
906 // referenced object is not accessed. Otherwise, if the glvalue
907 // has a class type, the conversion copy-initializes a temporary
908 // of type T from the glvalue and the result of the conversion
909 // is a prvalue for the temporary.
910 // FIXME: add some way to gate this entire thing for correctness in
911 // potentially potentially evaluated contexts.
915 E->getExprLoc(), E);
916 if (Temp.isInvalid())
917 return ExprError();
918 E = Temp.get();
919 }
920
921 return E;
922}
923
925 if (Ty->isIncompleteType()) {
926 // C++11 [expr.call]p7:
927 // After these conversions, if the argument does not have arithmetic,
928 // enumeration, pointer, pointer to member, or class type, the program
929 // is ill-formed.
930 //
931 // Since we've already performed array-to-pointer and function-to-pointer
932 // decay, the only such type in C++ is cv void. This also handles
933 // initializer lists as variadic arguments.
934 if (Ty->isVoidType())
935 return VAK_Invalid;
936
937 if (Ty->isObjCObjectType())
938 return VAK_Invalid;
939 return VAK_Valid;
940 }
941
943 return VAK_Invalid;
944
945 if (Context.getTargetInfo().getTriple().isWasm() &&
947 return VAK_Invalid;
948 }
949
950 if (Ty.isCXX98PODType(Context))
951 return VAK_Valid;
952
953 // C++11 [expr.call]p7:
954 // Passing a potentially-evaluated argument of class type (Clause 9)
955 // having a non-trivial copy constructor, a non-trivial move constructor,
956 // or a non-trivial destructor, with no corresponding parameter,
957 // is conditionally-supported with implementation-defined semantics.
960 if (!Record->hasNonTrivialCopyConstructor() &&
961 !Record->hasNonTrivialMoveConstructor() &&
962 !Record->hasNonTrivialDestructor())
963 return VAK_ValidInCXX11;
964
965 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
966 return VAK_Valid;
967
968 if (Ty->isObjCObjectType())
969 return VAK_Invalid;
970
971 if (getLangOpts().MSVCCompat)
972 return VAK_MSVCUndefined;
973
974 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
975 // permitted to reject them. We should consider doing so.
976 return VAK_Undefined;
977}
978
980 // Don't allow one to pass an Objective-C interface to a vararg.
981 const QualType &Ty = E->getType();
983
984 // Complain about passing non-POD types through varargs.
985 switch (VAK) {
986 case VAK_ValidInCXX11:
988 E->getBeginLoc(), nullptr,
989 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
990 [[fallthrough]];
991 case VAK_Valid:
992 if (Ty->isRecordType()) {
993 // This is unlikely to be what the user intended. If the class has a
994 // 'c_str' member function, the user probably meant to call that.
996 PDiag(diag::warn_pass_class_arg_to_vararg)
997 << Ty << CT << hasCStrMethod(E) << ".c_str()");
998 }
999 break;
1000
1001 case VAK_Undefined:
1002 case VAK_MSVCUndefined:
1003 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1004 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1005 << getLangOpts().CPlusPlus11 << Ty << CT);
1006 break;
1007
1008 case VAK_Invalid:
1010 Diag(E->getBeginLoc(),
1011 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1012 << Ty << CT;
1013 else if (Ty->isObjCObjectType())
1014 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1015 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1016 << Ty << CT);
1017 else
1018 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1019 << isa<InitListExpr>(E) << Ty << CT;
1020 break;
1021 }
1022}
1023
1025 FunctionDecl *FDecl) {
1026 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1027 // Strip the unbridged-cast placeholder expression off, if applicable.
1028 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1029 (CT == VariadicMethod ||
1030 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1032
1033 // Otherwise, do normal placeholder checking.
1034 } else {
1036 if (ExprRes.isInvalid())
1037 return ExprError();
1038 E = ExprRes.get();
1039 }
1040 }
1041
1043 if (ExprRes.isInvalid())
1044 return ExprError();
1045
1046 // Copy blocks to the heap.
1047 if (ExprRes.get()->getType()->isBlockPointerType())
1048 maybeExtendBlockObject(ExprRes);
1049
1050 E = ExprRes.get();
1051
1052 // Diagnostics regarding non-POD argument types are
1053 // emitted along with format string checking in Sema::CheckFunctionCall().
1055 // Turn this into a trap.
1056 CXXScopeSpec SS;
1057 SourceLocation TemplateKWLoc;
1058 UnqualifiedId Name;
1059 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1060 E->getBeginLoc());
1061 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1062 /*HasTrailingLParen=*/true,
1063 /*IsAddressOfOperand=*/false);
1064 if (TrapFn.isInvalid())
1065 return ExprError();
1066
1068 std::nullopt, E->getEndLoc());
1069 if (Call.isInvalid())
1070 return ExprError();
1071
1072 ExprResult Comma =
1073 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1074 if (Comma.isInvalid())
1075 return ExprError();
1076 return Comma.get();
1077 }
1078
1079 if (!getLangOpts().CPlusPlus &&
1081 diag::err_call_incomplete_argument))
1082 return ExprError();
1083
1084 return E;
1085}
1086
1087/// Convert complex integers to complex floats and real integers to
1088/// real floats as required for complex arithmetic. Helper function of
1089/// UsualArithmeticConversions()
1090///
1091/// \return false if the integer expression is an integer type and is
1092/// successfully converted to the (complex) float type.
1094 ExprResult &ComplexExpr,
1095 QualType IntTy,
1096 QualType ComplexTy,
1097 bool SkipCast) {
1098 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1099 if (SkipCast) return false;
1100 if (IntTy->isIntegerType()) {
1101 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1102 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1103 } else {
1104 assert(IntTy->isComplexIntegerType());
1105 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1106 CK_IntegralComplexToFloatingComplex);
1107 }
1108 return false;
1109}
1110
1111// This handles complex/complex, complex/float, or float/complex.
1112// When both operands are complex, the shorter operand is converted to the
1113// type of the longer, and that is the type of the result. This corresponds
1114// to what is done when combining two real floating-point operands.
1115// The fun begins when size promotion occur across type domains.
1116// From H&S 6.3.4: When one operand is complex and the other is a real
1117// floating-point type, the less precise type is converted, within it's
1118// real or complex domain, to the precision of the other type. For example,
1119// when combining a "long double" with a "double _Complex", the
1120// "double _Complex" is promoted to "long double _Complex".
1122 QualType ShorterType,
1123 QualType LongerType,
1124 bool PromotePrecision) {
1125 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1127 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1128
1129 if (PromotePrecision) {
1130 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1131 Shorter =
1132 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1133 } else {
1134 if (LongerIsComplex)
1135 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1136 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1137 }
1138 }
1139 return Result;
1140}
1141
1142/// Handle arithmetic conversion with complex types. Helper function of
1143/// UsualArithmeticConversions()
1145 ExprResult &RHS, QualType LHSType,
1146 QualType RHSType, bool IsCompAssign) {
1147 // Handle (complex) integer types.
1148 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1149 /*SkipCast=*/false))
1150 return LHSType;
1151 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1152 /*SkipCast=*/IsCompAssign))
1153 return RHSType;
1154
1155 // Compute the rank of the two types, regardless of whether they are complex.
1156 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1157 if (Order < 0)
1158 // Promote the precision of the LHS if not an assignment.
1159 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1160 /*PromotePrecision=*/!IsCompAssign);
1161 // Promote the precision of the RHS unless it is already the same as the LHS.
1162 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1163 /*PromotePrecision=*/Order > 0);
1164}
1165
1166/// Handle arithmetic conversion from integer to float. Helper function
1167/// of UsualArithmeticConversions()
1169 ExprResult &IntExpr,
1170 QualType FloatTy, QualType IntTy,
1171 bool ConvertFloat, bool ConvertInt) {
1172 if (IntTy->isIntegerType()) {
1173 if (ConvertInt)
1174 // Convert intExpr to the lhs floating point type.
1175 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1176 CK_IntegralToFloating);
1177 return FloatTy;
1178 }
1179
1180 // Convert both sides to the appropriate complex float.
1181 assert(IntTy->isComplexIntegerType());
1182 QualType result = S.Context.getComplexType(FloatTy);
1183
1184 // _Complex int -> _Complex float
1185 if (ConvertInt)
1186 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1187 CK_IntegralComplexToFloatingComplex);
1188
1189 // float -> _Complex float
1190 if (ConvertFloat)
1191 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1192 CK_FloatingRealToComplex);
1193
1194 return result;
1195}
1196
1197/// Handle arithmethic conversion with floating point types. Helper
1198/// function of UsualArithmeticConversions()
1200 ExprResult &RHS, QualType LHSType,
1201 QualType RHSType, bool IsCompAssign) {
1202 bool LHSFloat = LHSType->isRealFloatingType();
1203 bool RHSFloat = RHSType->isRealFloatingType();
1204
1205 // N1169 4.1.4: If one of the operands has a floating type and the other
1206 // operand has a fixed-point type, the fixed-point operand
1207 // is converted to the floating type [...]
1208 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1209 if (LHSFloat)
1210 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1211 else if (!IsCompAssign)
1212 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1213 return LHSFloat ? LHSType : RHSType;
1214 }
1215
1216 // If we have two real floating types, convert the smaller operand
1217 // to the bigger result.
1218 if (LHSFloat && RHSFloat) {
1219 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1220 if (order > 0) {
1221 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1222 return LHSType;
1223 }
1224
1225 assert(order < 0 && "illegal float comparison");
1226 if (!IsCompAssign)
1227 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1228 return RHSType;
1229 }
1230
1231 if (LHSFloat) {
1232 // Half FP has to be promoted to float unless it is natively supported
1233 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1234 LHSType = S.Context.FloatTy;
1235
1236 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1237 /*ConvertFloat=*/!IsCompAssign,
1238 /*ConvertInt=*/ true);
1239 }
1240 assert(RHSFloat);
1241 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1242 /*ConvertFloat=*/ true,
1243 /*ConvertInt=*/!IsCompAssign);
1244}
1245
1246/// Diagnose attempts to convert between __float128, __ibm128 and
1247/// long double if there is no support for such conversion.
1248/// Helper function of UsualArithmeticConversions().
1249static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1250 QualType RHSType) {
1251 // No issue if either is not a floating point type.
1252 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1253 return false;
1254
1255 // No issue if both have the same 128-bit float semantics.
1256 auto *LHSComplex = LHSType->getAs<ComplexType>();
1257 auto *RHSComplex = RHSType->getAs<ComplexType>();
1258
1259 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1260 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1261
1262 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1263 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1264
1265 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1266 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1267 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1268 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1269 return false;
1270
1271 return true;
1272}
1273
1274typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1275
1276namespace {
1277/// These helper callbacks are placed in an anonymous namespace to
1278/// permit their use as function template parameters.
1279ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1280 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1281}
1282
1283ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1284 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1285 CK_IntegralComplexCast);
1286}
1287}
1288
1289/// Handle integer arithmetic conversions. Helper function of
1290/// UsualArithmeticConversions()
1291template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1293 ExprResult &RHS, QualType LHSType,
1294 QualType RHSType, bool IsCompAssign) {
1295 // The rules for this case are in C99 6.3.1.8
1296 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1297 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1298 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1299 if (LHSSigned == RHSSigned) {
1300 // Same signedness; use the higher-ranked type
1301 if (order >= 0) {
1302 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1303 return LHSType;
1304 } else if (!IsCompAssign)
1305 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1306 return RHSType;
1307 } else if (order != (LHSSigned ? 1 : -1)) {
1308 // The unsigned type has greater than or equal rank to the
1309 // signed type, so use the unsigned type
1310 if (RHSSigned) {
1311 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1312 return LHSType;
1313 } else if (!IsCompAssign)
1314 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1315 return RHSType;
1316 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1317 // The two types are different widths; if we are here, that
1318 // means the signed type is larger than the unsigned type, so
1319 // use the signed type.
1320 if (LHSSigned) {
1321 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1322 return LHSType;
1323 } else if (!IsCompAssign)
1324 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1325 return RHSType;
1326 } else {
1327 // The signed type is higher-ranked than the unsigned type,
1328 // but isn't actually any bigger (like unsigned int and long
1329 // on most 32-bit systems). Use the unsigned type corresponding
1330 // to the signed type.
1331 QualType result =
1332 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1333 RHS = (*doRHSCast)(S, RHS.get(), result);
1334 if (!IsCompAssign)
1335 LHS = (*doLHSCast)(S, LHS.get(), result);
1336 return result;
1337 }
1338}
1339
1340/// Handle conversions with GCC complex int extension. Helper function
1341/// of UsualArithmeticConversions()
1343 ExprResult &RHS, QualType LHSType,
1344 QualType RHSType,
1345 bool IsCompAssign) {
1346 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1347 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1348
1349 if (LHSComplexInt && RHSComplexInt) {
1350 QualType LHSEltType = LHSComplexInt->getElementType();
1351 QualType RHSEltType = RHSComplexInt->getElementType();
1352 QualType ScalarType =
1353 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1354 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1355
1356 return S.Context.getComplexType(ScalarType);
1357 }
1358
1359 if (LHSComplexInt) {
1360 QualType LHSEltType = LHSComplexInt->getElementType();
1361 QualType ScalarType =
1362 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1363 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1365 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1366 CK_IntegralRealToComplex);
1367
1368 return ComplexType;
1369 }
1370
1371 assert(RHSComplexInt);
1372
1373 QualType RHSEltType = RHSComplexInt->getElementType();
1374 QualType ScalarType =
1375 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1376 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1378
1379 if (!IsCompAssign)
1380 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1381 CK_IntegralRealToComplex);
1382 return ComplexType;
1383}
1384
1385/// Return the rank of a given fixed point or integer type. The value itself
1386/// doesn't matter, but the values must be increasing with proper increasing
1387/// rank as described in N1169 4.1.1.
1388static unsigned GetFixedPointRank(QualType Ty) {
1389 const auto *BTy = Ty->getAs<BuiltinType>();
1390 assert(BTy && "Expected a builtin type.");
1391
1392 switch (BTy->getKind()) {
1393 case BuiltinType::ShortFract:
1394 case BuiltinType::UShortFract:
1395 case BuiltinType::SatShortFract:
1396 case BuiltinType::SatUShortFract:
1397 return 1;
1398 case BuiltinType::Fract:
1399 case BuiltinType::UFract:
1400 case BuiltinType::SatFract:
1401 case BuiltinType::SatUFract:
1402 return 2;
1403 case BuiltinType::LongFract:
1404 case BuiltinType::ULongFract:
1405 case BuiltinType::SatLongFract:
1406 case BuiltinType::SatULongFract:
1407 return 3;
1408 case BuiltinType::ShortAccum:
1409 case BuiltinType::UShortAccum:
1410 case BuiltinType::SatShortAccum:
1411 case BuiltinType::SatUShortAccum:
1412 return 4;
1413 case BuiltinType::Accum:
1414 case BuiltinType::UAccum:
1415 case BuiltinType::SatAccum:
1416 case BuiltinType::SatUAccum:
1417 return 5;
1418 case BuiltinType::LongAccum:
1419 case BuiltinType::ULongAccum:
1420 case BuiltinType::SatLongAccum:
1421 case BuiltinType::SatULongAccum:
1422 return 6;
1423 default:
1424 if (BTy->isInteger())
1425 return 0;
1426 llvm_unreachable("Unexpected fixed point or integer type");
1427 }
1428}
1429
1430/// handleFixedPointConversion - Fixed point operations between fixed
1431/// point types and integers or other fixed point types do not fall under
1432/// usual arithmetic conversion since these conversions could result in loss
1433/// of precsision (N1169 4.1.4). These operations should be calculated with
1434/// the full precision of their result type (N1169 4.1.6.2.1).
1436 QualType RHSTy) {
1437 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1438 "Expected at least one of the operands to be a fixed point type");
1439 assert((LHSTy->isFixedPointOrIntegerType() ||
1440 RHSTy->isFixedPointOrIntegerType()) &&
1441 "Special fixed point arithmetic operation conversions are only "
1442 "applied to ints or other fixed point types");
1443
1444 // If one operand has signed fixed-point type and the other operand has
1445 // unsigned fixed-point type, then the unsigned fixed-point operand is
1446 // converted to its corresponding signed fixed-point type and the resulting
1447 // type is the type of the converted operand.
1448 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1450 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1452
1453 // The result type is the type with the highest rank, whereby a fixed-point
1454 // conversion rank is always greater than an integer conversion rank; if the
1455 // type of either of the operands is a saturating fixedpoint type, the result
1456 // type shall be the saturating fixed-point type corresponding to the type
1457 // with the highest rank; the resulting value is converted (taking into
1458 // account rounding and overflow) to the precision of the resulting type.
1459 // Same ranks between signed and unsigned types are resolved earlier, so both
1460 // types are either signed or both unsigned at this point.
1461 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1462 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1463
1464 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1465
1467 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1468
1469 return ResultTy;
1470}
1471
1472/// Check that the usual arithmetic conversions can be performed on this pair of
1473/// expressions that might be of enumeration type.
1476 Sema::ArithConvKind ACK) {
1477 // C++2a [expr.arith.conv]p1:
1478 // If one operand is of enumeration type and the other operand is of a
1479 // different enumeration type or a floating-point type, this behavior is
1480 // deprecated ([depr.arith.conv.enum]).
1481 //
1482 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1483 // Eventually we will presumably reject these cases (in C++23 onwards?).
1485 R = RHS->getEnumCoercedType(S.Context);
1486 bool LEnum = L->isUnscopedEnumerationType(),
1487 REnum = R->isUnscopedEnumerationType();
1488 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1489 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1490 (REnum && L->isFloatingType())) {
1491 S.Diag(Loc, S.getLangOpts().CPlusPlus26
1492 ? diag::err_arith_conv_enum_float_cxx26
1493 : S.getLangOpts().CPlusPlus20
1494 ? diag::warn_arith_conv_enum_float_cxx20
1495 : diag::warn_arith_conv_enum_float)
1496 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1497 << L << R;
1498 } else if (!IsCompAssign && LEnum && REnum &&
1500 unsigned DiagID;
1501 // In C++ 26, usual arithmetic conversions between 2 different enum types
1502 // are ill-formed.
1503 if (S.getLangOpts().CPlusPlus26)
1504 DiagID = diag::err_conv_mixed_enum_types_cxx26;
1505 else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1506 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1507 // If either enumeration type is unnamed, it's less likely that the
1508 // user cares about this, but this situation is still deprecated in
1509 // C++2a. Use a different warning group.
1510 DiagID = S.getLangOpts().CPlusPlus20
1511 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1512 : diag::warn_arith_conv_mixed_anon_enum_types;
1513 } else if (ACK == Sema::ACK_Conditional) {
1514 // Conditional expressions are separated out because they have
1515 // historically had a different warning flag.
1516 DiagID = S.getLangOpts().CPlusPlus20
1517 ? diag::warn_conditional_mixed_enum_types_cxx20
1518 : diag::warn_conditional_mixed_enum_types;
1519 } else if (ACK == Sema::ACK_Comparison) {
1520 // Comparison expressions are separated out because they have
1521 // historically had a different warning flag.
1522 DiagID = S.getLangOpts().CPlusPlus20
1523 ? diag::warn_comparison_mixed_enum_types_cxx20
1524 : diag::warn_comparison_mixed_enum_types;
1525 } else {
1526 DiagID = S.getLangOpts().CPlusPlus20
1527 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1528 : diag::warn_arith_conv_mixed_enum_types;
1529 }
1530 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1531 << (int)ACK << L << R;
1532 }
1533}
1534
1535/// UsualArithmeticConversions - Performs various conversions that are common to
1536/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1537/// routine returns the first non-arithmetic type found. The client is
1538/// responsible for emitting appropriate error diagnostics.
1541 ArithConvKind ACK) {
1542 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1543
1544 if (ACK != ACK_CompAssign) {
1545 LHS = UsualUnaryConversions(LHS.get());
1546 if (LHS.isInvalid())
1547 return QualType();
1548 }
1549
1550 RHS = UsualUnaryConversions(RHS.get());
1551 if (RHS.isInvalid())
1552 return QualType();
1553
1554 // For conversion purposes, we ignore any qualifiers.
1555 // For example, "const float" and "float" are equivalent.
1556 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1557 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1558
1559 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1560 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1561 LHSType = AtomicLHS->getValueType();
1562
1563 // If both types are identical, no conversion is needed.
1564 if (Context.hasSameType(LHSType, RHSType))
1565 return Context.getCommonSugaredType(LHSType, RHSType);
1566
1567 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1568 // The caller can deal with this (e.g. pointer + int).
1569 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1570 return QualType();
1571
1572 // Apply unary and bitfield promotions to the LHS's type.
1573 QualType LHSUnpromotedType = LHSType;
1574 if (Context.isPromotableIntegerType(LHSType))
1575 LHSType = Context.getPromotedIntegerType(LHSType);
1576 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1577 if (!LHSBitfieldPromoteTy.isNull())
1578 LHSType = LHSBitfieldPromoteTy;
1579 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1580 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1581
1582 // If both types are identical, no conversion is needed.
1583 if (Context.hasSameType(LHSType, RHSType))
1584 return Context.getCommonSugaredType(LHSType, RHSType);
1585
1586 // At this point, we have two different arithmetic types.
1587
1588 // Diagnose attempts to convert between __ibm128, __float128 and long double
1589 // where such conversions currently can't be handled.
1590 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1591 return QualType();
1592
1593 // Handle complex types first (C99 6.3.1.8p1).
1594 if (LHSType->isComplexType() || RHSType->isComplexType())
1595 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1596 ACK == ACK_CompAssign);
1597
1598 // Now handle "real" floating types (i.e. float, double, long double).
1599 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1600 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1601 ACK == ACK_CompAssign);
1602
1603 // Handle GCC complex int extension.
1604 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1605 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1606 ACK == ACK_CompAssign);
1607
1608 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1609 return handleFixedPointConversion(*this, LHSType, RHSType);
1610
1611 // Finally, we have two differing integer types.
1612 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1613 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1614}
1615
1616//===----------------------------------------------------------------------===//
1617// Semantic Analysis for various Expression Types
1618//===----------------------------------------------------------------------===//
1619
1620
1622 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1623 bool PredicateIsExpr, void *ControllingExprOrType,
1624 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1625 unsigned NumAssocs = ArgTypes.size();
1626 assert(NumAssocs == ArgExprs.size());
1627
1628 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1629 for (unsigned i = 0; i < NumAssocs; ++i) {
1630 if (ArgTypes[i])
1631 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1632 else
1633 Types[i] = nullptr;
1634 }
1635
1636 // If we have a controlling type, we need to convert it from a parsed type
1637 // into a semantic type and then pass that along.
1638 if (!PredicateIsExpr) {
1639 TypeSourceInfo *ControllingType;
1640 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1641 &ControllingType);
1642 assert(ControllingType && "couldn't get the type out of the parser");
1643 ControllingExprOrType = ControllingType;
1644 }
1645
1647 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1648 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1649 delete [] Types;
1650 return ER;
1651}
1652
1654 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1655 bool PredicateIsExpr, void *ControllingExprOrType,
1657 unsigned NumAssocs = Types.size();
1658 assert(NumAssocs == Exprs.size());
1659 assert(ControllingExprOrType &&
1660 "Must have either a controlling expression or a controlling type");
1661
1662 Expr *ControllingExpr = nullptr;
1663 TypeSourceInfo *ControllingType = nullptr;
1664 if (PredicateIsExpr) {
1665 // Decay and strip qualifiers for the controlling expression type, and
1666 // handle placeholder type replacement. See committee discussion from WG14
1667 // DR423.
1671 reinterpret_cast<Expr *>(ControllingExprOrType));
1672 if (R.isInvalid())
1673 return ExprError();
1674 ControllingExpr = R.get();
1675 } else {
1676 // The extension form uses the type directly rather than converting it.
1677 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1678 if (!ControllingType)
1679 return ExprError();
1680 }
1681
1682 bool TypeErrorFound = false,
1683 IsResultDependent = ControllingExpr
1684 ? ControllingExpr->isTypeDependent()
1685 : ControllingType->getType()->isDependentType(),
1686 ContainsUnexpandedParameterPack =
1687 ControllingExpr
1688 ? ControllingExpr->containsUnexpandedParameterPack()
1689 : ControllingType->getType()->containsUnexpandedParameterPack();
1690
1691 // The controlling expression is an unevaluated operand, so side effects are
1692 // likely unintended.
1693 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1694 ControllingExpr->HasSideEffects(Context, false))
1695 Diag(ControllingExpr->getExprLoc(),
1696 diag::warn_side_effects_unevaluated_context);
1697
1698 for (unsigned i = 0; i < NumAssocs; ++i) {
1699 if (Exprs[i]->containsUnexpandedParameterPack())
1700 ContainsUnexpandedParameterPack = true;
1701
1702 if (Types[i]) {
1703 if (Types[i]->getType()->containsUnexpandedParameterPack())
1704 ContainsUnexpandedParameterPack = true;
1705
1706 if (Types[i]->getType()->isDependentType()) {
1707 IsResultDependent = true;
1708 } else {
1709 // We relax the restriction on use of incomplete types and non-object
1710 // types with the type-based extension of _Generic. Allowing incomplete
1711 // objects means those can be used as "tags" for a type-safe way to map
1712 // to a value. Similarly, matching on function types rather than
1713 // function pointer types can be useful. However, the restriction on VM
1714 // types makes sense to retain as there are open questions about how
1715 // the selection can be made at compile time.
1716 //
1717 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1718 // complete object type other than a variably modified type."
1719 unsigned D = 0;
1720 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1721 D = diag::err_assoc_type_incomplete;
1722 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1723 D = diag::err_assoc_type_nonobject;
1724 else if (Types[i]->getType()->isVariablyModifiedType())
1725 D = diag::err_assoc_type_variably_modified;
1726 else if (ControllingExpr) {
1727 // Because the controlling expression undergoes lvalue conversion,
1728 // array conversion, and function conversion, an association which is
1729 // of array type, function type, or is qualified can never be
1730 // reached. We will warn about this so users are less surprised by
1731 // the unreachable association. However, we don't have to handle
1732 // function types; that's not an object type, so it's handled above.
1733 //
1734 // The logic is somewhat different for C++ because C++ has different
1735 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1736 // If T is a non-class type, the type of the prvalue is the cv-
1737 // unqualified version of T. Otherwise, the type of the prvalue is T.
1738 // The result of these rules is that all qualified types in an
1739 // association in C are unreachable, and in C++, only qualified non-
1740 // class types are unreachable.
1741 //
1742 // NB: this does not apply when the first operand is a type rather
1743 // than an expression, because the type form does not undergo
1744 // conversion.
1745 unsigned Reason = 0;
1746 QualType QT = Types[i]->getType();
1747 if (QT->isArrayType())
1748 Reason = 1;
1749 else if (QT.hasQualifiers() &&
1750 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1751 Reason = 2;
1752
1753 if (Reason)
1754 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1755 diag::warn_unreachable_association)
1756 << QT << (Reason - 1);
1757 }
1758
1759 if (D != 0) {
1760 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1761 << Types[i]->getTypeLoc().getSourceRange()
1762 << Types[i]->getType();
1763 TypeErrorFound = true;
1764 }
1765
1766 // C11 6.5.1.1p2 "No two generic associations in the same generic
1767 // selection shall specify compatible types."
1768 for (unsigned j = i+1; j < NumAssocs; ++j)
1769 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1770 Context.typesAreCompatible(Types[i]->getType(),
1771 Types[j]->getType())) {
1772 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1773 diag::err_assoc_compatible_types)
1774 << Types[j]->getTypeLoc().getSourceRange()
1775 << Types[j]->getType()
1776 << Types[i]->getType();
1777 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1778 diag::note_compat_assoc)
1779 << Types[i]->getTypeLoc().getSourceRange()
1780 << Types[i]->getType();
1781 TypeErrorFound = true;
1782 }
1783 }
1784 }
1785 }
1786 if (TypeErrorFound)
1787 return ExprError();
1788
1789 // If we determined that the generic selection is result-dependent, don't
1790 // try to compute the result expression.
1791 if (IsResultDependent) {
1792 if (ControllingExpr)
1793 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1794 Types, Exprs, DefaultLoc, RParenLoc,
1795 ContainsUnexpandedParameterPack);
1796 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1797 Exprs, DefaultLoc, RParenLoc,
1798 ContainsUnexpandedParameterPack);
1799 }
1800
1801 SmallVector<unsigned, 1> CompatIndices;
1802 unsigned DefaultIndex = -1U;
1803 // Look at the canonical type of the controlling expression in case it was a
1804 // deduced type like __auto_type. However, when issuing diagnostics, use the
1805 // type the user wrote in source rather than the canonical one.
1806 for (unsigned i = 0; i < NumAssocs; ++i) {
1807 if (!Types[i])
1808 DefaultIndex = i;
1809 else if (ControllingExpr &&
1811 ControllingExpr->getType().getCanonicalType(),
1812 Types[i]->getType()))
1813 CompatIndices.push_back(i);
1814 else if (ControllingType &&
1816 ControllingType->getType().getCanonicalType(),
1817 Types[i]->getType()))
1818 CompatIndices.push_back(i);
1819 }
1820
1821 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1822 TypeSourceInfo *ControllingType) {
1823 // We strip parens here because the controlling expression is typically
1824 // parenthesized in macro definitions.
1825 if (ControllingExpr)
1826 ControllingExpr = ControllingExpr->IgnoreParens();
1827
1828 SourceRange SR = ControllingExpr
1829 ? ControllingExpr->getSourceRange()
1830 : ControllingType->getTypeLoc().getSourceRange();
1831 QualType QT = ControllingExpr ? ControllingExpr->getType()
1832 : ControllingType->getType();
1833
1834 return std::make_pair(SR, QT);
1835 };
1836
1837 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1838 // type compatible with at most one of the types named in its generic
1839 // association list."
1840 if (CompatIndices.size() > 1) {
1841 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1842 SourceRange SR = P.first;
1843 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1844 << SR << P.second << (unsigned)CompatIndices.size();
1845 for (unsigned I : CompatIndices) {
1846 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1847 diag::note_compat_assoc)
1848 << Types[I]->getTypeLoc().getSourceRange()
1849 << Types[I]->getType();
1850 }
1851 return ExprError();
1852 }
1853
1854 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1855 // its controlling expression shall have type compatible with exactly one of
1856 // the types named in its generic association list."
1857 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1858 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1859 SourceRange SR = P.first;
1860 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1861 return ExprError();
1862 }
1863
1864 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1865 // type name that is compatible with the type of the controlling expression,
1866 // then the result expression of the generic selection is the expression
1867 // in that generic association. Otherwise, the result expression of the
1868 // generic selection is the expression in the default generic association."
1869 unsigned ResultIndex =
1870 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1871
1872 if (ControllingExpr) {
1874 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1875 ContainsUnexpandedParameterPack, ResultIndex);
1876 }
1878 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1879 ContainsUnexpandedParameterPack, ResultIndex);
1880}
1881
1883 switch (Kind) {
1884 default:
1885 llvm_unreachable("unexpected TokenKind");
1886 case tok::kw___func__:
1887 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
1888 case tok::kw___FUNCTION__:
1890 case tok::kw___FUNCDNAME__:
1891 return PredefinedIdentKind::FuncDName; // [MS]
1892 case tok::kw___FUNCSIG__:
1893 return PredefinedIdentKind::FuncSig; // [MS]
1894 case tok::kw_L__FUNCTION__:
1895 return PredefinedIdentKind::LFunction; // [MS]
1896 case tok::kw_L__FUNCSIG__:
1897 return PredefinedIdentKind::LFuncSig; // [MS]
1898 case tok::kw___PRETTY_FUNCTION__:
1900 }
1901}
1902
1903/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1904/// to determine the value of a PredefinedExpr. This can be either a
1905/// block, lambda, captured statement, function, otherwise a nullptr.
1907 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
1908 DC = DC->getParent();
1909 return cast_or_null<Decl>(DC);
1910}
1911
1912/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1913/// location of the token and the offset of the ud-suffix within it.
1915 unsigned Offset) {
1916 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1917 S.getLangOpts());
1918}
1919
1920/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1921/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1923 IdentifierInfo *UDSuffix,
1924 SourceLocation UDSuffixLoc,
1925 ArrayRef<Expr*> Args,
1926 SourceLocation LitEndLoc) {
1927 assert(Args.size() <= 2 && "too many arguments for literal operator");
1928
1929 QualType ArgTy[2];
1930 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1931 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1932 if (ArgTy[ArgIdx]->isArrayType())
1933 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1934 }
1935
1936 DeclarationName OpName =
1938 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1939 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1940
1941 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1942 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1943 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1944 /*AllowStringTemplatePack*/ false,
1945 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1946 return ExprError();
1947
1948 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1949}
1950
1952 // StringToks needs backing storage as it doesn't hold array elements itself
1953 std::vector<Token> ExpandedToks;
1954 if (getLangOpts().MicrosoftExt)
1955 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
1956
1957 StringLiteralParser Literal(StringToks, PP,
1959 if (Literal.hadError)
1960 return ExprError();
1961
1962 SmallVector<SourceLocation, 4> StringTokLocs;
1963 for (const Token &Tok : StringToks)
1964 StringTokLocs.push_back(Tok.getLocation());
1965
1967 Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {},
1968 &StringTokLocs[0], StringTokLocs.size());
1969
1970 if (!Literal.getUDSuffix().empty()) {
1971 SourceLocation UDSuffixLoc =
1972 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1973 Literal.getUDSuffixOffset());
1974 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1975 }
1976
1977 return Lit;
1978}
1979
1980std::vector<Token>
1982 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
1983 // local macros that expand to string literals that may be concatenated.
1984 // These macros are expanded here (in Sema), because StringLiteralParser
1985 // (in Lex) doesn't know the enclosing function (because it hasn't been
1986 // parsed yet).
1987 assert(getLangOpts().MicrosoftExt);
1988
1989 // Note: Although function local macros are defined only inside functions,
1990 // we ensure a valid `CurrentDecl` even outside of a function. This allows
1991 // expansion of macros into empty string literals without additional checks.
1992 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
1993 if (!CurrentDecl)
1994 CurrentDecl = Context.getTranslationUnitDecl();
1995
1996 std::vector<Token> ExpandedToks;
1997 ExpandedToks.reserve(Toks.size());
1998 for (const Token &Tok : Toks) {
1999 if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2000 assert(tok::isStringLiteral(Tok.getKind()));
2001 ExpandedToks.emplace_back(Tok);
2002 continue;
2003 }
2004 if (isa<TranslationUnitDecl>(CurrentDecl))
2005 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2006 // Stringify predefined expression
2007 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2008 << Tok.getKind();
2009 SmallString<64> Str;
2010 llvm::raw_svector_ostream OS(Str);
2011 Token &Exp = ExpandedToks.emplace_back();
2012 Exp.startToken();
2013 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2014 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2015 OS << 'L';
2016 Exp.setKind(tok::wide_string_literal);
2017 } else {
2018 Exp.setKind(tok::string_literal);
2019 }
2020 OS << '"'
2022 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2023 << '"';
2024 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2025 }
2026 return ExpandedToks;
2027}
2028
2031 assert(!StringToks.empty() && "Must have at least one string!");
2032
2033 // StringToks needs backing storage as it doesn't hold array elements itself
2034 std::vector<Token> ExpandedToks;
2035 if (getLangOpts().MicrosoftExt)
2036 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2037
2038 StringLiteralParser Literal(StringToks, PP);
2039 if (Literal.hadError)
2040 return ExprError();
2041
2042 SmallVector<SourceLocation, 4> StringTokLocs;
2043 for (const Token &Tok : StringToks)
2044 StringTokLocs.push_back(Tok.getLocation());
2045
2046 QualType CharTy = Context.CharTy;
2048 if (Literal.isWide()) {
2049 CharTy = Context.getWideCharType();
2051 } else if (Literal.isUTF8()) {
2052 if (getLangOpts().Char8)
2053 CharTy = Context.Char8Ty;
2054 else if (getLangOpts().C23)
2055 CharTy = Context.UnsignedCharTy;
2057 } else if (Literal.isUTF16()) {
2058 CharTy = Context.Char16Ty;
2060 } else if (Literal.isUTF32()) {
2061 CharTy = Context.Char32Ty;
2063 } else if (Literal.isPascal()) {
2064 CharTy = Context.UnsignedCharTy;
2065 }
2066
2067 // Warn on u8 string literals before C++20 and C23, whose type
2068 // was an array of char before but becomes an array of char8_t.
2069 // In C++20, it cannot be used where a pointer to char is expected.
2070 // In C23, it might have an unexpected value if char was signed.
2071 if (Kind == StringLiteralKind::UTF8 &&
2073 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2074 : !getLangOpts().C23)) {
2075 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2076 ? diag::warn_cxx20_compat_utf8_string
2077 : diag::warn_c23_compat_utf8_string);
2078
2079 // Create removals for all 'u8' prefixes in the string literal(s). This
2080 // ensures C++20/C23 compatibility (but may change the program behavior when
2081 // built by non-Clang compilers for which the execution character set is
2082 // not always UTF-8).
2083 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2084 SourceLocation RemovalDiagLoc;
2085 for (const Token &Tok : StringToks) {
2086 if (Tok.getKind() == tok::utf8_string_literal) {
2087 if (RemovalDiagLoc.isInvalid())
2088 RemovalDiagLoc = Tok.getLocation();
2090 Tok.getLocation(),
2091 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2093 }
2094 }
2095 Diag(RemovalDiagLoc, RemovalDiag);
2096 }
2097
2098 QualType StrTy =
2099 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2100
2101 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2102 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2103 Kind, Literal.Pascal, StrTy,
2104 &StringTokLocs[0],
2105 StringTokLocs.size());
2106 if (Literal.getUDSuffix().empty())
2107 return Lit;
2108
2109 // We're building a user-defined literal.
2110 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2111 SourceLocation UDSuffixLoc =
2112 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2113 Literal.getUDSuffixOffset());
2114
2115 // Make sure we're allowed user-defined literals here.
2116 if (!UDLScope)
2117 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2118
2119 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2120 // operator "" X (str, len)
2121 QualType SizeType = Context.getSizeType();
2122
2123 DeclarationName OpName =
2125 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2126 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2127
2128 QualType ArgTy[] = {
2129 Context.getArrayDecayedType(StrTy), SizeType
2130 };
2131
2132 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2133 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2134 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2135 /*AllowStringTemplatePack*/ true,
2136 /*DiagnoseMissing*/ true, Lit)) {
2137
2138 case LOLR_Cooked: {
2139 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2140 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2141 StringTokLocs[0]);
2142 Expr *Args[] = { Lit, LenArg };
2143
2144 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2145 }
2146
2147 case LOLR_Template: {
2148 TemplateArgumentListInfo ExplicitArgs;
2149 TemplateArgument Arg(Lit);
2150 TemplateArgumentLocInfo ArgInfo(Lit);
2151 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2152 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2153 StringTokLocs.back(), &ExplicitArgs);
2154 }
2155
2157 TemplateArgumentListInfo ExplicitArgs;
2158
2159 unsigned CharBits = Context.getIntWidth(CharTy);
2160 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2161 llvm::APSInt Value(CharBits, CharIsUnsigned);
2162
2163 TemplateArgument TypeArg(CharTy);
2165 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2166
2167 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2168 Value = Lit->getCodeUnit(I);
2169 TemplateArgument Arg(Context, Value, CharTy);
2171 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2172 }
2173 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2174 StringTokLocs.back(), &ExplicitArgs);
2175 }
2176 case LOLR_Raw:
2178 llvm_unreachable("unexpected literal operator lookup result");
2179 case LOLR_Error:
2180 return ExprError();
2181 }
2182 llvm_unreachable("unexpected literal operator lookup result");
2183}
2184
2188 const CXXScopeSpec *SS) {
2189 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2190 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2191}
2192
2195 const DeclarationNameInfo &NameInfo,
2196 const CXXScopeSpec *SS, NamedDecl *FoundD,
2197 SourceLocation TemplateKWLoc,
2198 const TemplateArgumentListInfo *TemplateArgs) {
2201 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2202 TemplateArgs);
2203}
2204
2205// CUDA/HIP: Check whether a captured reference variable is referencing a
2206// host variable in a device or host device lambda.
2208 VarDecl *VD) {
2209 if (!S.getLangOpts().CUDA || !VD->hasInit())
2210 return false;
2211 assert(VD->getType()->isReferenceType());
2212
2213 // Check whether the reference variable is referencing a host variable.
2214 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2215 if (!DRE)
2216 return false;
2217 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2218 if (!Referee || !Referee->hasGlobalStorage() ||
2219 Referee->hasAttr<CUDADeviceAttr>())
2220 return false;
2221
2222 // Check whether the current function is a device or host device lambda.
2223 // Check whether the reference variable is a capture by getDeclContext()
2224 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2225 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2226 if (MD && MD->getParent()->isLambda() &&
2227 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2228 VD->getDeclContext() != MD)
2229 return true;
2230
2231 return false;
2232}
2233
2235 // A declaration named in an unevaluated operand never constitutes an odr-use.
2237 return NOUR_Unevaluated;
2238
2239 // C++2a [basic.def.odr]p4:
2240 // A variable x whose name appears as a potentially-evaluated expression e
2241 // is odr-used by e unless [...] x is a reference that is usable in
2242 // constant expressions.
2243 // CUDA/HIP:
2244 // If a reference variable referencing a host variable is captured in a
2245 // device or host device lambda, the value of the referee must be copied
2246 // to the capture and the reference variable must be treated as odr-use
2247 // since the value of the referee is not known at compile time and must
2248 // be loaded from the captured.
2249 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2250 if (VD->getType()->isReferenceType() &&
2251 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2253 VD->isUsableInConstantExpressions(Context))
2254 return NOUR_Constant;
2255 }
2256
2257 // All remaining non-variable cases constitute an odr-use. For variables, we
2258 // need to wait and see how the expression is used.
2259 return NOUR_None;
2260}
2261
2264 const DeclarationNameInfo &NameInfo,
2265 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2266 SourceLocation TemplateKWLoc,
2267 const TemplateArgumentListInfo *TemplateArgs) {
2268 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2269 NeedToCaptureVariable(D, NameInfo.getLoc());
2270
2272 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2273 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2275
2276 // C++ [except.spec]p17:
2277 // An exception-specification is considered to be needed when:
2278 // - in an expression, the function is the unique lookup result or
2279 // the selected member of a set of overloaded functions.
2280 //
2281 // We delay doing this until after we've built the function reference and
2282 // marked it as used so that:
2283 // a) if the function is defaulted, we get errors from defining it before /
2284 // instead of errors from computing its exception specification, and
2285 // b) if the function is a defaulted comparison, we can use the body we
2286 // build when defining it as input to the exception specification
2287 // computation rather than computing a new body.
2288 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2289 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2290 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2292 }
2293 }
2294
2295 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2297 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2299
2300 const auto *FD = dyn_cast<FieldDecl>(D);
2301 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2302 FD = IFD->getAnonField();
2303 if (FD) {
2304 UnusedPrivateFields.remove(FD);
2305 // Just in case we're building an illegal pointer-to-member.
2306 if (FD->isBitField())
2308 }
2309
2310 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2311 // designates a bit-field.
2312 if (const auto *BD = dyn_cast<BindingDecl>(D))
2313 if (const auto *BE = BD->getBinding())
2314 E->setObjectKind(BE->getObjectKind());
2315
2316 return E;
2317}
2318
2319void
2322 DeclarationNameInfo &NameInfo,
2323 const TemplateArgumentListInfo *&TemplateArgs) {
2324 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2325 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2326 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2327
2328 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2329 Id.TemplateId->NumArgs);
2330 translateTemplateArguments(TemplateArgsPtr, Buffer);
2331
2332 TemplateName TName = Id.TemplateId->Template.get();
2333 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2334 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2335 TemplateArgs = &Buffer;
2336 } else {
2337 NameInfo = GetNameFromUnqualifiedId(Id);
2338 TemplateArgs = nullptr;
2339 }
2340}
2341
2343 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2345 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2346 DeclContext *Ctx =
2347 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2348 if (!TC) {
2349 // Emit a special diagnostic for failed member lookups.
2350 // FIXME: computing the declaration context might fail here (?)
2351 if (Ctx)
2352 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2353 << SS.getRange();
2354 else
2355 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2356 return;
2357 }
2358
2359 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2360 bool DroppedSpecifier =
2361 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2362 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2363 ? diag::note_implicit_param_decl
2364 : diag::note_previous_decl;
2365 if (!Ctx)
2366 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2367 SemaRef.PDiag(NoteID));
2368 else
2369 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2370 << Typo << Ctx << DroppedSpecifier
2371 << SS.getRange(),
2372 SemaRef.PDiag(NoteID));
2373}
2374
2376 // During a default argument instantiation the CurContext points
2377 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2378 // function parameter list, hence add an explicit check.
2379 bool isDefaultArgument =
2380 !CodeSynthesisContexts.empty() &&
2381 CodeSynthesisContexts.back().Kind ==
2383 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2384 bool isInstance = CurMethod && CurMethod->isInstance() &&
2385 R.getNamingClass() == CurMethod->getParent() &&
2386 !isDefaultArgument;
2387
2388 // There are two ways we can find a class-scope declaration during template
2389 // instantiation that we did not find in the template definition: if it is a
2390 // member of a dependent base class, or if it is declared after the point of
2391 // use in the same class. Distinguish these by comparing the class in which
2392 // the member was found to the naming class of the lookup.
2393 unsigned DiagID = diag::err_found_in_dependent_base;
2394 unsigned NoteID = diag::note_member_declared_at;
2396 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2397 : diag::err_found_later_in_class;
2398 } else if (getLangOpts().MSVCCompat) {
2399 DiagID = diag::ext_found_in_dependent_base;
2400 NoteID = diag::note_dependent_member_use;
2401 }
2402
2403 if (isInstance) {
2404 // Give a code modification hint to insert 'this->'.
2405 Diag(R.getNameLoc(), DiagID)
2406 << R.getLookupName()
2407 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2409 } else {
2410 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2411 // they're not shadowed).
2412 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2413 }
2414
2415 for (const NamedDecl *D : R)
2416 Diag(D->getLocation(), NoteID);
2417
2418 // Return true if we are inside a default argument instantiation
2419 // and the found name refers to an instance member function, otherwise
2420 // the caller will try to create an implicit member call and this is wrong
2421 // for default arguments.
2422 //
2423 // FIXME: Is this special case necessary? We could allow the caller to
2424 // diagnose this.
2425 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2426 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2427 return true;
2428 }
2429
2430 // Tell the callee to try to recover.
2431 return false;
2432}
2433
2436 TemplateArgumentListInfo *ExplicitTemplateArgs,
2437 ArrayRef<Expr *> Args, DeclContext *LookupCtx,
2438 TypoExpr **Out) {
2439 DeclarationName Name = R.getLookupName();
2440
2441 unsigned diagnostic = diag::err_undeclared_var_use;
2442 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2443 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2444 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2445 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2446 diagnostic = diag::err_undeclared_use;
2447 diagnostic_suggest = diag::err_undeclared_use_suggest;
2448 }
2449
2450 // If the original lookup was an unqualified lookup, fake an
2451 // unqualified lookup. This is useful when (for example) the
2452 // original lookup would not have found something because it was a
2453 // dependent name.
2454 DeclContext *DC =
2455 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2456 while (DC) {
2457 if (isa<CXXRecordDecl>(DC)) {
2458 LookupQualifiedName(R, DC);
2459
2460 if (!R.empty()) {
2461 // Don't give errors about ambiguities in this lookup.
2463
2464 // If there's a best viable function among the results, only mention
2465 // that one in the notes.
2466 OverloadCandidateSet Candidates(R.getNameLoc(),
2468 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2470 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2471 OR_Success) {
2472 R.clear();
2473 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2474 R.resolveKind();
2475 }
2476
2478 }
2479
2480 R.clear();
2481 }
2482
2483 DC = DC->getLookupParent();
2484 }
2485
2486 // We didn't find anything, so try to correct for a typo.
2487 TypoCorrection Corrected;
2488 if (S && Out) {
2489 SourceLocation TypoLoc = R.getNameLoc();
2490 assert(!ExplicitTemplateArgs &&
2491 "Diagnosing an empty lookup with explicit template args!");
2492 *Out = CorrectTypoDelayed(
2493 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2494 [=](const TypoCorrection &TC) {
2495 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2496 diagnostic, diagnostic_suggest);
2497 },
2498 nullptr, CTK_ErrorRecovery, LookupCtx);
2499 if (*Out)
2500 return true;
2501 } else if (S && (Corrected =
2503 &SS, CCC, CTK_ErrorRecovery, LookupCtx))) {
2504 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2505 bool DroppedSpecifier =
2506 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2507 R.setLookupName(Corrected.getCorrection());
2508
2509 bool AcceptableWithRecovery = false;
2510 bool AcceptableWithoutRecovery = false;
2511 NamedDecl *ND = Corrected.getFoundDecl();
2512 if (ND) {
2513 if (Corrected.isOverloaded()) {
2517 for (NamedDecl *CD : Corrected) {
2518 if (FunctionTemplateDecl *FTD =
2519 dyn_cast<FunctionTemplateDecl>(CD))
2521 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2522 Args, OCS);
2523 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2524 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2526 Args, OCS);
2527 }
2528 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2529 case OR_Success:
2530 ND = Best->FoundDecl;
2531 Corrected.setCorrectionDecl(ND);
2532 break;
2533 default:
2534 // FIXME: Arbitrarily pick the first declaration for the note.
2535 Corrected.setCorrectionDecl(ND);
2536 break;
2537 }
2538 }
2539 R.addDecl(ND);
2540 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2541 CXXRecordDecl *Record = nullptr;
2542 if (Corrected.getCorrectionSpecifier()) {
2543 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2544 Record = Ty->getAsCXXRecordDecl();
2545 }
2546 if (!Record)
2547 Record = cast<CXXRecordDecl>(
2550 }
2551
2552 auto *UnderlyingND = ND->getUnderlyingDecl();
2553 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2554 isa<FunctionTemplateDecl>(UnderlyingND);
2555 // FIXME: If we ended up with a typo for a type name or
2556 // Objective-C class name, we're in trouble because the parser
2557 // is in the wrong place to recover. Suggest the typo
2558 // correction, but don't make it a fix-it since we're not going
2559 // to recover well anyway.
2560 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2561 getAsTypeTemplateDecl(UnderlyingND) ||
2562 isa<ObjCInterfaceDecl>(UnderlyingND);
2563 } else {
2564 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2565 // because we aren't able to recover.
2566 AcceptableWithoutRecovery = true;
2567 }
2568
2569 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2570 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2571 ? diag::note_implicit_param_decl
2572 : diag::note_previous_decl;
2573 if (SS.isEmpty())
2574 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2575 PDiag(NoteID), AcceptableWithRecovery);
2576 else
2577 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2578 << Name << computeDeclContext(SS, false)
2579 << DroppedSpecifier << SS.getRange(),
2580 PDiag(NoteID), AcceptableWithRecovery);
2581
2582 // Tell the callee whether to try to recover.
2583 return !AcceptableWithRecovery;
2584 }
2585 }
2586 R.clear();
2587
2588 // Emit a special diagnostic for failed member lookups.
2589 // FIXME: computing the declaration context might fail here (?)
2590 if (!SS.isEmpty()) {
2591 Diag(R.getNameLoc(), diag::err_no_member)
2592 << Name << computeDeclContext(SS, false)
2593 << SS.getRange();
2594 return true;
2595 }
2596
2597 // Give up, we can't recover.
2598 Diag(R.getNameLoc(), diagnostic) << Name;
2599 return true;
2600}
2601
2602/// In Microsoft mode, if we are inside a template class whose parent class has
2603/// dependent base classes, and we can't resolve an unqualified identifier, then
2604/// assume the identifier is a member of a dependent base class. We can only
2605/// recover successfully in static methods, instance methods, and other contexts
2606/// where 'this' is available. This doesn't precisely match MSVC's
2607/// instantiation model, but it's close enough.
2608static Expr *
2610 DeclarationNameInfo &NameInfo,
2611 SourceLocation TemplateKWLoc,
2612 const TemplateArgumentListInfo *TemplateArgs) {
2613 // Only try to recover from lookup into dependent bases in static methods or
2614 // contexts where 'this' is available.
2615 QualType ThisType = S.getCurrentThisType();
2616 const CXXRecordDecl *RD = nullptr;
2617 if (!ThisType.isNull())
2618 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2619 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2620 RD = MD->getParent();
2621 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2622 return nullptr;
2623
2624 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2625 // is available, suggest inserting 'this->' as a fixit.
2626 SourceLocation Loc = NameInfo.getLoc();
2627 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2628 DB << NameInfo.getName() << RD;
2629
2630 if (!ThisType.isNull()) {
2631 DB << FixItHint::CreateInsertion(Loc, "this->");
2633 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2634 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2635 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2636 }
2637
2638 // Synthesize a fake NNS that points to the derived class. This will
2639 // perform name lookup during template instantiation.
2640 CXXScopeSpec SS;
2641 auto *NNS =
2642 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2643 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2645 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2646 TemplateArgs);
2647}
2648
2651 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2652 bool HasTrailingLParen, bool IsAddressOfOperand,
2654 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2655 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2656 "cannot be direct & operand and have a trailing lparen");
2657 if (SS.isInvalid())
2658 return ExprError();
2659
2660 TemplateArgumentListInfo TemplateArgsBuffer;
2661
2662 // Decompose the UnqualifiedId into the following data.
2663 DeclarationNameInfo NameInfo;
2664 const TemplateArgumentListInfo *TemplateArgs;
2665 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2666
2667 DeclarationName Name = NameInfo.getName();
2668 IdentifierInfo *II = Name.getAsIdentifierInfo();
2669 SourceLocation NameLoc = NameInfo.getLoc();
2670
2671 if (II && II->isEditorPlaceholder()) {
2672 // FIXME: When typed placeholders are supported we can create a typed
2673 // placeholder expression node.
2674 return ExprError();
2675 }
2676
2677 // This specially handles arguments of attributes appertains to a type of C
2678 // struct field such that the name lookup within a struct finds the member
2679 // name, which is not the case for other contexts in C.
2680 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2681 // See if this is reference to a field of struct.
2682 LookupResult R(*this, NameInfo, LookupMemberName);
2683 // LookupName handles a name lookup from within anonymous struct.
2684 if (LookupName(R, S)) {
2685 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2686 QualType type = VD->getType().getNonReferenceType();
2687 // This will eventually be translated into MemberExpr upon
2688 // the use of instantiated struct fields.
2689 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2690 }
2691 }
2692 }
2693
2694 // Perform the required lookup.
2695 LookupResult R(*this, NameInfo,
2699 if (TemplateKWLoc.isValid() || TemplateArgs) {
2700 // Lookup the template name again to correctly establish the context in
2701 // which it was found. This is really unfortunate as we already did the
2702 // lookup to determine that it was a template name in the first place. If
2703 // this becomes a performance hit, we can work harder to preserve those
2704 // results until we get here but it's likely not worth it.
2705 AssumedTemplateKind AssumedTemplate;
2706 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2707 /*EnteringContext=*/false, TemplateKWLoc,
2708 &AssumedTemplate))
2709 return ExprError();
2710
2712 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2713 IsAddressOfOperand, TemplateArgs);
2714 } else {
2715 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2716 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2717 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2718
2719 // If the result might be in a dependent base class, this is a dependent
2720 // id-expression.
2722 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2723 IsAddressOfOperand, TemplateArgs);
2724
2725 // If this reference is in an Objective-C method, then we need to do
2726 // some special Objective-C lookup, too.
2727 if (IvarLookupFollowUp) {
2728 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2729 if (E.isInvalid())
2730 return ExprError();
2731
2732 if (Expr *Ex = E.getAs<Expr>())
2733 return Ex;
2734 }
2735 }
2736
2737 if (R.isAmbiguous())
2738 return ExprError();
2739
2740 // This could be an implicitly declared function reference if the language
2741 // mode allows it as a feature.
2742 if (R.empty() && HasTrailingLParen && II &&
2743 getLangOpts().implicitFunctionsAllowed()) {
2744 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2745 if (D) R.addDecl(D);
2746 }
2747
2748 // Determine whether this name might be a candidate for
2749 // argument-dependent lookup.
2750 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2751
2752 if (R.empty() && !ADL) {
2753 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2754 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2755 TemplateKWLoc, TemplateArgs))
2756 return E;
2757 }
2758
2759 // Don't diagnose an empty lookup for inline assembly.
2760 if (IsInlineAsmIdentifier)
2761 return ExprError();
2762
2763 // If this name wasn't predeclared and if this is not a function
2764 // call, diagnose the problem.
2765 TypoExpr *TE = nullptr;
2766 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2767 : nullptr);
2768 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2769 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2770 "Typo correction callback misconfigured");
2771 if (CCC) {
2772 // Make sure the callback knows what the typo being diagnosed is.
2773 CCC->setTypoName(II);
2774 if (SS.isValid())
2775 CCC->setTypoNNS(SS.getScopeRep());
2776 }
2777 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2778 // a template name, but we happen to have always already looked up the name
2779 // before we get here if it must be a template name.
2780 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2781 std::nullopt, nullptr, &TE)) {
2782 if (TE && KeywordReplacement) {
2783 auto &State = getTypoExprState(TE);
2784 auto BestTC = State.Consumer->getNextCorrection();
2785 if (BestTC.isKeyword()) {
2786 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2787 if (State.DiagHandler)
2788 State.DiagHandler(BestTC);
2789 KeywordReplacement->startToken();
2790 KeywordReplacement->setKind(II->getTokenID());
2791 KeywordReplacement->setIdentifierInfo(II);
2792 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2793 // Clean up the state associated with the TypoExpr, since it has
2794 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2795 clearDelayedTypo(TE);
2796 // Signal that a correction to a keyword was performed by returning a
2797 // valid-but-null ExprResult.
2798 return (Expr*)nullptr;
2799 }
2800 State.Consumer->resetCorrectionStream();
2801 }
2802 return TE ? TE : ExprError();
2803 }
2804
2805 assert(!R.empty() &&
2806 "DiagnoseEmptyLookup returned false but added no results");
2807
2808 // If we found an Objective-C instance variable, let
2809 // LookupInObjCMethod build the appropriate expression to
2810 // reference the ivar.
2811 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2812 R.clear();
2813 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2814 // In a hopelessly buggy code, Objective-C instance variable
2815 // lookup fails and no expression will be built to reference it.
2816 if (!E.isInvalid() && !E.get())
2817 return ExprError();
2818 return E;
2819 }
2820 }
2821
2822 // This is guaranteed from this point on.
2823 assert(!R.empty() || ADL);
2824
2825 // Check whether this might be a C++ implicit instance member access.
2826 // C++ [class.mfct.non-static]p3:
2827 // When an id-expression that is not part of a class member access
2828 // syntax and not used to form a pointer to member is used in the
2829 // body of a non-static member function of class X, if name lookup
2830 // resolves the name in the id-expression to a non-static non-type
2831 // member of some class C, the id-expression is transformed into a
2832 // class member access expression using (*this) as the
2833 // postfix-expression to the left of the . operator.
2834 //
2835 // But we don't actually need to do this for '&' operands if R
2836 // resolved to a function or overloaded function set, because the
2837 // expression is ill-formed if it actually works out to be a
2838 // non-static member function:
2839 //
2840 // C++ [expr.ref]p4:
2841 // Otherwise, if E1.E2 refers to a non-static member function. . .
2842 // [t]he expression can be used only as the left-hand operand of a
2843 // member function call.
2844 //
2845 // There are other safeguards against such uses, but it's important
2846 // to get this right here so that we don't end up making a
2847 // spuriously dependent expression if we're inside a dependent
2848 // instance method.
2849 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2850 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2851 S);
2852
2853 if (TemplateArgs || TemplateKWLoc.isValid()) {
2854
2855 // In C++1y, if this is a variable template id, then check it
2856 // in BuildTemplateIdExpr().
2857 // The single lookup result must be a variable template declaration.
2858 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2859 Id.TemplateId->Kind == TNK_Var_template) {
2860 assert(R.getAsSingle<VarTemplateDecl>() &&
2861 "There should only be one declaration found.");
2862 }
2863
2864 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2865 }
2866
2867 return BuildDeclarationNameExpr(SS, R, ADL);
2868}
2869
2871 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2872 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
2873 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2874 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
2875
2876 if (R.isAmbiguous())
2877 return ExprError();
2878
2880 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2881 NameInfo, /*TemplateArgs=*/nullptr);
2882
2883 if (R.empty()) {
2884 // Don't diagnose problems with invalid record decl, the secondary no_member
2885 // diagnostic during template instantiation is likely bogus, e.g. if a class
2886 // is invalid because it's derived from an invalid base class, then missing
2887 // members were likely supposed to be inherited.
2889 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2890 if (CD->isInvalidDecl())
2891 return ExprError();
2892 Diag(NameInfo.getLoc(), diag::err_no_member)
2893 << NameInfo.getName() << DC << SS.getRange();
2894 return ExprError();
2895 }
2896
2897 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2898 // Diagnose a missing typename if this resolved unambiguously to a type in
2899 // a dependent context. If we can recover with a type, downgrade this to
2900 // a warning in Microsoft compatibility mode.
2901 unsigned DiagID = diag::err_typename_missing;
2902 if (RecoveryTSI && getLangOpts().MSVCCompat)
2903 DiagID = diag::ext_typename_missing;
2905 auto D = Diag(Loc, DiagID);
2906 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2907 << SourceRange(Loc, NameInfo.getEndLoc());
2908
2909 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2910 // context.
2911 if (!RecoveryTSI)
2912 return ExprError();
2913
2914 // Only issue the fixit if we're prepared to recover.
2915 D << FixItHint::CreateInsertion(Loc, "typename ");
2916
2917 // Recover by pretending this was an elaborated type.
2919 TypeLocBuilder TLB;
2920 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2921
2926
2927 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2928
2929 return ExprEmpty();
2930 }
2931
2932 // If necessary, build an implicit class member access.
2933 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2935 /*TemplateKWLoc=*/SourceLocation(),
2936 R, /*TemplateArgs=*/nullptr,
2937 /*S=*/nullptr);
2938
2939 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
2940}
2941
2944 NestedNameSpecifier *Qualifier,
2945 NamedDecl *FoundDecl,
2946 NamedDecl *Member) {
2947 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2948 if (!RD)
2949 return From;
2950
2951 QualType DestRecordType;
2952 QualType DestType;
2953 QualType FromRecordType;
2954 QualType FromType = From->getType();
2955 bool PointerConversions = false;
2956 if (isa<FieldDecl>(Member)) {
2957 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2958 auto FromPtrType = FromType->getAs<PointerType>();
2959 DestRecordType = Context.getAddrSpaceQualType(
2960 DestRecordType, FromPtrType
2961 ? FromType->getPointeeType().getAddressSpace()
2962 : FromType.getAddressSpace());
2963
2964 if (FromPtrType) {
2965 DestType = Context.getPointerType(DestRecordType);
2966 FromRecordType = FromPtrType->getPointeeType();
2967 PointerConversions = true;
2968 } else {
2969 DestType = DestRecordType;
2970 FromRecordType = FromType;
2971 }
2972 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
2973 if (!Method->isImplicitObjectMemberFunction())
2974 return From;
2975
2976 DestType = Method->getThisType().getNonReferenceType();
2977 DestRecordType = Method->getFunctionObjectParameterType();
2978
2979 if (FromType->getAs<PointerType>()) {
2980 FromRecordType = FromType->getPointeeType();
2981 PointerConversions = true;
2982 } else {
2983 FromRecordType = FromType;
2984 DestType = DestRecordType;
2985 }
2986
2987 LangAS FromAS = FromRecordType.getAddressSpace();
2988 LangAS DestAS = DestRecordType.getAddressSpace();
2989 if (FromAS != DestAS) {
2990 QualType FromRecordTypeWithoutAS =
2991 Context.removeAddrSpaceQualType(FromRecordType);
2992 QualType FromTypeWithDestAS =
2993 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
2994 if (PointerConversions)
2995 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
2996 From = ImpCastExprToType(From, FromTypeWithDestAS,
2997 CK_AddressSpaceConversion, From->getValueKind())
2998 .get();
2999 }
3000 } else {
3001 // No conversion necessary.
3002 return From;
3003 }
3004
3005 if (DestType->isDependentType() || FromType->isDependentType())
3006 return From;
3007
3008 // If the unqualified types are the same, no conversion is necessary.
3009 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3010 return From;
3011
3012 SourceRange FromRange = From->getSourceRange();
3013 SourceLocation FromLoc = FromRange.getBegin();
3014
3015 ExprValueKind VK = From->getValueKind();
3016
3017 // C++ [class.member.lookup]p8:
3018 // [...] Ambiguities can often be resolved by qualifying a name with its
3019 // class name.
3020 //
3021 // If the member was a qualified name and the qualified referred to a
3022 // specific base subobject type, we'll cast to that intermediate type
3023 // first and then to the object in which the member is declared. That allows
3024 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3025 //
3026 // class Base { public: int x; };
3027 // class Derived1 : public Base { };
3028 // class Derived2 : public Base { };
3029 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3030 //
3031 // void VeryDerived::f() {
3032 // x = 17; // error: ambiguous base subobjects
3033 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3034 // }
3035 if (Qualifier && Qualifier->getAsType()) {
3036 QualType QType = QualType(Qualifier->getAsType(), 0);
3037 assert(QType->isRecordType() && "lookup done with non-record type");
3038
3039 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3040
3041 // In C++98, the qualifier type doesn't actually have to be a base
3042 // type of the object type, in which case we just ignore it.
3043 // Otherwise build the appropriate casts.
3044 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3045 CXXCastPath BasePath;
3046 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3047 FromLoc, FromRange, &BasePath))
3048 return ExprError();
3049
3050 if (PointerConversions)
3051 QType = Context.getPointerType(QType);
3052 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3053 VK, &BasePath).get();
3054
3055 FromType = QType;
3056 FromRecordType = QRecordType;
3057
3058 // If the qualifier type was the same as the destination type,
3059 // we're done.
3060 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3061 return From;
3062 }
3063 }
3064
3065 CXXCastPath BasePath;
3066 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3067 FromLoc, FromRange, &BasePath,
3068 /*IgnoreAccess=*/true))
3069 return ExprError();
3070
3071 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3072 VK, &BasePath);
3073}
3074
3076 const LookupResult &R,
3077 bool HasTrailingLParen) {
3078 // Only when used directly as the postfix-expression of a call.
3079 if (!HasTrailingLParen)
3080 return false;
3081
3082 // Never if a scope specifier was provided.
3083 if (SS.isNotEmpty())
3084 return false;
3085
3086 // Only in C++ or ObjC++.
3087 if (!getLangOpts().CPlusPlus)
3088 return false;
3089
3090 // Turn off ADL when we find certain kinds of declarations during
3091 // normal lookup:
3092 for (const NamedDecl *D : R) {
3093 // C++0x [basic.lookup.argdep]p3:
3094 // -- a declaration of a class member
3095 // Since using decls preserve this property, we check this on the
3096 // original decl.
3097 if (D->isCXXClassMember())
3098 return false;
3099
3100 // C++0x [basic.lookup.argdep]p3:
3101 // -- a block-scope function declaration that is not a
3102 // using-declaration
3103 // NOTE: we also trigger this for function templates (in fact, we
3104 // don't check the decl type at all, since all other decl types
3105 // turn off ADL anyway).
3106 if (isa<UsingShadowDecl>(D))
3107 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3109 return false;
3110
3111 // C++0x [basic.lookup.argdep]p3:
3112 // -- a declaration that is neither a function or a function
3113 // template
3114 // And also for builtin functions.
3115 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3116 // But also builtin functions.
3117 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3118 return false;
3119 } else if (!isa<FunctionTemplateDecl>(D))
3120 return false;
3121 }
3122
3123 return true;
3124}
3125
3126
3127/// Diagnoses obvious problems with the use of the given declaration
3128/// as an expression. This is only actually called for lookups that
3129/// were not overloaded, and it doesn't promise that the declaration
3130/// will in fact be used.
3132 bool AcceptInvalid) {
3133 if (D->isInvalidDecl() && !AcceptInvalid)
3134 return true;
3135
3136 if (isa<TypedefNameDecl>(D)) {
3137 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3138 return true;
3139 }
3140
3141 if (isa<ObjCInterfaceDecl>(D)) {
3142 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3143 return true;
3144 }
3145
3146 if (isa<NamespaceDecl>(D)) {
3147 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3148 return true;
3149 }
3150
3151 return false;
3152}
3153
3154// Certain multiversion types should be treated as overloaded even when there is
3155// only one result.
3157 assert(R.isSingleResult() && "Expected only a single result");
3158 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3159 return FD &&
3160 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3161}
3162
3164 LookupResult &R, bool NeedsADL,
3165 bool AcceptInvalidDecl) {
3166 // If this is a single, fully-resolved result and we don't need ADL,
3167 // just build an ordinary singleton decl ref.
3168 if (!NeedsADL && R.isSingleResult() &&
3172 R.getRepresentativeDecl(), nullptr,
3173 AcceptInvalidDecl);
3174
3175 // We only need to check the declaration if there's exactly one
3176 // result, because in the overloaded case the results can only be
3177 // functions and function templates.
3179 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3180 AcceptInvalidDecl))
3181 return ExprError();
3182
3183 // Otherwise, just build an unresolved lookup expression. Suppress
3184 // any lookup-related diagnostics; we'll hash these out later, when
3185 // we've picked a target.
3187
3190 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3191 /*KnownDependent=*/false);
3192
3193 return ULE;
3194}
3195
3197 SourceLocation loc,
3198 ValueDecl *var);
3199
3201 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3202 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3203 bool AcceptInvalidDecl) {
3204 assert(D && "Cannot refer to a NULL declaration");
3205 assert(!isa<FunctionTemplateDecl>(D) &&
3206 "Cannot refer unambiguously to a function template");
3207
3208 SourceLocation Loc = NameInfo.getLoc();
3209 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3210 // Recovery from invalid cases (e.g. D is an invalid Decl).
3211 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3212 // diagnostics, as invalid decls use int as a fallback type.
3213 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3214 }
3215
3216 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3217 // Specifically diagnose references to class templates that are missing
3218 // a template argument list.
3219 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3220 return ExprError();
3221 }
3222
3223 // Make sure that we're referring to a value.
3224 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3225 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3226 Diag(D->getLocation(), diag::note_declared_at);
3227 return ExprError();
3228 }
3229
3230 // Check whether this declaration can be used. Note that we suppress
3231 // this check when we're going to perform argument-dependent lookup
3232 // on this function name, because this might not be the function
3233 // that overload resolution actually selects.
3234 if (DiagnoseUseOfDecl(D, Loc))
3235 return ExprError();
3236
3237 auto *VD = cast<ValueDecl>(D);
3238
3239 // Only create DeclRefExpr's for valid Decl's.
3240 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3241 return ExprError();
3242
3243 // Handle members of anonymous structs and unions. If we got here,
3244 // and the reference is to a class member indirect field, then this
3245 // must be the subject of a pointer-to-member expression.
3246 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3247 IndirectField && !IndirectField->isCXXClassMember())
3249 IndirectField);
3250
3251 QualType type = VD->getType();
3252 if (type.isNull())
3253 return ExprError();
3254 ExprValueKind valueKind = VK_PRValue;
3255
3256 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3257 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3258 // is expanded by some outer '...' in the context of the use.
3259 type = type.getNonPackExpansionType();
3260
3261 switch (D->getKind()) {
3262 // Ignore all the non-ValueDecl kinds.
3263#define ABSTRACT_DECL(kind)
3264#define VALUE(type, base)
3265#define DECL(type, base) case Decl::type:
3266#include "clang/AST/DeclNodes.inc"
3267 llvm_unreachable("invalid value decl kind");
3268
3269 // These shouldn't make it here.
3270 case Decl::ObjCAtDefsField:
3271 llvm_unreachable("forming non-member reference to ivar?");
3272
3273 // Enum constants are always r-values and never references.
3274 // Unresolved using declarations are dependent.
3275 case Decl::EnumConstant:
3276 case Decl::UnresolvedUsingValue:
3277 case Decl::OMPDeclareReduction:
3278 case Decl::OMPDeclareMapper:
3279 valueKind = VK_PRValue;
3280 break;
3281
3282 // Fields and indirect fields that got here must be for
3283 // pointer-to-member expressions; we just call them l-values for
3284 // internal consistency, because this subexpression doesn't really
3285 // exist in the high-level semantics.
3286 case Decl::Field:
3287 case Decl::IndirectField:
3288 case Decl::ObjCIvar:
3289 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3290 "building reference to field in C?");
3291
3292 // These can't have reference type in well-formed programs, but
3293 // for internal consistency we do this anyway.
3294 type = type.getNonReferenceType();
3295 valueKind = VK_LValue;
3296 break;
3297
3298 // Non-type template parameters are either l-values or r-values
3299 // depending on the type.
3300 case Decl::NonTypeTemplateParm: {
3301 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3302 type = reftype->getPointeeType();
3303 valueKind = VK_LValue; // even if the parameter is an r-value reference
3304 break;
3305 }
3306
3307 // [expr.prim.id.unqual]p2:
3308 // If the entity is a template parameter object for a template
3309 // parameter of type T, the type of the expression is const T.
3310 // [...] The expression is an lvalue if the entity is a [...] template
3311 // parameter object.
3312 if (type->isRecordType()) {
3313 type = type.getUnqualifiedType().withConst();
3314 valueKind = VK_LValue;
3315 break;
3316 }
3317
3318 // For non-references, we need to strip qualifiers just in case
3319 // the template parameter was declared as 'const int' or whatever.
3320 valueKind = VK_PRValue;
3321 type = type.getUnqualifiedType();
3322 break;
3323 }
3324
3325 case Decl::Var:
3326 case Decl::VarTemplateSpecialization:
3327 case Decl::VarTemplatePartialSpecialization:
3328 case Decl::Decomposition:
3329 case Decl::OMPCapturedExpr:
3330 // In C, "extern void blah;" is valid and is an r-value.
3331 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3332 type->isVoidType()) {
3333 valueKind = VK_PRValue;
3334 break;
3335 }
3336 [[fallthrough]];
3337
3338 case Decl::ImplicitParam:
3339 case Decl::ParmVar: {
3340 // These are always l-values.
3341 valueKind = VK_LValue;
3342 type = type.getNonReferenceType();
3343
3344 // FIXME: Does the addition of const really only apply in
3345 // potentially-evaluated contexts? Since the variable isn't actually
3346 // captured in an unevaluated context, it seems that the answer is no.
3347 if (!isUnevaluatedContext()) {
3348 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3349 if (!CapturedType.isNull())
3350 type = CapturedType;
3351 }
3352
3353 break;
3354 }
3355
3356 case Decl::Binding:
3357 // These are always lvalues.
3358 valueKind = VK_LValue;
3359 type = type.getNonReferenceType();
3360 break;
3361
3362 case Decl::Function: {
3363 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3366 valueKind = VK_PRValue;
3367 break;
3368 }
3369 }
3370
3371 const FunctionType *fty = type->castAs<FunctionType>();
3372
3373 // If we're referring to a function with an __unknown_anytype
3374 // result type, make the entire expression __unknown_anytype.
3375 if (fty->getReturnType() == Context.UnknownAnyTy) {
3377 valueKind = VK_PRValue;
3378 break;
3379 }
3380
3381 // Functions are l-values in C++.
3382 if (getLangOpts().CPlusPlus) {
3383 valueKind = VK_LValue;
3384 break;
3385 }
3386
3387 // C99 DR 316 says that, if a function type comes from a
3388 // function definition (without a prototype), that type is only
3389 // used for checking compatibility. Therefore, when referencing
3390 // the function, we pretend that we don't have the full function
3391 // type.
3392 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3394 fty->getExtInfo());
3395
3396 // Functions are r-values in C.
3397 valueKind = VK_PRValue;
3398 break;
3399 }
3400
3401 case Decl::CXXDeductionGuide:
3402 llvm_unreachable("building reference to deduction guide");
3403
3404 case Decl::MSProperty:
3405 case Decl::MSGuid:
3406 case Decl::TemplateParamObject:
3407 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3408 // capture in OpenMP, or duplicated between host and device?
3409 valueKind = VK_LValue;
3410 break;
3411
3412 case Decl::UnnamedGlobalConstant:
3413 valueKind = VK_LValue;
3414 break;
3415
3416 case Decl::CXXMethod:
3417 // If we're referring to a method with an __unknown_anytype
3418 // result type, make the entire expression __unknown_anytype.
3419 // This should only be possible with a type written directly.
3420 if (const FunctionProtoType *proto =
3421 dyn_cast<FunctionProtoType>(VD->getType()))
3422 if (proto->getReturnType() == Context.UnknownAnyTy) {
3424 valueKind = VK_PRValue;
3425 break;
3426 }
3427
3428 // C++ methods are l-values if static, r-values if non-static.
3429 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3430 valueKind = VK_LValue;
3431 break;
3432 }
3433 [[fallthrough]];
3434
3435 case Decl::CXXConversion:
3436 case Decl::CXXDestructor:
3437 case Decl::CXXConstructor:
3438 valueKind = VK_PRValue;
3439 break;
3440 }
3441
3442 auto *E =
3443 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3444 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3445 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3446 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3447 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3448 // diagnostics).
3449 if (VD->isInvalidDecl() && E)
3450 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3451 return E;
3452}
3453
3454static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3456 Target.resize(CharByteWidth * (Source.size() + 1));
3457 char *ResultPtr = &Target[0];
3458 const llvm::UTF8 *ErrorPtr;
3459 bool success =
3460 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3461 (void)success;
3462 assert(success);
3463 Target.resize(ResultPtr - &Target[0]);
3464}
3465
3468 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3469 if (!currentDecl) {
3470 Diag(Loc, diag::ext_predef_outside_function);
3471 currentDecl = Context.getTranslationUnitDecl();
3472 }
3473
3474 QualType ResTy;
3475 StringLiteral *SL = nullptr;
3476 if (cast<DeclContext>(currentDecl)->isDependentContext())
3477 ResTy = Context.DependentTy;
3478 else {
3479 // Pre-defined identifiers are of type char[x], where x is the length of
3480 // the string.
3481 bool ForceElaboratedPrinting =
3482 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3483 auto Str =
3484 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3485 unsigned Length = Str.length();
3486
3487 llvm::APInt LengthI(32, Length + 1);
3490 ResTy =
3492 SmallString<32> RawChars;
3494 Str, RawChars);
3495 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3497 /*IndexTypeQuals*/ 0);
3499 /*Pascal*/ false, ResTy, Loc);
3500 } else {
3502 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3504 /*IndexTypeQuals*/ 0);
3506 /*Pascal*/ false, ResTy, Loc);
3507 }
3508 }
3509
3510 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3511 SL);
3512}
3513
3516}
3517
3519 SmallString<16> CharBuffer;
3520 bool Invalid = false;
3521 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3522 if (Invalid)
3523 return ExprError();
3524
3525 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3526 PP, Tok.getKind());
3527 if (Literal.hadError())
3528 return ExprError();
3529
3530 QualType Ty;
3531 if (Literal.isWide())
3532 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3533 else if (Literal.isUTF8() && getLangOpts().C23)
3534 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3535 else if (Literal.isUTF8() && getLangOpts().Char8)
3536 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3537 else if (Literal.isUTF16())
3538 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3539 else if (Literal.isUTF32())
3540 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3541 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3542 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3543 else
3544 Ty = Context.CharTy; // 'x' -> char in C++;
3545 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3546
3548 if (Literal.isWide())
3550 else if (Literal.isUTF16())
3552 else if (Literal.isUTF32())
3554 else if (Literal.isUTF8())
3556
3557 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3558 Tok.getLocation());
3559
3560 if (Literal.getUDSuffix().empty())
3561 return Lit;
3562
3563 // We're building a user-defined literal.
3564 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3565 SourceLocation UDSuffixLoc =
3566 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3567
3568 // Make sure we're allowed user-defined literals here.
3569 if (!UDLScope)
3570 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3571
3572 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3573 // operator "" X (ch)
3574 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3575 Lit, Tok.getLocation());
3576}
3577
3579 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3580 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3581 Context.IntTy, Loc);
3582}
3583
3586 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3587
3588 using llvm::APFloat;
3589 APFloat Val(Format);
3590
3591 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3592 if (RM == llvm::RoundingMode::Dynamic)
3593 RM = llvm::RoundingMode::NearestTiesToEven;
3594 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3595
3596 // Overflow is always an error, but underflow is only an error if
3597 // we underflowed to zero (APFloat reports denormals as underflow).
3598 if ((result & APFloat::opOverflow) ||
3599 ((result & APFloat::opUnderflow) && Val.isZero())) {
3600 unsigned diagnostic;
3601 SmallString<20> buffer;
3602 if (result & APFloat::opOverflow) {
3603 diagnostic = diag::warn_float_overflow;
3604 APFloat::getLargest(Format).toString(buffer);
3605 } else {
3606 diagnostic = diag::warn_float_underflow;
3607 APFloat::getSmallest(Format).toString(buffer);
3608 }
3609
3610 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3611 }
3612
3613 bool isExact = (result == APFloat::opOK);
3614 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3615}
3616
3618 assert(E && "Invalid expression");
3619
3620 if (E->isValueDependent())
3621 return false;
3622
3623 QualType QT = E->getType();
3624 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3625 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3626 return true;
3627 }
3628
3629 llvm::APSInt ValueAPS;
3631
3632 if (R.isInvalid())
3633 return true;
3634
3635 // GCC allows the value of unroll count to be 0.
3636 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3637 // "The values of 0 and 1 block any unrolling of the loop."
3638 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3639 // '#pragma unroll' cases.
3640 bool ValueIsPositive =
3641 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3642 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3643 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3644 << toString(ValueAPS, 10) << ValueIsPositive;
3645 return true;
3646 }
3647
3648 return false;
3649}
3650
3652 // Fast path for a single digit (which is quite common). A single digit
3653 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3654 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3655 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3656 return ActOnIntegerConstant(Tok.getLocation(), Val);
3657 }
3658
3659 SmallString<128> SpellingBuffer;
3660 // NumericLiteralParser wants to overread by one character. Add padding to
3661 // the buffer in case the token is copied to the buffer. If getSpelling()
3662 // returns a StringRef to the memory buffer, it should have a null char at
3663 // the EOF, so it is also safe.
3664 SpellingBuffer.resize(Tok.getLength() + 1);
3665
3666 // Get the spelling of the token, which eliminates trigraphs, etc.
3667 bool Invalid = false;
3668 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3669 if (Invalid)
3670 return ExprError();
3671
3672 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3675 if (Literal.hadError)
3676 return ExprError();
3677
3678 if (Literal.hasUDSuffix()) {
3679 // We're building a user-defined literal.
3680 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3681 SourceLocation UDSuffixLoc =
3682 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3683
3684 // Make sure we're allowed user-defined literals here.
3685 if (!UDLScope)
3686 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3687
3688 QualType CookedTy;
3689 if (Literal.isFloatingLiteral()) {
3690 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3691 // long double, the literal is treated as a call of the form
3692 // operator "" X (f L)
3693 CookedTy = Context.LongDoubleTy;
3694 } else {
3695 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3696 // unsigned long long, the literal is treated as a call of the form
3697 // operator "" X (n ULL)
3698 CookedTy = Context.UnsignedLongLongTy;
3699 }
3700
3701 DeclarationName OpName =
3703 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3704 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3705
3706 SourceLocation TokLoc = Tok.getLocation();
3707
3708 // Perform literal operator lookup to determine if we're building a raw
3709 // literal or a cooked one.
3710 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3711 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3712 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3713 /*AllowStringTemplatePack*/ false,
3714 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3716 // Lookup failure for imaginary constants isn't fatal, there's still the
3717 // GNU extension producing _Complex types.
3718 break;
3719 case LOLR_Error:
3720 return ExprError();
3721 case LOLR_Cooked: {
3722 Expr *Lit;
3723 if (Literal.isFloatingLiteral()) {
3724 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3725 } else {
3726 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3727 if (Literal.GetIntegerValue(ResultVal))
3728 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3729 << /* Unsigned */ 1;
3730 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3731 Tok.getLocation());
3732 }
3733 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3734 }
3735
3736 case LOLR_Raw: {
3737 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3738 // literal is treated as a call of the form
3739 // operator "" X ("n")
3740 unsigned Length = Literal.getUDSuffixOffset();
3743 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3744 Expr *Lit =
3745 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3747 /*Pascal*/ false, StrTy, &TokLoc, 1);
3748 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3749 }
3750
3751 case LOLR_Template: {
3752 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3753 // template), L is treated as a call fo the form
3754 // operator "" X <'c1', 'c2', ... 'ck'>()
3755 // where n is the source character sequence c1 c2 ... ck.
3756 TemplateArgumentListInfo ExplicitArgs;
3757 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3758 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3759 llvm::APSInt Value(CharBits, CharIsUnsigned);
3760 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3761 Value = TokSpelling[I];
3764 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3765 }
3766 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
3767 &ExplicitArgs);
3768 }
3770 llvm_unreachable("unexpected literal operator lookup result");
3771 }
3772 }
3773
3774 Expr *Res;
3775
3776 if (Literal.isFixedPointLiteral()) {
3777 QualType Ty;
3778
3779 if (Literal.isAccum) {
3780 if (Literal.isHalf) {
3781 Ty = Context.ShortAccumTy;
3782 } else if (Literal.isLong) {
3783 Ty = Context.LongAccumTy;
3784 } else {
3785 Ty = Context.AccumTy;
3786 }
3787 } else if (Literal.isFract) {
3788 if (Literal.isHalf) {
3789 Ty = Context.ShortFractTy;
3790 } else if (Literal.isLong) {
3791 Ty = Context.LongFractTy;
3792 } else {
3793 Ty = Context.FractTy;
3794 }
3795 }
3796
3797 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3798
3799 bool isSigned = !Literal.isUnsigned;
3800 unsigned scale = Context.getFixedPointScale(Ty);
3801 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3802
3803 llvm::APInt Val(bit_width, 0, isSigned);
3804 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3805 bool ValIsZero = Val.isZero() && !Overflowed;
3806
3807 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3808 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3809 // Clause 6.4.4 - The value of a constant shall be in the range of
3810 // representable values for its type, with exception for constants of a
3811 // fract type with a value of exactly 1; such a constant shall denote
3812 // the maximal value for the type.
3813 --Val;
3814 else if (Val.ugt(MaxVal) || Overflowed)
3815 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3816
3818 Tok.getLocation(), scale);
3819 } else if (Literal.isFloatingLiteral()) {
3820 QualType Ty;
3821 if (Literal.isHalf){
3822 if (getLangOpts().HLSL ||
3823 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3824 Ty = Context.HalfTy;
3825 else {
3826 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3827 return ExprError();
3828 }
3829 } else if (Literal.isFloat)
3830 Ty = Context.FloatTy;
3831 else if (Literal.isLong)
3833 else if (Literal.isFloat16)
3834 Ty = Context.Float16Ty;
3835 else if (Literal.isFloat128)
3836 Ty = Context.Float128Ty;
3837 else if (getLangOpts().HLSL)
3838 Ty = Context.FloatTy;
3839 else
3840 Ty = Context.DoubleTy;
3841
3842 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3843
3844 if (Ty == Context.DoubleTy) {
3845 if (getLangOpts().SinglePrecisionConstants) {
3846 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3847 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3848 }
3849 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3850 "cl_khr_fp64", getLangOpts())) {
3851 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3852 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3854 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3855 }
3856 }
3857 } else if (!Literal.isIntegerLiteral()) {
3858 return ExprError();
3859 } else {
3860 QualType Ty;
3861
3862 // 'z/uz' literals are a C++23 feature.
3863 if (Literal.isSizeT)
3866 ? diag::warn_cxx20_compat_size_t_suffix
3867 : diag::ext_cxx23_size_t_suffix
3868 : diag::err_cxx23_size_t_suffix);
3869
3870 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
3871 // but we do not currently support the suffix in C++ mode because it's not
3872 // entirely clear whether WG21 will prefer this suffix to return a library
3873 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
3874 // literals are a C++ extension.
3875 if (Literal.isBitInt)
3876 PP.Diag(Tok.getLocation(),
3877 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
3878 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
3879 : diag::ext_c23_bitint_suffix);
3880
3881 // Get the value in the widest-possible width. What is "widest" depends on
3882 // whether the literal is a bit-precise integer or not. For a bit-precise
3883 // integer type, try to scan the source to determine how many bits are
3884 // needed to represent the value. This may seem a bit expensive, but trying
3885 // to get the integer value from an overly-wide APInt is *extremely*
3886 // expensive, so the naive approach of assuming
3887 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3888 unsigned BitsNeeded =
3889 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3890 Literal.getLiteralDigits(), Literal.getRadix())
3892 llvm::APInt ResultVal(BitsNeeded, 0);
3893
3894 if (Literal.GetIntegerValue(ResultVal)) {
3895 // If this value didn't fit into uintmax_t, error and force to ull.
3896 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3897 << /* Unsigned */ 1;
3899 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3900 "long long is not intmax_t?");
3901 } else {
3902 // If this value fits into a ULL, try to figure out what else it fits into
3903 // according to the rules of C99 6.4.4.1p5.
3904
3905 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3906 // be an unsigned int.
3907 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3908
3909 // HLSL doesn't really have `long` or `long long`. We support the `ll`
3910 // suffix for portability of code with C++, but both `l` and `ll` are
3911 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
3912 // same.
3913 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
3914 Literal.isLong = true;
3915 Literal.isLongLong = false;
3916 }
3917
3918 // Check from smallest to largest, picking the smallest type we can.
3919 unsigned Width = 0;
3920
3921 // Microsoft specific integer suffixes are explicitly sized.
3922 if (Literal.MicrosoftInteger) {
3923 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3924 Width = 8;
3925 Ty = Context.CharTy;
3926 } else {
3927 Width = Literal.MicrosoftInteger;
3928 Ty = Context.getIntTypeForBitwidth(Width,
3929 /*Signed=*/!Literal.isUnsigned);
3930 }
3931 }
3932
3933 // Bit-precise integer literals are automagically-sized based on the
3934 // width required by the literal.
3935 if (Literal.isBitInt) {
3936 // The signed version has one more bit for the sign value. There are no
3937 // zero-width bit-precise integers, even if the literal value is 0.
3938 Width = std::max(ResultVal.getActiveBits(), 1u) +
3939 (Literal.isUnsigned ? 0u : 1u);
3940
3941 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
3942 // and reset the type to the largest supported width.
3943 unsigned int MaxBitIntWidth =
3945 if (Width > MaxBitIntWidth) {
3946 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3947 << Literal.isUnsigned;
3948 Width = MaxBitIntWidth;
3949 }
3950
3951 // Reset the result value to the smaller APInt and select the correct
3952 // type to be used. Note, we zext even for signed values because the
3953 // literal itself is always an unsigned value (a preceeding - is a
3954 // unary operator, not part of the literal).
3955 ResultVal = ResultVal.zextOrTrunc(Width);
3956 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
3957 }
3958
3959 // Check C++23 size_t literals.
3960 if (Literal.isSizeT) {
3961 assert(!Literal.MicrosoftInteger &&
3962 "size_t literals can't be Microsoft literals");
3963 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3965
3966 // Does it fit in size_t?
3967 if (ResultVal.isIntN(SizeTSize)) {
3968 // Does it fit in ssize_t?
3969 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3971 else if (AllowUnsigned)
3972 Ty = Context.getSizeType();
3973 Width = SizeTSize;
3974 }
3975 }
3976
3977 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3978 !Literal.isSizeT) {
3979 // Are int/unsigned possibilities?
3980 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3981
3982 // Does it fit in a unsigned int?
3983 if (ResultVal.isIntN(IntSize)) {
3984 // Does it fit in a signed int?
3985 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3986 Ty = Context.IntTy;
3987 else if (AllowUnsigned)
3989 Width = IntSize;
3990 }
3991 }
3992
3993 // Are long/unsigned long possibilities?
3994 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
3995 unsigned LongSize = Context.getTargetInfo().getLongWidth();
3996
3997 // Does it fit in a unsigned long?
3998 if (ResultVal.isIntN(LongSize)) {
3999 // Does it fit in a signed long?
4000 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4001 Ty = Context.LongTy;
4002 else if (AllowUnsigned)
4004 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4005 // is compatible.
4006 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4007 const unsigned LongLongSize =
4009 Diag(Tok.getLocation(),
4011 ? Literal.isLong
4012 ? diag::warn_old_implicitly_unsigned_long_cxx
4013 : /*C++98 UB*/ diag::
4014 ext_old_implicitly_unsigned_long_cxx
4015 : diag::warn_old_implicitly_unsigned_long)
4016 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4017 : /*will be ill-formed*/ 1);
4019 }
4020 Width = LongSize;
4021 }
4022 }
4023
4024 // Check long long if needed.
4025 if (Ty.isNull() && !Literal.isSizeT) {
4026 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4027
4028 // Does it fit in a unsigned long long?
4029 if (ResultVal.isIntN(LongLongSize)) {
4030 // Does it fit in a signed long long?
4031 // To be compatible with MSVC, hex integer literals ending with the
4032 // LL or i64 suffix are always signed in Microsoft mode.
4033 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4034 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4035 Ty = Context.LongLongTy;
4036 else if (AllowUnsigned)
4038 Width = LongLongSize;
4039
4040 // 'long long' is a C99 or C++11 feature, whether the literal
4041 // explicitly specified 'long long' or we needed the extra width.
4042 if (getLangOpts().CPlusPlus)
4043 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4044 ? diag::warn_cxx98_compat_longlong
4045 : diag::ext_cxx11_longlong);
4046 else if (!getLangOpts().C99)
4047 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4048 }
4049 }
4050
4051 // If we still couldn't decide a type, we either have 'size_t' literal
4052 // that is out of range, or a decimal literal that does not fit in a
4053 // signed long long and has no U suffix.
4054 if (Ty.isNull()) {
4055 if (Literal.isSizeT)
4056 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4057 << Literal.isUnsigned;
4058 else
4059 Diag(Tok.getLocation(),
4060 diag::ext_integer_literal_too_large_for_signed);
4063 }
4064
4065 if (ResultVal.getBitWidth() != Width)
4066 ResultVal = ResultVal.trunc(Width);
4067 }
4068 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4069 }
4070
4071 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4072 if (Literal.isImaginary) {
4073 Res = new (Context) ImaginaryLiteral(Res,
4075
4076 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4077 }
4078 return Res;
4079}
4080
4082 assert(E && "ActOnParenExpr() missing expr");
4083 QualType ExprTy = E->getType();
4084 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4085 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4086 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4087 return new (Context) ParenExpr(L, R, E);
4088}
4089
4092 SourceRange ArgRange) {
4093 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4094 // scalar or vector data type argument..."
4095 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4096 // type (C99 6.2.5p18) or void.
4097 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4098 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4099 << T << ArgRange;
4100 return true;
4101 }
4102
4103 assert((T->isVoidType() || !T->isIncompleteType()) &&
4104 "Scalar types should always be complete");
4105 return false;
4106}
4107
4110 SourceRange ArgRange) {
4111 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4112 if (!T->isVectorType() && !T->isSizelessVectorType())
4113 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4114 << ""
4115 << "__builtin_vectorelements" << T << ArgRange;
4116
4117 return false;
4118}
4119
4122 SourceRange ArgRange) {
4123 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4124 return true;
4125
4126 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4128 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4129 return true;
4130 }
4131
4132 return false;
4133}
4134
4137 SourceRange ArgRange,
4138 UnaryExprOrTypeTrait TraitKind) {
4139 // Invalid types must be hard errors for SFINAE in C++.
4140 if (S.LangOpts.CPlusPlus)
4141 return true;
4142
4143 // C99 6.5.3.4p1:
4144 if (T->isFunctionType() &&
4145 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4146 TraitKind == UETT_PreferredAlignOf)) {
4147 // sizeof(function)/alignof(function) is allowed as an extension.
4148 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4149 << getTraitSpelling(TraitKind) << ArgRange;
4150 return false;
4151 }
4152
4153 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4154 // this is an error (OpenCL v1.1 s6.3.k)
4155 if (T->isVoidType()) {
4156 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4157 : diag::ext_sizeof_alignof_void_type;
4158 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4159 return false;
4160 }
4161
4162 return true;
4163}
4164
4167 SourceRange ArgRange,
4168 UnaryExprOrTypeTrait TraitKind) {
4169 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4170 // runtime doesn't allow it.
4172 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4173 << T << (TraitKind == UETT_SizeOf)
4174 << ArgRange;
4175 return true;
4176 }
4177
4178 return false;
4179}
4180
4181/// Check whether E is a pointer from a decayed array type (the decayed
4182/// pointer type is equal to T) and emit a warning if it is.
4184 const Expr *E) {
4185 // Don't warn if the operation changed the type.
4186 if (T != E->getType())
4187 return;
4188
4189 // Now look for array decays.
4190 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4191 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4192 return;
4193
4194 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4195 << ICE->getType()
4196 << ICE->getSubExpr()->getType();
4197}
4198
4200 UnaryExprOrTypeTrait ExprKind) {
4201 QualType ExprTy = E->getType();
4202 assert(!ExprTy->isReferenceType());
4203
4204 bool IsUnevaluatedOperand =
4205 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4206 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4207 ExprKind == UETT_VecStep);
4208 if (IsUnevaluatedOperand) {
4210 if (Result.isInvalid())
4211 return true;
4212 E = Result.get();
4213 }
4214
4215 // The operand for sizeof and alignof is in an unevaluated expression context,
4216 // so side effects could result in unintended consequences.
4217 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4218 // used to build SFINAE gadgets.
4219 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4220 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4222 !E->getType()->isVariableArrayType() &&
4223 E->HasSideEffects(Context, false))
4224 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4225
4226 if (ExprKind == UETT_VecStep)
4227 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4228 E->getSourceRange());
4229
4230 if (ExprKind == UETT_VectorElements)
4231 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4232 E->getSourceRange());
4233
4234 // Explicitly list some types as extensions.
4235 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4236 E->getSourceRange(), ExprKind))
4237 return false;
4238
4239 // WebAssembly tables are always illegal operands to unary expressions and
4240 // type traits.
4241 if (Context.getTargetInfo().getTriple().isWasm() &&
4243 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4244 << getTraitSpelling(ExprKind);
4245 return true;
4246 }
4247
4248 // 'alignof' applied to an expression only requires the base element type of
4249 // the expression to be complete. 'sizeof' requires the expression's type to
4250 // be complete (and will attempt to complete it if it's an array of unknown
4251 // bound).
4252 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4255 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4256 getTraitSpelling(ExprKind), E->getSourceRange()))
4257 return true;
4258 } else {
4260 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4261 getTraitSpelling(ExprKind), E->getSourceRange()))
4262 return true;
4263 }
4264
4265 // Completing the expression's type may have changed it.
4266 ExprTy = E->getType();
4267 assert(!ExprTy->isReferenceType());
4268
4269 if (ExprTy->isFunctionType()) {
4270 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4271 << getTraitSpelling(ExprKind) << E->getSourceRange();
4272 return true;
4273 }
4274
4275 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4276 E->getSourceRange(), ExprKind))
4277 return true;
4278
4279 if (ExprKind == UETT_SizeOf) {
4280 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4281 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4282 QualType OType = PVD->getOriginalType();
4283 QualType Type = PVD->getType();
4284 if (Type->isPointerType() && OType->isArrayType()) {
4285 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4286 << Type << OType;
4287 Diag(PVD->getLocation(), diag::note_declared_at);
4288 }
4289 }
4290 }
4291
4292 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4293 // decays into a pointer and returns an unintended result. This is most
4294 // likely a typo for "sizeof(array) op x".
4295 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4296 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4297 BO->getLHS());
4298 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4299 BO->getRHS());
4300 }
4301 }
4302
4303 return false;
4304}
4305
4306static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4307 // Cannot know anything else if the expression is dependent.
4308 if (E->isTypeDependent())
4309 return false;
4310
4311 if (E->getObjectKind() == OK_BitField) {
4312 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4313 << 1 << E->getSourceRange();
4314 return true;
4315 }
4316
4317 ValueDecl *D = nullptr;
4318 Expr *Inner = E->IgnoreParens();
4319 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4320 D = DRE->getDecl();
4321 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4322 D = ME->getMemberDecl();
4323 }
4324
4325 // If it's a field, require the containing struct to have a
4326 // complete definition so that we can compute the layout.
4327 //
4328 // This can happen in C++11 onwards, either by naming the member
4329 // in a way that is not transformed into a member access expression
4330 // (in an unevaluated operand, for instance), or by naming the member
4331 // in a trailing-return-type.
4332 //
4333 // For the record, since __alignof__ on expressions is a GCC
4334 // extension, GCC seems to permit this but always gives the
4335 // nonsensical answer 0.
4336 //
4337 // We don't really need the layout here --- we could instead just
4338 // directly check for all the appropriate alignment-lowing
4339 // attributes --- but that would require duplicating a lot of
4340 // logic that just isn't worth duplicating for such a marginal
4341 // use-case.
4342 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4343 // Fast path this check, since we at least know the record has a
4344 // definition if we can find a member of it.
4345 if (!FD->getParent()->isCompleteDefinition()) {
4346 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4347 << E->getSourceRange();
4348 return true;
4349 }
4350
4351 // Otherwise, if it's a field, and the field doesn't have
4352 // reference type, then it must have a complete type (or be a
4353 // flexible array member, which we explicitly want to
4354 // white-list anyway), which makes the following checks trivial.
4355 if (!FD->getType()->isReferenceType())
4356 return false;
4357 }
4358
4359 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4360}
4361
4363 E = E->IgnoreParens();
4364
4365 // Cannot know anything else if the expression is dependent.
4366 if (E->isTypeDependent())
4367 return false;
4368
4369 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4370}
4371
4373 CapturingScopeInfo *CSI) {
4374 assert(T->isVariablyModifiedType());
4375 assert(CSI != nullptr);
4376
4377 // We're going to walk down into the type and look for VLA expressions.
4378 do {
4379 const Type *Ty = T.getTypePtr();
4380 switch (Ty->getTypeClass()) {
4381#define TYPE(Class, Base)
4382#define ABSTRACT_TYPE(Class, Base)
4383#define NON_CANONICAL_TYPE(Class, Base)
4384#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4385#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4386#include "clang/AST/TypeNodes.inc"
4387 T = QualType();
4388 break;
4389 // These types are never variably-modified.
4390 case Type::Builtin:
4391 case Type::Complex:
4392 case Type::Vector:
4393 case Type::ExtVector:
4394 case Type::ConstantMatrix:
4395 case Type::Record:
4396 case Type::Enum:
4397 case Type::TemplateSpecialization:
4398 case Type::ObjCObject:
4399 case Type::ObjCInterface:
4400 case Type::ObjCObjectPointer:
4401 case Type::ObjCTypeParam:
4402 case Type::Pipe:
4403 case Type::BitInt:
4404 llvm_unreachable("type class is never variably-modified!");
4405 case Type::Elaborated:
4406 T = cast<ElaboratedType>(Ty)->getNamedType();
4407 break;
4408 case Type::Adjusted:
4409 T = cast<AdjustedType>(Ty)->getOriginalType();
4410 break;
4411 case Type::Decayed:
4412 T = cast<DecayedType>(Ty)->getPointeeType();
4413 break;
4414 case Type::ArrayParameter:
4415 T = cast<ArrayParameterType>(Ty)->getElementType();
4416 break;
4417 case Type::Pointer:
4418 T = cast<PointerType>(Ty)->getPointeeType();
4419 break;
4420 case Type::BlockPointer:
4421 T = cast<BlockPointerType>(Ty)->getPointeeType();
4422 break;
4423 case Type::LValueReference:
4424 case Type::RValueReference:
4425 T = cast<ReferenceType>(Ty)->getPointeeType();
4426 break;
4427 case Type::MemberPointer:
4428 T = cast<MemberPointerType>(Ty)->getPointeeType();
4429 break;
4430 case Type::ConstantArray:
4431 case Type::IncompleteArray:
4432 // Losing element qualification here is fine.
4433 T = cast<ArrayType>(Ty)->getElementType();
4434 break;
4435 case Type::VariableArray: {
4436 // Losing element qualification here is fine.
4437 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4438
4439 // Unknown size indication requires no size computation.
4440 // Otherwise, evaluate and record it.
4441 auto Size = VAT->getSizeExpr();
4442 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4443 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4444 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4445
4446 T = VAT->getElementType();
4447 break;
4448 }
4449 case Type::FunctionProto:
4450 case Type::FunctionNoProto:
4451 T = cast<FunctionType>(Ty)->getReturnType();
4452 break;
4453 case Type::Paren:
4454 case Type::TypeOf:
4455 case Type::UnaryTransform:
4456 case Type::Attributed:
4457 case Type::BTFTagAttributed:
4458 case Type::SubstTemplateTypeParm:
4459 case Type::MacroQualified:
4460 case Type::CountAttributed:
4461 // Keep walking after single level desugaring.
4462 T = T.getSingleStepDesugaredType(Context);
4463 break;
4464 case Type::Typedef:
4465 T = cast<TypedefType>(Ty)->desugar();
4466 break;
4467 case Type::Decltype:
4468 T = cast<DecltypeType>(Ty)->desugar();
4469 break;
4470 case Type::PackIndexing:
4471 T = cast<PackIndexingType>(Ty)->desugar();
4472 break;
4473 case Type::Using:
4474 T = cast<UsingType>(Ty)->desugar();
4475 break;
4476 case Type::Auto:
4477 case Type::DeducedTemplateSpecialization:
4478 T = cast<DeducedType>(Ty)->getDeducedType();
4479 break;
4480 case Type::TypeOfExpr:
4481 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4482 break;
4483 case Type::Atomic:
4484 T = cast<AtomicType>(Ty)->getValueType();
4485 break;
4486 }
4487 } while (!T.isNull() && T->isVariablyModifiedType());
4488}
4489
4491 SourceLocation OpLoc,
4492 SourceRange ExprRange,
4493 UnaryExprOrTypeTrait ExprKind,
4494 StringRef KWName) {
4495 if (ExprType->isDependentType())
4496 return false;
4497
4498 // C++ [expr.sizeof]p2:
4499 // When applied to a reference or a reference type, the result
4500 // is the size of the referenced type.
4501 // C++11 [expr.alignof]p3:
4502 // When alignof is applied to a reference type, the result
4503 // shall be the alignment of the referenced type.
4504 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4505 ExprType = Ref->getPointeeType();
4506
4507 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4508 // When alignof or _Alignof is applied to an array type, the result
4509 // is the alignment of the element type.
4510 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4511 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4512 // If the trait is 'alignof' in C before C2y, the ability to apply the
4513 // trait to an incomplete array is an extension.
4514 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4515 ExprType->isIncompleteArrayType())
4516 Diag(OpLoc, getLangOpts().C2y
4517 ? diag::warn_c2y_compat_alignof_incomplete_array
4518 : diag::ext_c2y_alignof_incomplete_array);
4519 ExprType = Context.getBaseElementType(ExprType);
4520 }
4521
4522 if (ExprKind == UETT_VecStep)
4523 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4524
4525 if (ExprKind == UETT_VectorElements)
4526 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4527 ExprRange);
4528
4529 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4530 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4531 ExprRange);
4532
4533 // Explicitly list some types as extensions.
4534 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4535 ExprKind))
4536 return false;
4537
4539 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4540 KWName, ExprRange))
4541 return true;
4542
4543 if (ExprType->isFunctionType()) {
4544 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4545 return true;
4546 }
4547
4548 // WebAssembly tables are always illegal operands to unary expressions and
4549 // type traits.
4550 if (Context.getTargetInfo().getTriple().isWasm() &&
4551 ExprType->isWebAssemblyTableType()) {
4552 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4553 << getTraitSpelling(ExprKind);
4554 return true;
4555 }
4556
4557 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4558 ExprKind))
4559 return true;
4560
4561 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4562 if (auto *TT = ExprType->getAs<TypedefType>()) {
4563 for (auto I = FunctionScopes.rbegin(),
4564 E = std::prev(FunctionScopes.rend());
4565 I != E; ++I) {
4566 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4567 if (CSI == nullptr)
4568 break;
4569 DeclContext *DC = nullptr;
4570 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4571 DC = LSI->CallOperator;
4572 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4573 DC = CRSI->TheCapturedDecl;
4574 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4575 DC = BSI->TheDecl;
4576 if (DC) {
4577 if (DC->containsDecl(TT->getDecl()))
4578 break;
4579 captureVariablyModifiedType(Context, ExprType, CSI);
4580 }
4581 }
4582 }
4583 }
4584
4585 return false;
4586}
4587
4589 SourceLocation OpLoc,
4590 UnaryExprOrTypeTrait ExprKind,
4591 SourceRange R) {
4592 if (!TInfo)
4593 return ExprError();
4594
4595 QualType T = TInfo->getType();
4596
4597 if (!T->isDependentType() &&
4598 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4599 getTraitSpelling(ExprKind)))
4600 return ExprError();
4601
4602 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4603 // properly deal with VLAs in nested calls of sizeof and typeof.
4604 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4605 TInfo->getType()->isVariablyModifiedType())
4606 TInfo = TransformToPotentiallyEvaluated(TInfo);
4607
4608 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4609 return new (Context) UnaryExprOrTypeTraitExpr(
4610 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4611}
4612
4615 UnaryExprOrTypeTrait ExprKind) {
4617 if (PE.isInvalid())
4618 return ExprError();
4619
4620 E = PE.get();
4621
4622 // Verify that the operand is valid.
4623 bool isInvalid = false;
4624 if (E->isTypeDependent()) {
4625 // Delay type-checking for type-dependent expressions.
4626 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4627 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4628 } else if (ExprKind == UETT_VecStep) {
4630 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4631 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4632 isInvalid = true;
4633 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4634 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4635 isInvalid = true;
4636 } else if (ExprKind == UETT_VectorElements) {
4637 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);
4638 } else {
4640 }
4641
4642 if (isInvalid)
4643 return ExprError();
4644
4645 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4647 if (PE.isInvalid()) return ExprError();
4648 E = PE.get();
4649 }
4650
4651 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4652 return new (Context) UnaryExprOrTypeTraitExpr(
4653 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4654}
4655
4658 UnaryExprOrTypeTrait ExprKind, bool IsType,
4659 void *TyOrEx, SourceRange ArgRange) {
4660 // If error parsing type, ignore.
4661 if (!TyOrEx) return ExprError();
4662
4663 if (IsType) {
4664 TypeSourceInfo *TInfo;
4665 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4666 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4667 }
4668
4669 Expr *ArgEx = (Expr *)TyOrEx;
4670 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4671 return Result;
4672}
4673
4675 SourceLocation OpLoc, SourceRange R) {
4676 if (!TInfo)
4677 return true;
4678 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4679 UETT_AlignOf, KWName);
4680}
4681
4683 SourceLocation OpLoc, SourceRange R) {
4684 TypeSourceInfo *TInfo;
4686 &TInfo);
4687 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4688}
4689
4691 bool IsReal) {
4692 if (V.get()->isTypeDependent())
4693 return S.Context.DependentTy;
4694
4695 // _Real and _Imag are only l-values for normal l-values.
4696 if (V.get()->getObjectKind() != OK_Ordinary) {
4697 V = S.DefaultLvalueConversion(V.get());
4698 if (V.isInvalid())
4699 return QualType();
4700 }
4701
4702 // These operators return the element type of a complex type.
4703 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4704 return CT->getElementType();
4705
4706 // Otherwise they pass through real integer and floating point types here.
4707 if (V.get()->getType()->isArithmeticType())
4708 return V.get()->getType();
4709
4710 // Test for placeholders.
4711 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4712 if (PR.isInvalid()) return QualType();
4713 if (PR.get() != V.get()) {
4714 V = PR;
4715 return CheckRealImagOperand(S, V, Loc, IsReal);
4716 }
4717
4718 // Reject anything else.
4719 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4720 << (IsReal ? "__real" : "__imag");
4721 return QualType();
4722}
4723
4724
4725
4728 tok::TokenKind Kind, Expr *Input) {
4730 switch (Kind) {
4731 default: llvm_unreachable("Unknown unary op!");
4732 case tok::plusplus: Opc = UO_PostInc; break;
4733 case tok::minusminus: Opc = UO_PostDec; break;
4734 }
4735
4736 // Since this might is a postfix expression, get rid of ParenListExprs.
4738 if (Result.isInvalid()) return ExprError();
4739 Input = Result.get();
4740
4741 return BuildUnaryOp(S, OpLoc, Opc, Input);
4742}
4743
4744/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4745///
4746/// \return true on error
4748 SourceLocation opLoc,
4749 Expr *op) {
4750 assert(op->getType()->isObjCObjectPointerType());
4752 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4753 return false;
4754
4755 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4757 << op->getSourceRange();
4758 return true;
4759}
4760
4762 auto *BaseNoParens = Base->IgnoreParens();
4763 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4764 return MSProp->getPropertyDecl()->getType()->isArrayType();
4765 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4766}
4767
4768// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4769// Typically this is DependentTy, but can sometimes be more precise.
4770//
4771// There are cases when we could determine a non-dependent type:
4772// - LHS and RHS may have non-dependent types despite being type-dependent
4773// (e.g. unbounded array static members of the current instantiation)
4774// - one may be a dependent-sized array with known element type
4775// - one may be a dependent-typed valid index (enum in current instantiation)
4776//
4777// We *always* return a dependent type, in such cases it is DependentTy.
4778// This avoids creating type-dependent expressions with non-dependent types.
4779// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4781 const ASTContext &Ctx) {
4782 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4783 QualType LTy = LHS->getType(), RTy = RHS->getType();
4785 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4786 if (const PointerType *PT = LTy->getAs<PointerType>())
4787 Result = PT->getPointeeType();
4788 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4789 Result = AT->getElementType();
4790 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4791 if (const PointerType *PT = RTy->getAs<PointerType>())
4792 Result = PT->getPointeeType();
4793 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4794 Result = AT->getElementType();
4795 }
4796 // Ensure we return a dependent type.
4797 return Result->isDependentType() ? Result : Ctx.DependentTy;
4798}
4799
4801 SourceLocation lbLoc,
4802 MultiExprArg ArgExprs,
4803 SourceLocation rbLoc) {
4804
4805 if (base && !base->getType().isNull() &&
4806 base->hasPlaceholderType(BuiltinType::ArraySection)) {
4807 auto *AS = cast<ArraySectionExpr>(base);
4808 if (AS->isOMPArraySection())
4810 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
4811 /*Length*/ nullptr,
4812 /*Stride=*/nullptr, rbLoc);
4813
4814 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
4815 SourceLocation(), /*Length*/ nullptr,
4816 rbLoc);
4817 }
4818
4819 // Since this might be a postfix expression, get rid of ParenListExprs.
4820 if (isa<ParenListExpr>(base)) {
4822 if (result.isInvalid())
4823 return ExprError();
4824 base = result.get();
4825 }
4826
4827 // Check if base and idx form a MatrixSubscriptExpr.
4828 //
4829 // Helper to check for comma expressions, which are not allowed as indices for
4830 // matrix subscript expressions.
4831 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4832 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4833 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4834 << SourceRange(base->getBeginLoc(), rbLoc);
4835 return true;
4836 }
4837 return false;
4838 };
4839 // The matrix subscript operator ([][])is considered a single operator.
4840 // Separating the index expressions by parenthesis is not allowed.
4841 if (base && !base->getType().isNull() &&
4842 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4843 !isa<MatrixSubscriptExpr>(base)) {
4844 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4845 << SourceRange(base->getBeginLoc(), rbLoc);
4846 return ExprError();
4847 }
4848 // If the base is a MatrixSubscriptExpr, try to create a new
4849 // MatrixSubscriptExpr.
4850 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4851 if (matSubscriptE) {
4852 assert(ArgExprs.size() == 1);
4853 if (CheckAndReportCommaError(ArgExprs.front()))
4854 return ExprError();
4855
4856 assert(matSubscriptE->isIncomplete() &&
4857 "base has to be an incomplete matrix subscript");
4858 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4859 matSubscriptE->getRowIdx(),
4860 ArgExprs.front(), rbLoc);
4861 }
4862 if (base->getType()->isWebAssemblyTableType()) {
4863 Diag(base->getExprLoc(), diag::err_wasm_table_art)
4864 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
4865 return ExprError();
4866 }
4867
4868 // Handle any non-overload placeholder types in the base and index
4869 // expressions. We can't handle overloads here because the other
4870 // operand might be an overloadable type, in which case the overload
4871 // resolution for the operator overload should get the first crack
4872 // at the overload.
4873 bool IsMSPropertySubscript = false;
4874 if (base->getType()->isNonOverloadPlaceholderType()) {
4875 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4876 if (!IsMSPropertySubscript) {
4877 ExprResult result = CheckPlaceholderExpr(base);
4878 if (result.isInvalid())
4879 return ExprError();
4880 base = result.get();
4881 }
4882 }
4883
4884 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4885 if (base->getType()->isMatrixType()) {
4886 assert(ArgExprs.size() == 1);
4887 if (CheckAndReportCommaError(ArgExprs.front()))
4888 return ExprError();
4889
4890 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4891 rbLoc);
4892 }
4893
4894 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4895 Expr *idx = ArgExprs[0];
4896 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4897 (isa<CXXOperatorCallExpr>(idx) &&
4898 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4899 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4900 << SourceRange(base->getBeginLoc(), rbLoc);
4901 }
4902 }
4903
4904 if (ArgExprs.size() == 1 &&
4905 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4906 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4907 if (result.isInvalid())
4908 return ExprError();
4909 ArgExprs[0] = result.get();
4910 } else {
4911 if (CheckArgsForPlaceholders(ArgExprs))
4912 return ExprError();
4913 }
4914
4915 // Build an unanalyzed expression if either operand is type-dependent.
4916 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4917 (base->isTypeDependent() ||
4919 !isa<PackExpansionExpr>(ArgExprs[0])) {
4920 return new (Context) ArraySubscriptExpr(
4921 base, ArgExprs.front(),
4922 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4923 VK_LValue, OK_Ordinary, rbLoc);
4924 }
4925
4926 // MSDN, property (C++)
4927 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4928 // This attribute can also be used in the declaration of an empty array in a
4929 // class or structure definition. For example:
4930 // __declspec(property(get=GetX, put=PutX)) int x[];
4931 // The above statement indicates that x[] can be used with one or more array
4932 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4933 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4934 if (IsMSPropertySubscript) {
4935 assert(ArgExprs.size() == 1);
4936 // Build MS property subscript expression if base is MS property reference
4937 // or MS property subscript.
4938 return new (Context)
4939 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4940 VK_LValue, OK_Ordinary, rbLoc);
4941 }
4942
4943 // Use C++ overloaded-operator rules if either operand has record
4944 // type. The spec says to do this if either type is *overloadable*,
4945 // but enum types can't declare subscript operators or conversion
4946 // operators, so there's nothing interesting for overload resolution
4947 // to do if there aren't any record types involved.
4948 //
4949 // ObjC pointers have their own subscripting logic that is not tied
4950 // to overload resolution and so should not take this path.
4951 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4952 ((base->getType()->isRecordType() ||
4953 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
4954 ArgExprs[0]->getType()->isRecordType())))) {
4955 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4956 }
4957
4958 ExprResult Res =
4959 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4960
4961 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4962 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4963
4964 return Res;
4965}
4966
4969 InitializationKind Kind =
4971 InitializationSequence InitSeq(*this, Entity, Kind, E);
4972 return InitSeq.Perform(*this, Entity, Kind, E);
4973}
4974
4976 Expr *ColumnIdx,
4977 SourceLocation RBLoc) {
4979 if (BaseR.isInvalid())
4980 return BaseR;
4981 Base = BaseR.get();
4982
4983 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
4984 if (RowR.isInvalid())
4985 return RowR;
4986 RowIdx = RowR.get();
4987
4988 if (!ColumnIdx)
4989 return new (Context) MatrixSubscriptExpr(
4990 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
4991
4992 // Build an unanalyzed expression if any of the operands is type-dependent.
4993 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
4994 ColumnIdx->isTypeDependent())
4995 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
4996 Context.DependentTy, RBLoc);
4997
4998 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
4999 if (ColumnR.isInvalid())
5000 return ColumnR;
5001 ColumnIdx = ColumnR.get();
5002
5003 // Check that IndexExpr is an integer expression. If it is a constant
5004 // expression, check that it is less than Dim (= the number of elements in the
5005 // corresponding dimension).
5006 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5007 bool IsColumnIdx) -> Expr * {
5008 if (!IndexExpr->getType()->isIntegerType() &&
5009 !IndexExpr->isTypeDependent()) {
5010 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5011 << IsColumnIdx;
5012 return nullptr;
5013 }
5014
5015 if (std::optional<llvm::APSInt> Idx =
5016 IndexExpr->getIntegerConstantExpr(Context)) {
5017 if ((*Idx < 0 || *Idx >= Dim)) {
5018 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5019 << IsColumnIdx << Dim;
5020 return nullptr;
5021 }
5022 }
5023
5024 ExprResult ConvExpr =
5026 assert(!ConvExpr.isInvalid() &&
5027 "should be able to convert any integer type to size type");
5028 return ConvExpr.get();
5029 };
5030
5031 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5032 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5033 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5034 if (!RowIdx || !ColumnIdx)
5035 return ExprError();
5036
5037 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5038 MTy->getElementType(), RBLoc);
5039}
5040
5041void Sema::CheckAddressOfNoDeref(const Expr *E) {
5042 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5043 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5044
5045 // For expressions like `&(*s).b`, the base is recorded and what should be
5046 // checked.
5047 const MemberExpr *Member = nullptr;
5048 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5049 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5050
5051 LastRecord.PossibleDerefs.erase(StrippedExpr);
5052}
5053
5054void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5056 return;
5057
5058 QualType ResultTy = E->getType();
5059 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5060
5061 // Bail if the element is an array since it is not memory access.
5062 if (isa<ArrayType>(ResultTy))
5063 return;
5064
5065 if (ResultTy->hasAttr(attr::NoDeref)) {
5066 LastRecord.PossibleDerefs.insert(E);
5067 return;
5068 }
5069
5070 // Check if the base type is a pointer to a member access of a struct
5071 // marked with noderef.
5072 const Expr *Base = E->getBase();
5073 QualType BaseTy = Base->getType();
5074 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5075 // Not a pointer access
5076 return;
5077
5078 const MemberExpr *Member = nullptr;
5079 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5080 Member->isArrow())
5081 Base = Member->getBase();
5082
5083 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5084 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5085 LastRecord.PossibleDerefs.insert(E);
5086 }
5087}
5088
5091 Expr *Idx, SourceLocation RLoc) {
5092 Expr *LHSExp = Base;
5093 Expr *RHSExp = Idx;
5094
5097
5098 // Per C++ core issue 1213, the result is an xvalue if either operand is
5099 // a non-lvalue array, and an lvalue otherwise.
5100 if (getLangOpts().CPlusPlus11) {
5101 for (auto *Op : {LHSExp, RHSExp}) {
5102 Op = Op->IgnoreImplicit();
5103 if (Op->getType()->isArrayType() && !Op->isLValue())
5104 VK = VK_XValue;
5105 }
5106 }
5107
5108 // Perform default conversions.
5109 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5111 if (Result.isInvalid())
5112 return ExprError();
5113 LHSExp = Result.get();
5114 }
5116 if (Result.isInvalid())
5117 return ExprError();
5118 RHSExp = Result.get();
5119
5120 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5121
5122 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5123 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5124 // in the subscript position. As a result, we need to derive the array base
5125 // and index from the expression types.
5126 Expr *BaseExpr, *IndexExpr;
5127 QualType ResultType;
5128 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5129 BaseExpr = LHSExp;
5130 IndexExpr = RHSExp;
5131 ResultType =
5133 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5134 BaseExpr = LHSExp;
5135 IndexExpr = RHSExp;
5136 ResultType = PTy->getPointeeType();
5137 } else if (const ObjCObjectPointerType *PTy =
5138 LHSTy->getAs<ObjCObjectPointerType>()) {
5139 BaseExpr = LHSExp;
5140 IndexExpr = RHSExp;
5141
5142 // Use custom logic if this should be the pseudo-object subscript
5143 // expression.
5145 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5146 nullptr, nullptr);
5147
5148 ResultType = PTy->getPointeeType();
5149 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5150 // Handle the uncommon case of "123[Ptr]".
5151 BaseExpr = RHSExp;
5152 IndexExpr = LHSExp;
5153 ResultType = PTy->getPointeeType();
5154 } else if (const ObjCObjectPointerType *PTy =
5155 RHSTy->getAs<ObjCObjectPointerType>()) {
5156 // Handle the uncommon case of "123[Ptr]".
5157 BaseExpr = RHSExp;
5158 IndexExpr = LHSExp;
5159 ResultType = PTy->getPointeeType();
5161 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5162 << ResultType << BaseExpr->getSourceRange();
5163 return ExprError();
5164 }
5165 } else if (LHSTy->isSubscriptableVectorType()) {
5166 if (LHSTy->isBuiltinType() &&
5167 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5168 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5169 if (BTy->isSVEBool())
5170 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5171 << LHSExp->getSourceRange()
5172 << RHSExp->getSourceRange());
5173 ResultType = BTy->getSveEltType(Context);
5174 } else {
5175 const VectorType *VTy = LHSTy->getAs<VectorType>();
5176 ResultType = VTy->getElementType();
5177 }
5178 BaseExpr = LHSExp; // vectors: V[123]
5179 IndexExpr = RHSExp;
5180 // We apply C++ DR1213 to vector subscripting too.
5181 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5182 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5183 if (Materialized.isInvalid())
5184 return ExprError();
5185 LHSExp = Materialized.get();
5186 }
5187 VK = LHSExp->getValueKind();
5188 if (VK != VK_PRValue)
5189 OK = OK_VectorComponent;
5190
5191 QualType BaseType = BaseExpr->getType();
5192 Qualifiers BaseQuals = BaseType.getQualifiers();
5193 Qualifiers MemberQuals = ResultType.getQualifiers();
5194 Qualifiers Combined = BaseQuals + MemberQuals;
5195 if (Combined != MemberQuals)
5196 ResultType = Context.getQualifiedType(ResultType, Combined);
5197 } else if (LHSTy->isArrayType()) {
5198 // If we see an array that wasn't promoted by
5199 // DefaultFunctionArrayLvalueConversion, it must be an array that
5200 // wasn't promoted because of the C90 rule that doesn't
5201 // allow promoting non-lvalue arrays. Warn, then
5202 // force the promotion here.
5203 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5204 << LHSExp->getSourceRange();
5205 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5206 CK_ArrayToPointerDecay).get();
5207 LHSTy = LHSExp->getType();
5208
5209 BaseExpr = LHSExp;
5210 IndexExpr = RHSExp;
5211 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5212 } else if (RHSTy->isArrayType()) {
5213 // Same as previous, except for 123[f().a] case
5214 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5215 << RHSExp->getSourceRange();
5216 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5217 CK_ArrayToPointerDecay).get();
5218 RHSTy = RHSExp->getType();
5219
5220 BaseExpr = RHSExp;
5221 IndexExpr = LHSExp;
5222 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5223 } else {
5224 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5225 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5226 }
5227 // C99 6.5.2.1p1
5228 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5229 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5230 << IndexExpr->getSourceRange());
5231
5232 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5233 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5234 !IndexExpr->isTypeDependent()) {
5235 std::optional<llvm::APSInt> IntegerContantExpr =
5237 if (!IntegerContantExpr.has_value() ||
5238 IntegerContantExpr.value().isNegative())
5239 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5240 }
5241
5242 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5243 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5244 // type. Note that Functions are not objects, and that (in C99 parlance)
5245 // incomplete types are not object types.
5246 if (ResultType->isFunctionType()) {
5247 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5248 << ResultType << BaseExpr->getSourceRange();
5249 return ExprError();
5250 }
5251
5252 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5253 // GNU extension: subscripting on pointer to void
5254 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5255 << BaseExpr->getSourceRange();
5256
5257 // C forbids expressions of unqualified void type from being l-values.
5258 // See IsCForbiddenLValueType.
5259 if (!ResultType.hasQualifiers())
5260 VK = VK_PRValue;
5261 } else if (!ResultType->isDependentType() &&
5262 !ResultType.isWebAssemblyReferenceType() &&
5264 LLoc, ResultType,
5265 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5266 return ExprError();
5267
5268 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5269 !ResultType.isCForbiddenLValueType());
5270
5272 FunctionScopes.size() > 1) {
5273 if (auto *TT =
5274 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5275 for (auto I = FunctionScopes.rbegin(),
5276 E = std::prev(FunctionScopes.rend());
5277 I != E; ++I) {
5278 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5279 if (CSI == nullptr)
5280 break;
5281 DeclContext *DC = nullptr;
5282 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5283 DC = LSI->CallOperator;
5284 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5285 DC = CRSI->TheCapturedDecl;
5286 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5287 DC = BSI->TheDecl;
5288 if (DC) {
5289 if (DC->containsDecl(TT->getDecl()))
5290 break;
5292 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5293 }
5294 }
5295 }
5296 }
5297
5298 return new (Context)
5299 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5300}
5301
5303 ParmVarDecl *Param, Expr *RewrittenInit,
5304 bool SkipImmediateInvocations) {
5305 if (Param->hasUnparsedDefaultArg()) {
5306 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5307 // If we've already cleared out the location for the default argument,
5308 // that means we're parsing it right now.
5309 if (!UnparsedDefaultArgLocs.count(Param)) {
5310 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5311 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5312 Param->setInvalidDecl();
5313 return true;
5314 }
5315
5316 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5317 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5319 diag::note_default_argument_declared_here);
5320 return true;
5321 }
5322
5323 if (Param->hasUninstantiatedDefaultArg()) {
5324 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5325 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5326 return true;
5327 }
5328
5329 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5330 assert(Init && "default argument but no initializer?");
5331
5332 // If the default expression creates temporaries, we need to
5333 // push them to the current stack of expression temporaries so they'll
5334 // be properly destroyed.
5335 // FIXME: We should really be rebuilding the default argument with new
5336 // bound temporaries; see the comment in PR5810.
5337 // We don't need to do that with block decls, though, because
5338 // blocks in default argument expression can never capture anything.
5339 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5340 // Set the "needs cleanups" bit regardless of whether there are
5341 // any explicit objects.
5342 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5343 // Append all the objects to the cleanup list. Right now, this
5344 // should always be a no-op, because blocks in default argument
5345 // expressions should never be able to capture anything.
5346 assert(!InitWithCleanup->getNumObjects() &&
5347 "default argument expression has capturing blocks?");
5348 }
5349 // C++ [expr.const]p15.1:
5350 // An expression or conversion is in an immediate function context if it is
5351 // potentially evaluated and [...] its innermost enclosing non-block scope
5352 // is a function parameter scope of an immediate function.
5354 *this,
5358 Param);
5359 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5360 SkipImmediateInvocations;
5361 runWithSufficientStackSpace(CallLoc, [&] {
5362 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5363 });
5364 return false;
5365}
5366
5367struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
5369 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {}
5370
5371 bool HasImmediateCalls = false;
5372 bool shouldVisitImplicitCode() const { return true; }
5373
5375 if (const FunctionDecl *FD = E->getDirectCallee())
5376 HasImmediateCalls |= FD->isImmediateFunction();
5378 }
5379
5381 if (const FunctionDecl *FD = E->getConstructor())
5382 HasImmediateCalls |= FD->isImmediateFunction();
5384 }
5385
5386 // SourceLocExpr are not immediate invocations
5387 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5388 // need to be rebuilt so that they refer to the correct SourceLocation and
5389 // DeclContext.
5391 HasImmediateCalls = true;
5393 }
5394
5395 // A nested lambda might have parameters with immediate invocations
5396 // in their default arguments.
5397 // The compound statement is not visited (as it does not constitute a
5398 // subexpression).
5399 // FIXME: We should consider visiting and transforming captures
5400 // with init expressions.
5402 return VisitCXXMethodDecl(E->getCallOperator());
5403 }
5404
5406 return TraverseStmt(E->getExpr());
5407 }
5408
5410 return TraverseStmt(E->getExpr());
5411 }
5412};
5413
5415 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5417 : TreeTransform(SemaRef) {}
5418
5419 // Lambda can only have immediate invocations in the default
5420 // args of their parameters, which is transformed upon calling the closure.
5421 // The body is not a subexpression, so we have nothing to do.
5422 // FIXME: Immediate calls in capture initializers should be transformed.
5425
5426 // Make sure we don't rebuild the this pointer as it would
5427 // cause it to incorrectly point it to the outermost class
5428 // in the case of nested struct initialization.
5430
5431 // Rewrite to source location to refer to the context in which they are used.
5433 if (E->getParentContext() == SemaRef.CurContext)
5434 return E;
5435 return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getType(),
5436 E->getBeginLoc(), E->getEndLoc(),
5437 SemaRef.CurContext);
5438 }
5439};
5440
5442 FunctionDecl *FD, ParmVarDecl *Param,
5443 Expr *Init) {
5444 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5445
5446 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5447 bool InLifetimeExtendingContext = isInLifetimeExtendingContext();
5448 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5449 InitializationContext =
5451 if (!InitializationContext.has_value())
5452 InitializationContext.emplace(CallLoc, Param, CurContext);
5453
5454 if (!Init && !Param->hasUnparsedDefaultArg()) {
5455 // Mark that we are replacing a default argument first.
5456 // If we are instantiating a template we won't have to
5457 // retransform immediate calls.
5458 // C++ [expr.const]p15.1:
5459 // An expression or conversion is in an immediate function context if it
5460 // is potentially evaluated and [...] its innermost enclosing non-block
5461 // scope is a function parameter scope of an immediate function.
5463 *this,
5467 Param);
5468
5469 if (Param->hasUninstantiatedDefaultArg()) {
5470 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5471 return ExprError();
5472 }
5473 // CWG2631
5474 // An immediate invocation that is not evaluated where it appears is
5475 // evaluated and checked for whether it is a constant expression at the
5476 // point where the enclosing initializer is used in a function call.
5478 if (!NestedDefaultChecking)
5479 V.TraverseDecl(Param);
5480
5481 // Rewrite the call argument that was created from the corresponding
5482 // parameter's default argument.
5483 if (V.HasImmediateCalls || InLifetimeExtendingContext) {
5484 if (V.HasImmediateCalls)
5485 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5486 CallLoc, Param, CurContext};
5487 // Pass down lifetime extending flag, and collect temporaries in
5488 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5491 ExprResult Res;
5492 runWithSufficientStackSpace(CallLoc, [&] {
5493 Res = Immediate.TransformInitializer(Param->getInit(),
5494 /*NotCopy=*/false);
5495 });
5496 if (Res.isInvalid())
5497 return ExprError();
5498 Res = ConvertParamDefaultArgument(Param, Res.get(),
5499 Res.get()->getBeginLoc());
5500 if (Res.isInvalid())
5501 return ExprError();
5502 Init = Res.get();
5503 }
5504 }
5505
5507 CallLoc, FD, Param, Init,
5508 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5509 return ExprError();
5510
5511 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5512 Init, InitializationContext->Context);
5513}
5514
5516 assert(Field->hasInClassInitializer());
5517
5518 // If we might have already tried and failed to instantiate, don't try again.
5519 if (Field->isInvalidDecl())
5520 return ExprError();
5521
5522 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5523
5524 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5525
5526 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5527 InitializationContext =
5529 if (!InitializationContext.has_value())
5530 InitializationContext.emplace(Loc, Field, CurContext);
5531
5532 Expr *Init = nullptr;
5533
5534 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5535
5538
5539 if (!Field->getInClassInitializer()) {
5540 // Maybe we haven't instantiated the in-class initializer. Go check the
5541 // pattern FieldDecl to see if it has one.
5542 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5543 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5545 ClassPattern->lookup(Field->getDeclName());
5546
5547 FieldDecl *Pattern = nullptr;
5548 for (auto *L : Lookup) {
5549 if ((Pattern = dyn_cast<FieldDecl>(L)))
5550 break;
5551 }
5552 assert(Pattern && "We must have set the Pattern!");
5553 if (!Pattern->hasInClassInitializer() ||
5554 InstantiateInClassInitializer(Loc, Field, Pattern,
5556 Field->setInvalidDecl();
5557 return ExprError();
5558 }
5559 }
5560 }
5561
5562 // CWG2631
5563 // An immediate invocation that is not evaluated where it appears is
5564 // evaluated and checked for whether it is a constant expression at the
5565 // point where the enclosing initializer is used in a [...] a constructor
5566 // definition, or an aggregate initialization.
5568 if (!NestedDefaultChecking)
5569 V.TraverseDecl(Field);
5570 if (V.HasImmediateCalls) {
5571 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5572 CurContext};
5573 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5574 NestedDefaultChecking;
5575
5577 ExprResult Res;
5579 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5580 /*CXXDirectInit=*/false);
5581 });
5582 if (!Res.isInvalid())
5583 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5584 if (Res.isInvalid()) {
5585 Field->setInvalidDecl();
5586 return ExprError();
5587 }
5588 Init = Res.get();
5589 }
5590
5591 if (Field->getInClassInitializer()) {
5592 Expr *E = Init ? Init : Field->getInClassInitializer();
5593 if (!NestedDefaultChecking)
5595 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5596 });
5597 // C++11 [class.base.init]p7:
5598 // The initialization of each base and member constitutes a
5599 // full-expression.
5600 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5601 if (Res.isInvalid()) {
5602 Field->setInvalidDecl();
5603 return ExprError();
5604 }
5605 Init = Res.get();
5606
5607 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5608 Field, InitializationContext->Context,
5609 Init);
5610 }
5611
5612 // DR1351:
5613 // If the brace-or-equal-initializer of a non-static data member
5614 // invokes a defaulted default constructor of its class or of an
5615 // enclosing class in a potentially evaluated subexpression, the
5616 // program is ill-formed.
5617 //
5618 // This resolution is unworkable: the exception specification of the
5619 // default constructor can be needed in an unevaluated context, in
5620 // particular, in the operand of a noexcept-expression, and we can be
5621 // unable to compute an exception specification for an enclosed class.
5622 //
5623 // Any attempt to resolve the exception specification of a defaulted default
5624 // constructor before the initializer is lexically complete will ultimately
5625 // come here at which point we can diagnose it.
5626 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5627 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5628 << OutermostClass << Field;
5629 Diag(Field->getEndLoc(),
5630 diag::note_default_member_initializer_not_yet_parsed);
5631 // Recover by marking the field invalid, unless we're in a SFINAE context.
5632 if (!isSFINAEContext())
5633 Field->setInvalidDecl();
5634 return ExprError();
5635}
5636
5639 Expr *Fn) {
5640 if (Proto && Proto->isVariadic()) {
5641 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5642 return VariadicConstructor;
5643 else if (Fn && Fn->getType()->isBlockPointerType())
5644 return VariadicBlock;
5645 else if (FDecl) {
5646 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5647 if (Method->isInstance())
5648 return VariadicMethod;
5649 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5650 return VariadicMethod;
5651 return VariadicFunction;
5652 }
5653 return VariadicDoesNotApply;
5654}
5655
5656namespace {
5657class FunctionCallCCC final : public FunctionCallFilterCCC {
5658public:
5659 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5660 unsigned NumArgs, MemberExpr *ME)
5661 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5662 FunctionName(FuncName) {}
5663
5664 bool ValidateCandidate(const TypoCorrection &candidate) override {
5665 if (!candidate.getCorrectionSpecifier() ||
5666 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5667 return false;
5668 }
5669
5671 }
5672
5673 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5674 return std::make_unique<FunctionCallCCC>(*this);
5675 }
5676
5677private:
5678 const IdentifierInfo *const FunctionName;
5679};
5680}
5681
5683 FunctionDecl *FDecl,
5684 ArrayRef<Expr *> Args) {
5685 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5686 DeclarationName FuncName = FDecl->getDeclName();
5687 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5688
5689 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5690 if (TypoCorrection Corrected = S.CorrectTypo(
5692 S.getScopeForContext(S.CurContext), nullptr, CCC,
5694 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5695 if (Corrected.isOverloaded()) {
5698 for (NamedDecl *CD : Corrected) {
5699 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5701 OCS);
5702 }
5703 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5704 case OR_Success:
5705 ND = Best->FoundDecl;
5706 Corrected.setCorrectionDecl(ND);
5707 break;
5708 default:
5709 break;
5710 }
5711 }
5712 ND = ND->getUnderlyingDecl();
5713 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5714 return Corrected;
5715 }
5716 }
5717 return TypoCorrection();
5718}
5719
5720// [C++26][[expr.unary.op]/p4
5721// A pointer to member is only formed when an explicit &
5722// is used and its operand is a qualified-id not enclosed in parentheses.
5724 if (!isa<ParenExpr>(Fn))
5725 return false;
5726
5727 Fn = Fn->IgnoreParens();
5728
5729 auto *UO = dyn_cast<UnaryOperator>(Fn);
5730 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
5731 return false;
5732 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
5733 return DRE->hasQualifier();
5734 }
5735 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
5736 return OVL->getQualifier();
5737 return false;
5738}
5739
5740bool
5742 FunctionDecl *FDecl,
5743 const FunctionProtoType *Proto,
5744 ArrayRef<Expr *> Args,
5745 SourceLocation RParenLoc,
5746 bool IsExecConfig) {
5747 // Bail out early if calling a builtin with custom typechecking.
5748 if (FDecl)
5749 if (unsigned ID = FDecl->getBuiltinID())
5751 return false;
5752
5753 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5754 // assignment, to the types of the corresponding parameter, ...
5755
5756 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
5757 bool HasExplicitObjectParameter =
5758 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
5759 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
5760 unsigned NumParams = Proto->getNumParams();
5761 bool Invalid = false;
5762 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5763 unsigned FnKind = Fn->getType()->isBlockPointerType()
5764 ? 1 /* block */
5765 : (IsExecConfig ? 3 /* kernel function (exec config) */
5766 : 0 /* function */);
5767
5768 // If too few arguments are available (and we don't have default
5769 // arguments for the remaining parameters), don't make the call.
5770 if (Args.size() < NumParams) {
5771 if (Args.size() < MinArgs) {
5772 TypoCorrection TC;
5773 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5774 unsigned diag_id =
5775 MinArgs == NumParams && !Proto->isVariadic()
5776 ? diag::err_typecheck_call_too_few_args_suggest
5777 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5779 TC, PDiag(diag_id)
5780 << FnKind << MinArgs - ExplicitObjectParameterOffset
5781 << static_cast<unsigned>(Args.size()) -
5782 ExplicitObjectParameterOffset
5783 << HasExplicitObjectParameter << TC.getCorrectionRange());
5784 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
5785 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5786 ->getDeclName())
5787 Diag(RParenLoc,
5788 MinArgs == NumParams && !Proto->isVariadic()
5789 ? diag::err_typecheck_call_too_few_args_one
5790 : diag::err_typecheck_call_too_few_args_at_least_one)
5791 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5792 << HasExplicitObjectParameter << Fn->getSourceRange();
5793 else
5794 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5795 ? diag::err_typecheck_call_too_few_args
5796 : diag::err_typecheck_call_too_few_args_at_least)
5797 << FnKind << MinArgs - ExplicitObjectParameterOffset
5798 << static_cast<unsigned>(Args.size()) -
5799 ExplicitObjectParameterOffset
5800 << HasExplicitObjectParameter << Fn->getSourceRange();
5801
5802 // Emit the location of the prototype.
5803 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5804 Diag(FDecl->getLocation(), diag::note_callee_decl)
5805 << FDecl << FDecl->getParametersSourceRange();
5806
5807 return true;
5808 }
5809 // We reserve space for the default arguments when we create
5810 // the call expression, before calling ConvertArgumentsForCall.
5811 assert((Call->getNumArgs() == NumParams) &&
5812 "We should have reserved space for the default arguments before!");
5813 }
5814
5815 // If too many are passed and not variadic, error on the extras and drop
5816 // them.
5817 if (Args.size() > NumParams) {
5818 if (!Proto->isVariadic()) {
5819 TypoCorrection TC;
5820 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5821 unsigned diag_id =
5822 MinArgs == NumParams && !Proto->isVariadic()
5823 ? diag::err_typecheck_call_too_many_args_suggest
5824 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5826 TC, PDiag(diag_id)
5827 << FnKind << NumParams - ExplicitObjectParameterOffset
5828 << static_cast<unsigned>(Args.size()) -
5829 ExplicitObjectParameterOffset
5830 << HasExplicitObjectParameter << TC.getCorrectionRange());
5831 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
5832 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5833 ->getDeclName())
5834 Diag(Args[NumParams]->getBeginLoc(),
5835 MinArgs == NumParams
5836 ? diag::err_typecheck_call_too_many_args_one
5837 : diag::err_typecheck_call_too_many_args_at_most_one)
5838 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5839 << static_cast<unsigned>(Args.size()) -
5840 ExplicitObjectParameterOffset
5841 << HasExplicitObjectParameter << Fn->getSourceRange()
5842 << SourceRange(Args[NumParams]->getBeginLoc(),
5843 Args.back()->getEndLoc());
5844 else
5845 Diag(Args[NumParams]->getBeginLoc(),
5846 MinArgs == NumParams
5847 ? diag::err_typecheck_call_too_many_args
5848 : diag::err_typecheck_call_too_many_args_at_most)
5849 << FnKind << NumParams - ExplicitObjectParameterOffset
5850 << static_cast<unsigned>(Args.size()) -
5851 ExplicitObjectParameterOffset
5852 << HasExplicitObjectParameter << Fn->getSourceRange()
5853 << SourceRange(Args[NumParams]->getBeginLoc(),
5854 Args.back()->getEndLoc());
5855
5856 // Emit the location of the prototype.
5857 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5858 Diag(FDecl->getLocation(), diag::note_callee_decl)
5859 << FDecl << FDecl->getParametersSourceRange();
5860
5861 // This deletes the extra arguments.
5862 Call->shrinkNumArgs(NumParams);
5863 return true;
5864 }
5865 }
5866 SmallVector<Expr *, 8> AllArgs;
5867 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5868
5869 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5870 AllArgs, CallType);
5871 if (Invalid)
5872 return true;
5873 unsigned TotalNumArgs = AllArgs.size();
5874 for (unsigned i = 0; i < TotalNumArgs; ++i)
5875 Call->setArg(i, AllArgs[i]);
5876
5877 Call->computeDependence();
5878 return false;
5879}
5880
5882 const FunctionProtoType *Proto,
5883 unsigned FirstParam, ArrayRef<Expr *> Args,
5884 SmallVectorImpl<Expr *> &AllArgs,
5885 VariadicCallType CallType, bool AllowExplicit,
5886 bool IsListInitialization) {
5887 unsigned NumParams = Proto->getNumParams();
5888 bool Invalid = false;
5889 size_t ArgIx = 0;
5890 // Continue to check argument types (even if we have too few/many args).
5891 for (unsigned i = FirstParam; i < NumParams; i++) {
5892 QualType ProtoArgType = Proto->getParamType(i);
5893
5894 Expr *Arg;
5895 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5896 if (ArgIx < Args.size()) {
5897 Arg = Args[ArgIx++];
5898
5899 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5900 diag::err_call_incomplete_argument, Arg))
5901 return true;
5902
5903 // Strip the unbridged-cast placeholder expression off, if applicable.
5904 bool CFAudited = false;
5905 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5906 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5907 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5908 Arg = ObjC().stripARCUnbridgedCast(Arg);
5909 else if (getLangOpts().ObjCAutoRefCount &&
5910 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5911 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5912 CFAudited = true;
5913
5914 if (Proto->getExtParameterInfo(i).isNoEscape() &&
5915 ProtoArgType->isBlockPointerType())
5916 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5917 BE->getBlockDecl()->setDoesNotEscape();
5918
5919 InitializedEntity Entity =
5921 ProtoArgType)
5923 Context, ProtoArgType, Proto->isParamConsumed(i));
5924
5925 // Remember that parameter belongs to a CF audited API.
5926 if (CFAudited)
5927 Entity.setParameterCFAudited();
5928
5930 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5931 if (ArgE.isInvalid())
5932 return true;
5933
5934 Arg = ArgE.getAs<Expr>();
5935 } else {
5936 assert(Param && "can't use default arguments without a known callee");
5937
5938 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5939 if (ArgExpr.isInvalid())
5940 return true;
5941
5942 Arg = ArgExpr.getAs<Expr>();
5943 }
5944
5945 // Check for array bounds violations for each argument to the call. This
5946 // check only triggers warnings when the argument isn't a more complex Expr
5947 // with its own checking, such as a BinaryOperator.
5948 CheckArrayAccess(Arg);
5949
5950 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5951 CheckStaticArrayArgument(CallLoc, Param, Arg);
5952
5953 AllArgs.push_back(Arg);
5954 }
5955
5956 // If this is a variadic call, handle args passed through "...".
5957 if (CallType != VariadicDoesNotApply) {
5958 // Assume that extern "C" functions with variadic arguments that
5959 // return __unknown_anytype aren't *really* variadic.
5960 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5961 FDecl->isExternC()) {
5962 for (Expr *A : Args.slice(ArgIx)) {
5963 QualType paramType; // ignored
5964 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5965 Invalid |= arg.isInvalid();
5966 AllArgs.push_back(arg.get());
5967 }
5968
5969 // Otherwise do argument promotion, (C99 6.5.2.2p7).
5970 } else {
5971 for (Expr *A : Args.slice(ArgIx)) {
5972 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5973 Invalid |= Arg.isInvalid();
5974 AllArgs.push_back(Arg.get());
5975 }
5976 }
5977
5978 // Check for array bounds violations.
5979 for (Expr *A : Args.slice(ArgIx))
5980 CheckArrayAccess(A);
5981 }
5982 return Invalid;
5983}
5984
5986 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5987 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5988 TL = DTL.getOriginalLoc();
5989 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5990 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5991 << ATL.getLocalSourceRange();
5992}
5993
5994void
5996 ParmVarDecl *Param,
5997 const Expr *ArgExpr) {
5998 // Static array parameters are not supported in C++.
5999 if (!Param || getLangOpts().CPlusPlus)
6000 return;
6001
6002 QualType OrigTy = Param->getOriginalType();
6003
6004 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6005 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6006 return;
6007
6008 if (ArgExpr->isNullPointerConstant(Context,
6010 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6011 DiagnoseCalleeStaticArrayParam(*this, Param);
6012 return;
6013 }
6014
6015 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6016 if (!CAT)
6017 return;
6018
6019 const ConstantArrayType *ArgCAT =
6021 if (!ArgCAT)
6022 return;
6023
6024 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6025 ArgCAT->getElementType())) {
6026 if (ArgCAT->getSize().ult(CAT->getSize())) {
6027 Diag(CallLoc, diag::warn_static_array_too_small)
6028 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6029 << (unsigned)CAT->getZExtSize() << 0;
6030 DiagnoseCalleeStaticArrayParam(*this, Param);
6031 }
6032 return;
6033 }
6034
6035 std::optional<CharUnits> ArgSize =
6037 std::optional<CharUnits> ParmSize =
6039 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6040 Diag(CallLoc, diag::warn_static_array_too_small)
6041 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6042 << (unsigned)ParmSize->getQuantity() << 1;
6043 DiagnoseCalleeStaticArrayParam(*this, Param);
6044 }
6045}
6046
6047/// Given a function expression of unknown-any type, try to rebuild it
6048/// to have a function type.
6050
6051/// Is the given type a placeholder that we need to lower out
6052/// immediately during argument processing?
6054 // Placeholders are never sugared.
6055 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6056 if (!placeholder) return false;
6057
6058 switch (placeholder->getKind()) {
6059 // Ignore all the non-placeholder types.
6060#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6061 case BuiltinType::Id:
6062#include "clang/Basic/OpenCLImageTypes.def"
6063#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6064 case BuiltinType::Id:
6065#include "clang/Basic/OpenCLExtensionTypes.def"
6066 // In practice we'll never use this, since all SVE types are sugared
6067 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6068#define SVE_TYPE(Name, Id, SingletonId) \
6069 case BuiltinType::Id:
6070#include "clang/Basic/AArch64SVEACLETypes.def"
6071#define PPC_VECTOR_TYPE(Name, Id, Size) \
6072 case BuiltinType::Id:
6073#include "clang/Basic/PPCTypes.def"
6074#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6075#include "clang/Basic/RISCVVTypes.def"
6076#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6077#include "clang/Basic/WebAssemblyReferenceTypes.def"
6078#define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6079#include "clang/Basic/AMDGPUTypes.def"
6080#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6081#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6082#include "clang/AST/BuiltinTypes.def"
6083 return false;
6084
6085 case BuiltinType::UnresolvedTemplate:
6086 // We cannot lower out overload sets; they might validly be resolved
6087 // by the call machinery.
6088 case BuiltinType::Overload:
6089 return false;
6090
6091 // Unbridged casts in ARC can be handled in some call positions and
6092 // should be left in place.
6093 case BuiltinType::ARCUnbridgedCast:
6094 return false;
6095
6096 // Pseudo-objects should be converted as soon as possible.
6097 case BuiltinType::PseudoObject:
6098 return true;
6099
6100 // The debugger mode could theoretically but currently does not try
6101 // to resolve unknown-typed arguments based on known parameter types.
6102 case BuiltinType::UnknownAny:
6103 return true;
6104
6105 // These are always invalid as call arguments and should be reported.
6106 case BuiltinType::BoundMember:
6107 case BuiltinType::BuiltinFn:
6108 case BuiltinType::IncompleteMatrixIdx:
6109 case BuiltinType::ArraySection:
6110 case BuiltinType::OMPArrayShaping:
6111 case BuiltinType::OMPIterator:
6112 return true;
6113
6114 }
6115 llvm_unreachable("bad builtin type kind");
6116}
6117
6119 // Apply this processing to all the arguments at once instead of
6120 // dying at the first failure.
6121 bool hasInvalid = false;
6122 for (size_t i = 0, e = args.size(); i != e; i++) {
6123 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6124 ExprResult result = CheckPlaceholderExpr(args[i]);
6125 if (result.isInvalid()) hasInvalid = true;
6126 else args[i] = result.get();
6127 }
6128 }
6129 return hasInvalid;
6130}
6131
6132/// If a builtin function has a pointer argument with no explicit address
6133/// space, then it should be able to accept a pointer to any address
6134/// space as input. In order to do this, we need to replace the
6135/// standard builtin declaration with one that uses the same address space
6136/// as the call.
6137///
6138/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6139/// it does not contain any pointer arguments without
6140/// an address space qualifer. Otherwise the rewritten
6141/// FunctionDecl is returned.
6142/// TODO: Handle pointer return types.
6144 FunctionDecl *FDecl,
6145 MultiExprArg ArgExprs) {
6146
6147 QualType DeclType = FDecl->getType();
6148 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6149
6150 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6151 ArgExprs.size() < FT->getNumParams())
6152 return nullptr;
6153
6154 bool NeedsNewDecl = false;
6155 unsigned i = 0;
6156 SmallVector<QualType, 8> OverloadParams;
6157
6158 for (QualType ParamType : FT->param_types()) {
6159
6160 // Convert array arguments to pointer to simplify type lookup.
6161 ExprResult ArgRes =
6163 if (ArgRes.isInvalid())
6164 return nullptr;
6165 Expr *Arg = ArgRes.get();
6166 QualType ArgType = Arg->getType();
6167 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6168 !ArgType->isPointerType() ||
6169 !ArgType->getPointeeType().hasAddressSpace() ||
6171 OverloadParams.push_back(ParamType);
6172 continue;
6173 }
6174
6175 QualType PointeeType = ParamType->getPointeeType();
6176 if (PointeeType.hasAddressSpace())
6177 continue;
6178
6179 NeedsNewDecl = true;
6180 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6181
6182 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6183 OverloadParams.push_back(Context.getPointerType(PointeeType));
6184 }
6185
6186 if (!NeedsNewDecl)
6187 return nullptr;
6188
6190 EPI.Variadic = FT->isVariadic();
6191 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6192 OverloadParams, EPI);
6193 DeclContext *Parent = FDecl->getParent();
6194 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6195 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6196 FDecl->getIdentifier(), OverloadTy,
6197 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6198 false,
6199 /*hasPrototype=*/true);
6201 FT = cast<FunctionProtoType>(OverloadTy);
6202 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6203 QualType ParamType = FT->getParamType(i);
6204 ParmVarDecl *Parm =
6205 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6206 SourceLocation(), nullptr, ParamType,
6207 /*TInfo=*/nullptr, SC_None, nullptr);
6208 Parm->setScopeInfo(0, i);
6209 Params.push_back(Parm);
6210 }
6211 OverloadDecl->setParams(Params);
6212 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6213 return OverloadDecl;
6214}
6215
6216static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6217 FunctionDecl *Callee,
6218 MultiExprArg ArgExprs) {
6219 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6220 // similar attributes) really don't like it when functions are called with an
6221 // invalid number of args.
6222 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6223 /*PartialOverloading=*/false) &&
6224 !Callee->isVariadic())
6225 return;
6226 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6227 return;
6228
6229 if (const EnableIfAttr *Attr =
6230 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6231 S.Diag(Fn->getBeginLoc(),
6232 isa<CXXMethodDecl>(Callee)
6233 ? diag::err_ovl_no_viable_member_function_in_call
6234 : diag::err_ovl_no_viable_function_in_call)
6235 << Callee << Callee->getSourceRange();
6236 S.Diag(Callee->getLocation(),
6237 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6238 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6239 return;
6240 }
6241}
6242
6244 const UnresolvedMemberExpr *const UME, Sema &S) {
6245
6246 const auto GetFunctionLevelDCIfCXXClass =
6247 [](Sema &S) -> const CXXRecordDecl * {
6248 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6249 if (!DC || !DC->getParent())
6250 return nullptr;
6251
6252 // If the call to some member function was made from within a member
6253 // function body 'M' return return 'M's parent.
6254 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6255 return MD->getParent()->getCanonicalDecl();
6256 // else the call was made from within a default member initializer of a
6257 // class, so return the class.
6258 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6259 return RD->getCanonicalDecl();
6260 return nullptr;
6261 };
6262 // If our DeclContext is neither a member function nor a class (in the
6263 // case of a lambda in a default member initializer), we can't have an
6264 // enclosing 'this'.
6265
6266 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6267 if (!CurParentClass)
6268 return false;
6269
6270 // The naming class for implicit member functions call is the class in which
6271 // name lookup starts.
6272 const CXXRecordDecl *const NamingClass =
6274 assert(NamingClass && "Must have naming class even for implicit access");
6275
6276 // If the unresolved member functions were found in a 'naming class' that is
6277 // related (either the same or derived from) to the class that contains the
6278 // member function that itself contained the implicit member access.
6279
6280 return CurParentClass == NamingClass ||
6281 CurParentClass->isDerivedFrom(NamingClass);
6282}
6283
6284static void
6286 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6287
6288 if (!UME)
6289 return;
6290
6291 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6292 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6293 // already been captured, or if this is an implicit member function call (if
6294 // it isn't, an attempt to capture 'this' should already have been made).
6295 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6296 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6297 return;
6298
6299 // Check if the naming class in which the unresolved members were found is
6300 // related (same as or is a base of) to the enclosing class.
6301
6303 return;
6304
6305
6306 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6307 // If the enclosing function is not dependent, then this lambda is
6308 // capture ready, so if we can capture this, do so.
6309 if (!EnclosingFunctionCtx->isDependentContext()) {
6310 // If the current lambda and all enclosing lambdas can capture 'this' -
6311 // then go ahead and capture 'this' (since our unresolved overload set
6312 // contains at least one non-static member function).
6313 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6314 S.CheckCXXThisCapture(CallLoc);
6315 } else if (S.CurContext->isDependentContext()) {
6316 // ... since this is an implicit member reference, that might potentially
6317 // involve a 'this' capture, mark 'this' for potential capture in
6318 // enclosing lambdas.
6319 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6320 CurLSI->addPotentialThisCapture(CallLoc);
6321 }
6322}
6323
6324// Once a call is fully resolved, warn for unqualified calls to specific
6325// C++ standard functions, like move and forward.
6327 const CallExpr *Call) {
6328 // We are only checking unary move and forward so exit early here.
6329 if (Call->getNumArgs() != 1)
6330 return;
6331
6332 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6333 if (!E || isa<UnresolvedLookupExpr>(E))
6334 return;
6335 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6336 if (!DRE || !DRE->getLocation().isValid())
6337 return;
6338
6339 if (DRE->getQualifier())
6340 return;
6341
6342 const FunctionDecl *FD = Call->getDirectCallee();
6343 if (!FD)
6344 return;
6345
6346 // Only warn for some functions deemed more frequent or problematic.
6347 unsigned BuiltinID = FD->getBuiltinID();
6348 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6349 return;
6350
6351 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6353 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6354}
6355
6357 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6358 Expr *ExecConfig) {
6360 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6361 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6362 if (Call.isInvalid())
6363 return Call;
6364
6365 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6366 // language modes.
6367 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6368 ULE && ULE->hasExplicitTemplateArgs() &&
6369 ULE->decls_begin() == ULE->decls_end()) {
6370 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6371 ? diag::warn_cxx17_compat_adl_only_template_id
6372 : diag::ext_adl_only_template_id)
6373 << ULE->getName();
6374 }
6375
6376 if (LangOpts.OpenMP)
6377 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6378 ExecConfig);
6379 if (LangOpts.CPlusPlus) {
6380 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6382
6383 // If we previously found that the id-expression of this call refers to a
6384 // consteval function but the call is dependent, we should not treat is an
6385 // an invalid immediate call.
6386 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6387 DRE && Call.get()->isValueDependent()) {
6389 }
6390 }
6391 return Call;
6392}
6393
6395 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6396 Expr *ExecConfig, bool IsExecConfig,
6397 bool AllowRecovery) {
6398 // Since this might be a postfix expression, get rid of ParenListExprs.
6400 if (Result.isInvalid()) return ExprError();
6401 Fn = Result.get();
6402
6403 if (CheckArgsForPlaceholders(ArgExprs))
6404 return ExprError();
6405
6406 if (getLangOpts().CPlusPlus) {
6407 // If this is a pseudo-destructor expression, build the call immediately.
6408 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6409 if (!ArgExprs.empty()) {
6410 // Pseudo-destructor calls should not have any arguments.
6411 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6413 SourceRange(ArgExprs.front()->getBeginLoc(),
6414 ArgExprs.back()->getEndLoc()));
6415 }
6416
6417 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6418 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6419 }
6420 if (Fn->getType() == Context.PseudoObjectTy) {
6421 ExprResult result = CheckPlaceholderExpr(Fn);
6422 if (result.isInvalid()) return ExprError();
6423 Fn = result.get();
6424 }
6425
6426 // Determine whether this is a dependent call inside a C++ template,
6427 // in which case we won't do any semantic analysis now.
6428 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6429 if (ExecConfig) {
6431 cast<CallExpr>(ExecConfig), ArgExprs,
6433 RParenLoc, CurFPFeatureOverrides());
6434 } else {
6435
6437 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6438 Fn->getBeginLoc());
6439
6440 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6441 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6442 }
6443 }
6444
6445 // Determine whether this is a call to an object (C++ [over.call.object]).
6446 if (Fn->getType()->isRecordType())
6447 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6448 RParenLoc);
6449
6450 if (Fn->getType() == Context.UnknownAnyTy) {
6451 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6452 if (result.isInvalid()) return ExprError();
6453 Fn = result.get();
6454 }
6455
6456 if (Fn->getType() == Context.BoundMemberTy) {
6457 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6458 RParenLoc, ExecConfig, IsExecConfig,
6459 AllowRecovery);
6460 }
6461 }
6462
6463 // Check for overloaded calls. This can happen even in C due to extensions.
6464 if (Fn->getType() == Context.OverloadTy) {
6466
6467 // We aren't supposed to apply this logic if there's an '&' involved.
6470 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6471 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6472 OverloadExpr *ovl = find.Expression;
6473 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6475 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6476 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6477 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6478 RParenLoc, ExecConfig, IsExecConfig,
6479 AllowRecovery);
6480 }
6481 }
6482
6483 // If we're directly calling a function, get the appropriate declaration.
6484 if (Fn->getType() == Context.UnknownAnyTy) {
6485 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6486 if (result.isInvalid()) return ExprError();
6487 Fn = result.get();
6488 }
6489
6490 Expr *NakedFn = Fn->IgnoreParens();
6491
6492 bool CallingNDeclIndirectly = false;
6493 NamedDecl *NDecl = nullptr;
6494 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6495 if (UnOp->getOpcode() == UO_AddrOf) {
6496 CallingNDeclIndirectly = true;
6497 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6498 }
6499 }
6500
6501 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6502 NDecl = DRE->getDecl();
6503
6504 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6505 if (FDecl && FDecl->getBuiltinID()) {
6506 // Rewrite the function decl for this builtin by replacing parameters
6507 // with no explicit address space with the address space of the arguments
6508 // in ArgExprs.
6509 if ((FDecl =
6510 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6511 NDecl = FDecl;
6513 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6514 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6515 nullptr, DRE->isNonOdrUse());
6516 }
6517 }
6518 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6519 NDecl = ME->getMemberDecl();
6520
6521 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6522 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6523 FD, /*Complain=*/true, Fn->getBeginLoc()))
6524 return ExprError();
6525
6526 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6527
6528 // If this expression is a call to a builtin function in HIP device
6529 // compilation, allow a pointer-type argument to default address space to be
6530 // passed as a pointer-type parameter to a non-default address space.
6531 // If Arg is declared in the default address space and Param is declared
6532 // in a non-default address space, perform an implicit address space cast to
6533 // the parameter type.
6534 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6535 FD->getBuiltinID()) {
6536 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6537 ++Idx) {
6538 ParmVarDecl *Param = FD->getParamDecl(Idx);
6539 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6540 !ArgExprs[Idx]->getType()->isPointerType())
6541 continue;
6542
6543 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6544 auto ArgTy = ArgExprs[Idx]->getType();
6545 auto ArgPtTy = ArgTy->getPointeeType();
6546 auto ArgAS = ArgPtTy.getAddressSpace();
6547
6548 // Add address space cast if target address spaces are different
6549 bool NeedImplicitASC =
6550 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6551 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6552 // or from specific AS which has target AS matching that of Param.
6554 if (!NeedImplicitASC)
6555 continue;
6556
6557 // First, ensure that the Arg is an RValue.
6558 if (ArgExprs[Idx]->isGLValue()) {
6559 ArgExprs[Idx] = ImplicitCastExpr::Create(
6560 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6561 nullptr, VK_PRValue, FPOptionsOverride());
6562 }
6563
6564 // Construct a new arg type with address space of Param
6565 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6566 ArgPtQuals.setAddressSpace(ParamAS);
6567 auto NewArgPtTy =
6568 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6569 auto NewArgTy =
6571 ArgTy.getQualifiers());
6572
6573 // Finally perform an implicit address space cast
6574 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6575 CK_AddressSpaceConversion)
6576 .get();
6577 }
6578 }
6579 }
6580
6582 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6583 assert(!getLangOpts().CPlusPlus);
6584 assert((Fn->containsErrors() ||
6585 llvm::any_of(ArgExprs,
6586 [](clang::Expr *E) { return E->containsErrors(); })) &&
6587 "should only occur in error-recovery path.");
6588 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6589 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6590 }
6591 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6592 ExecConfig, IsExecConfig);
6593}
6594
6596 MultiExprArg CallArgs) {
6597 StringRef Name = Context.BuiltinInfo.getName(Id);
6598 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6600 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6601
6602 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6603 assert(BuiltInDecl && "failed to find builtin declaration");
6604
6605 ExprResult DeclRef =
6606 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6607 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6608
6610 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6611
6612 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6613 return Call.get();
6614}
6615
6617 SourceLocation BuiltinLoc,
6618 SourceLocation RParenLoc) {
6619 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6620 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6621}
6622
6624 SourceLocation BuiltinLoc,
6625 SourceLocation RParenLoc) {
6628 QualType SrcTy = E->getType();
6629 if (!SrcTy->isDependentType() &&
6630 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6631 return ExprError(
6632 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6633 << DestTy << SrcTy << E->getSourceRange());
6634 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6635}
6636
6638 SourceLocation BuiltinLoc,
6639 SourceLocation RParenLoc) {
6640 TypeSourceInfo *TInfo;
6641 GetTypeFromParser(ParsedDestTy, &TInfo);
6642 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6643}
6644
6646 SourceLocation LParenLoc,
6647 ArrayRef<Expr *> Args,
6648 SourceLocation RParenLoc, Expr *Config,
6649 bool IsExecConfig, ADLCallKind UsesADL) {
6650 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6651 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6652
6653 // Functions with 'interrupt' attribute cannot be called directly.
6654 if (FDecl) {
6655 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
6656 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6657 return ExprError();
6658 }
6659 if (FDecl->hasAttr<ARMInterruptAttr>()) {
6660 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
6661 return ExprError();
6662 }
6663 }
6664
6665 // X86 interrupt handlers may only call routines with attribute
6666 // no_caller_saved_registers since there is no efficient way to
6667 // save and restore the non-GPR state.
6668 if (auto *Caller = getCurFunctionDecl()) {
6669 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6670 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6671 const TargetInfo &TI = Context.getTargetInfo();
6672 bool HasNonGPRRegisters =
6673 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6674 if (HasNonGPRRegisters &&
6675 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6676 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6677 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6678 if (FDecl)
6679 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6680 }
6681 }
6682 }
6683
6684 // Promote the function operand.
6685 // We special-case function promotion here because we only allow promoting
6686 // builtin functions to function pointers in the callee of a call.
6688 QualType ResultTy;
6689 if (BuiltinID &&
6690 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6691 // Extract the return type from the (builtin) function pointer type.
6692 // FIXME Several builtins still have setType in
6693 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6694 // Builtins.td to ensure they are correct before removing setType calls.
6695 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6696 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6697 ResultTy = FDecl->getCallResultType();
6698 } else {
6700 ResultTy = Context.BoolTy;
6701 }
6702 if (Result.isInvalid())
6703 return ExprError();
6704 Fn = Result.get();
6705
6706 // Check for a valid function type, but only if it is not a builtin which
6707 // requires custom type checking. These will be handled by
6708 // CheckBuiltinFunctionCall below just after creation of the call expression.
6709 const FunctionType *FuncT = nullptr;
6710 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6711 retry:
6712 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6713 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6714 // have type pointer to function".
6715 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6716 if (!FuncT)
6717 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6718 << Fn->getType() << Fn->getSourceRange());
6719 } else if (const BlockPointerType *BPT =
6720 Fn->getType()->getAs<BlockPointerType>()) {
6721 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6722 } else {
6723 // Handle calls to expressions of unknown-any type.
6724 if (Fn->getType() == Context.UnknownAnyTy) {
6725 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6726 if (rewrite.isInvalid())
6727 return ExprError();
6728 Fn = rewrite.get();
6729 goto retry;
6730 }
6731
6732 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6733 << Fn->getType() << Fn->getSourceRange());
6734 }
6735 }
6736
6737 // Get the number of parameters in the function prototype, if any.
6738 // We will allocate space for max(Args.size(), NumParams) arguments
6739 // in the call expression.
6740 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6741 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6742
6743 CallExpr *TheCall;
6744 if (Config) {
6745 assert(UsesADL == ADLCallKind::NotADL &&
6746 "CUDAKernelCallExpr should not use ADL");
6747 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6748 Args, ResultTy, VK_PRValue, RParenLoc,
6749 CurFPFeatureOverrides(), NumParams);
6750 } else {
6751 TheCall =
6752 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6753 CurFPFeatureOverrides(), NumParams, UsesADL);
6754 }
6755
6757 // Forget about the nulled arguments since typo correction
6758 // do not handle them well.
6759 TheCall->shrinkNumArgs(Args.size());
6760 // C cannot always handle TypoExpr nodes in builtin calls and direct
6761 // function calls as their argument checking don't necessarily handle
6762 // dependent types properly, so make sure any TypoExprs have been
6763 // dealt with.
6765 if (!Result.isUsable()) return ExprError();
6766 CallExpr *TheOldCall = TheCall;
6767 TheCall = dyn_cast<CallExpr>(Result.get());
6768 bool CorrectedTypos = TheCall != TheOldCall;
6769 if (!TheCall) return Result;
6770 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6771
6772 // A new call expression node was created if some typos were corrected.
6773 // However it may not have been constructed with enough storage. In this
6774 // case, rebuild the node with enough storage. The waste of space is
6775 // immaterial since this only happens when some typos were corrected.
6776 if (CorrectedTypos && Args.size() < NumParams) {
6777 if (Config)
6779 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6780 RParenLoc, CurFPFeatureOverrides(), NumParams);
6781 else
6782 TheCall =
6783 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6784 CurFPFeatureOverrides(), NumParams, UsesADL);
6785 }
6786 // We can now handle the nulled arguments for the default arguments.
6787 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6788 }
6789
6790 // Bail out early if calling a builtin with custom type checking.
6791 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6792 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6793 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
6795 return E;
6796 }
6797
6798 if (getLangOpts().CUDA) {
6799 if (Config) {
6800 // CUDA: Kernel calls must be to global functions
6801 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6802 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6803 << FDecl << Fn->getSourceRange());
6804
6805 // CUDA: Kernel function must have 'void' return type
6806 if (!FuncT->getReturnType()->isVoidType() &&
6807 !FuncT->getReturnType()->getAs<AutoType>() &&
6809 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6810 << Fn->getType() << Fn->getSourceRange());
6811 } else {
6812 // CUDA: Calls to global functions must be configured
6813 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6814 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6815 << FDecl << Fn->getSourceRange());
6816 }
6817 }
6818
6819 // Check for a valid return type
6820 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6821 FDecl))
6822 return ExprError();
6823
6824 // We know the result type of the call, set it.
6825 TheCall->setType(FuncT->getCallResultType(Context));
6827
6828 // WebAssembly tables can't be used as arguments.
6829 if (Context.getTargetInfo().getTriple().isWasm()) {
6830 for (const Expr *Arg : Args) {
6831 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
6832 return ExprError(Diag(Arg->getExprLoc(),
6833 diag::err_wasm_table_as_function_parameter));
6834 }
6835 }
6836 }
6837
6838 if (Proto) {
6839 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6840 IsExecConfig))
6841 return ExprError();
6842 } else {
6843 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6844
6845 if (FDecl) {
6846 // Check if we have too few/too many template arguments, based
6847 // on our knowledge of the function definition.
6848 const FunctionDecl *Def = nullptr;
6849 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6850 Proto = Def->getType()->getAs<FunctionProtoType>();
6851 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6852 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6853 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6854 }
6855
6856 // If the function we're calling isn't a function prototype, but we have
6857 // a function prototype from a prior declaratiom, use that prototype.
6858 if (!FDecl->hasPrototype())
6859 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6860 }
6861
6862 // If we still haven't found a prototype to use but there are arguments to
6863 // the call, diagnose this as calling a function without a prototype.
6864 // However, if we found a function declaration, check to see if
6865 // -Wdeprecated-non-prototype was disabled where the function was declared.
6866 // If so, we will silence the diagnostic here on the assumption that this
6867 // interface is intentional and the user knows what they're doing. We will
6868 // also silence the diagnostic if there is a function declaration but it
6869 // was implicitly defined (the user already gets diagnostics about the
6870 // creation of the implicit function declaration, so the additional warning
6871 // is not helpful).
6872 if (!Proto && !Args.empty() &&
6873 (!FDecl || (!FDecl->isImplicit() &&
6874 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
6875 FDecl->getLocation()))))
6876 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
6877 << (FDecl != nullptr) << FDecl;
6878
6879 // Promote the arguments (C99 6.5.2.2p6).
6880 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6881 Expr *Arg = Args[i];
6882
6883 if (Proto && i < Proto->getNumParams()) {
6885 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6886 ExprResult ArgE =
6888 if (ArgE.isInvalid())
6889 return true;
6890
6891 Arg = ArgE.getAs<Expr>();
6892
6893 } else {
6895
6896 if (ArgE.isInvalid())
6897 return true;
6898
6899 Arg = ArgE.getAs<Expr>();
6900 }
6901
6902 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6903 diag::err_call_incomplete_argument, Arg))
6904 return ExprError();
6905
6906 TheCall->setArg(i, Arg);
6907 }
6908 TheCall->computeDependence();
6909 }
6910
6911 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6912 if (!isa<RequiresExprBodyDecl>(CurContext) &&
6913 Method->isImplicitObjectMemberFunction())
6914 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
6915 << Fn->getSourceRange() << 0);
6916
6917 // Check for sentinels
6918 if (NDecl)
6919 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
6920
6921 // Warn for unions passing across security boundary (CMSE).
6922 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
6923 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6924 if (const auto *RT =
6925 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
6926 if (RT->getDecl()->isOrContainsUnion())
6927 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
6928 << 0 << i;
6929 }
6930 }
6931 }
6932
6933 // Do special checking on direct calls to functions.
6934 if (FDecl) {
6935 if (CheckFunctionCall(FDecl, TheCall, Proto))
6936 return ExprError();
6937
6938 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
6939
6940 if (BuiltinID)
6941 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6942 } else if (NDecl) {
6943 if (CheckPointerCall(NDecl, TheCall, Proto))
6944 return ExprError();
6945 } else {
6946 if (CheckOtherCall(TheCall, Proto))
6947 return ExprError();
6948 }
6949
6950 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
6951}
6952
6955 SourceLocation RParenLoc, Expr *InitExpr) {
6956 assert(Ty && "ActOnCompoundLiteral(): missing type");
6957 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
6958
6959 TypeSourceInfo *TInfo;
6960 QualType literalType = GetTypeFromParser(Ty, &TInfo);
6961 if (!TInfo)
6962 TInfo = Context.getTrivialTypeSourceInfo(literalType);
6963
6964 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
6965}
6966
6969 SourceLocation RParenLoc, Expr *LiteralExpr) {
6970 QualType literalType = TInfo->getType();
6971
6972 if (literalType->isArrayType()) {
6974 LParenLoc, Context.getBaseElementType(literalType),
6975 diag::err_array_incomplete_or_sizeless_type,
6976 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
6977 return ExprError();
6978 if (literalType->isVariableArrayType()) {
6979 // C23 6.7.10p4: An entity of variable length array type shall not be
6980 // initialized except by an empty initializer.
6981 //
6982 // The C extension warnings are issued from ParseBraceInitializer() and
6983 // do not need to be issued here. However, we continue to issue an error
6984 // in the case there are initializers or we are compiling C++. We allow
6985 // use of VLAs in C++, but it's not clear we want to allow {} to zero
6986 // init a VLA in C++ in all cases (such as with non-trivial constructors).
6987 // FIXME: should we allow this construct in C++ when it makes sense to do
6988 // so?
6989 //
6990 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
6991 // shall specify an object type or an array of unknown size, but not a
6992 // variable length array type. This seems odd, as it allows 'int a[size] =
6993 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
6994 // says, this is what's implemented here for C (except for the extension
6995 // that permits constant foldable size arrays)
6996
6997 auto diagID = LangOpts.CPlusPlus
6998 ? diag::err_variable_object_no_init
6999 : diag::err_compound_literal_with_vla_type;
7000 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7001 diagID))
7002 return ExprError();
7003 }
7004 } else if (!literalType->isDependentType() &&
7005 RequireCompleteType(LParenLoc, literalType,
7006 diag::err_typecheck_decl_incomplete_type,
7007 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7008 return ExprError();
7009
7010 InitializedEntity Entity
7014 SourceRange(LParenLoc, RParenLoc),
7015 /*InitList=*/true);
7016 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7017 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7018 &literalType);
7019 if (Result.isInvalid())
7020 return ExprError();
7021 LiteralExpr = Result.get();
7022
7023 bool isFileScope = !CurContext->isFunctionOrMethod();
7024
7025 // In C, compound literals are l-values for some reason.
7026 // For GCC compatibility, in C++, file-scope array compound literals with
7027 // constant initializers are also l-values, and compound literals are
7028 // otherwise prvalues.
7029 //
7030 // (GCC also treats C++ list-initialized file-scope array prvalues with
7031 // constant initializers as l-values, but that's non-conforming, so we don't
7032 // follow it there.)
7033 //
7034 // FIXME: It would be better to handle the lvalue cases as materializing and
7035 // lifetime-extending a temporary object, but our materialized temporaries
7036 // representation only supports lifetime extension from a variable, not "out
7037 // of thin air".
7038 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7039 // is bound to the result of applying array-to-pointer decay to the compound
7040 // literal.
7041 // FIXME: GCC supports compound literals of reference type, which should
7042 // obviously have a value kind derived from the kind of reference involved.
7043 ExprValueKind VK =
7044 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7045 ? VK_PRValue
7046 : VK_LValue;
7047
7048 if (isFileScope)
7049 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7050 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7051 Expr *Init = ILE->getInit(i);
7052 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7053 }
7054
7055 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7056 VK, LiteralExpr, isFileScope);
7057 if (isFileScope) {
7058 if (!LiteralExpr->isTypeDependent() &&
7059 !LiteralExpr->isValueDependent() &&
7060 !literalType->isDependentType()) // C99 6.5.2.5p3
7061 if (CheckForConstantInitializer(LiteralExpr))
7062 return ExprError();
7063 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7064 literalType.getAddressSpace() != LangAS::Default) {
7065 // Embedded-C extensions to C99 6.5.2.5:
7066 // "If the compound literal occurs inside the body of a function, the
7067 // type name shall not be qualified by an address-space qualifier."
7068 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7069 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7070 return ExprError();
7071 }
7072
7073 if (!isFileScope && !getLangOpts().CPlusPlus) {
7074 // Compound literals that have automatic storage duration are destroyed at
7075 // the end of the scope in C; in C++, they're just temporaries.
7076
7077 // Emit diagnostics if it is or contains a C union type that is non-trivial
7078 // to destruct.
7082
7083 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7084 if (literalType.isDestructedType()) {
7086 ExprCleanupObjects.push_back(E);
7088 }
7089 }
7090
7093 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7094 E->getInitializer()->getExprLoc());
7095
7096 return MaybeBindToTemporary(E);
7097}
7098
7101 SourceLocation RBraceLoc) {
7102 // Only produce each kind of designated initialization diagnostic once.
7103 SourceLocation FirstDesignator;
7104 bool DiagnosedArrayDesignator = false;
7105 bool DiagnosedNestedDesignator = false;
7106 bool DiagnosedMixedDesignator = false;
7107
7108 // Check that any designated initializers are syntactically valid in the
7109 // current language mode.
7110 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7111 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7112 if (FirstDesignator.isInvalid())
7113 FirstDesignator = DIE->getBeginLoc();
7114
7115 if (!getLangOpts().CPlusPlus)
7116 break;
7117
7118 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7119 DiagnosedNestedDesignator = true;
7120 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7121 << DIE->getDesignatorsSourceRange();
7122 }
7123
7124 for (auto &Desig : DIE->designators()) {
7125 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7126 DiagnosedArrayDesignator = true;
7127 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7128 << Desig.getSourceRange();
7129 }
7130 }
7131
7132 if (!DiagnosedMixedDesignator &&
7133 !isa<DesignatedInitExpr>(InitArgList[0])) {
7134 DiagnosedMixedDesignator = true;
7135 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7136 << DIE->getSourceRange();
7137 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7138 << InitArgList[0]->getSourceRange();
7139 }
7140 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7141 isa<DesignatedInitExpr>(InitArgList[0])) {
7142 DiagnosedMixedDesignator = true;
7143 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7144 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7145 << DIE->getSourceRange();
7146 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7147 << InitArgList[I]->getSourceRange();
7148 }
7149 }
7150
7151 if (FirstDesignator.isValid()) {
7152 // Only diagnose designated initiaization as a C++20 extension if we didn't
7153 // already diagnose use of (non-C++20) C99 designator syntax.
7154 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7155 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7156 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7157 ? diag::warn_cxx17_compat_designated_init
7158 : diag::ext_cxx_designated_init);
7159 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7160 Diag(FirstDesignator, diag::ext_designated_init);
7161 }
7162 }
7163
7164 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7165}
7166
7169 SourceLocation RBraceLoc) {
7170 // Semantic analysis for initializers is done by ActOnDeclarator() and
7171 // CheckInitializer() - it requires knowledge of the object being initialized.
7172
7173 // Immediately handle non-overload placeholders. Overloads can be
7174 // resolved contextually, but everything else here can't.
7175 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7176 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7177 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7178
7179 // Ignore failures; dropping the entire initializer list because
7180 // of one failure would be terrible for indexing/etc.
7181 if (result.isInvalid()) continue;
7182
7183 InitArgList[I] = result.get();
7184 }
7185 }
7186
7187 InitListExpr *E =
7188 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7189 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7190 return E;
7191}
7192
7194 assert(E.get()->getType()->isBlockPointerType());
7195 assert(E.get()->isPRValue());
7196
7197 // Only do this in an r-value context.
7198 if (!getLangOpts().ObjCAutoRefCount) return;
7199
7201 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7202 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7204}
7205
7207 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7208 // Also, callers should have filtered out the invalid cases with
7209 // pointers. Everything else should be possible.
7210
7211 QualType SrcTy = Src.get()->getType();
7212 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7213 return CK_NoOp;
7214
7215 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7217 llvm_unreachable("member pointer type in C");
7218
7219 case Type::STK_CPointer:
7222 switch (DestTy->getScalarTypeKind()) {
7223 case Type::STK_CPointer: {
7224 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7225 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7226 if (SrcAS != DestAS)
7227 return CK_AddressSpaceConversion;
7228 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7229 return CK_NoOp;
7230 return CK_BitCast;
7231 }
7233 return (SrcKind == Type::STK_BlockPointer
7234 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7236 if (SrcKind == Type::STK_ObjCObjectPointer)
7237 return CK_BitCast;
7238 if (SrcKind == Type::STK_CPointer)
7239 return CK_CPointerToObjCPointerCast;
7241 return CK_BlockPointerToObjCPointerCast;
7242 case Type::STK_Bool:
7243 return CK_PointerToBoolean;
7244 case Type::STK_Integral:
7245 return CK_PointerToIntegral;
7246 case Type::STK_Floating:
7251 llvm_unreachable("illegal cast from pointer");
7252 }
7253 llvm_unreachable("Should have returned before this");
7254
7256 switch (DestTy->getScalarTypeKind()) {
7258 return CK_FixedPointCast;
7259 case Type::STK_Bool:
7260 return CK_FixedPointToBoolean;
7261 case Type::STK_Integral:
7262 return CK_FixedPointToIntegral;
7263 case Type::STK_Floating:
7264 return CK_FixedPointToFloating;
7267 Diag(Src.get()->getExprLoc(),
7268 diag::err_unimplemented_conversion_with_fixed_point_type)
7269 << DestTy;
7270 return CK_IntegralCast;
7271 case Type::STK_CPointer:
7275 llvm_unreachable("illegal cast to pointer type");
7276 }
7277 llvm_unreachable("Should have returned before this");
7278
7279 case Type::STK_Bool: // casting from bool is like casting from an integer
7280 case Type::STK_Integral:
7281 switch (DestTy->getScalarTypeKind()) {
7282 case Type::STK_CPointer:
7287 return CK_NullToPointer;
7288 return CK_IntegralToPointer;
7289 case Type::STK_Bool:
7290 return CK_IntegralToBoolean;
7291 case Type::STK_Integral:
7292 return CK_IntegralCast;
7293 case Type::STK_Floating:
7294 return CK_IntegralToFloating;
7296 Src = ImpCastExprToType(Src.get(),
7297 DestTy->castAs<ComplexType>()->getElementType(),
7298 CK_IntegralCast);
7299 return CK_IntegralRealToComplex;
7301 Src = ImpCastExprToType(Src.get(),
7302 DestTy->castAs<ComplexType>()->getElementType(),
7303 CK_IntegralToFloating);
7304 return CK_FloatingRealToComplex;
7306 llvm_unreachable("member pointer type in C");
7308 return CK_IntegralToFixedPoint;
7309 }
7310 llvm_unreachable("Should have returned before this");
7311
7312 case Type::STK_Floating:
7313 switch (DestTy->getScalarTypeKind()) {
7314 case Type::STK_Floating:
7315 return CK_FloatingCast;
7316 case Type::STK_Bool:
7317 return CK_FloatingToBoolean;
7318 case Type::STK_Integral:
7319 return CK_FloatingToIntegral;
7321 Src = ImpCastExprToType(Src.get(),
7322 DestTy->castAs<ComplexType>()->getElementType(),
7323 CK_FloatingCast);
7324 return CK_FloatingRealToComplex;
7326 Src = ImpCastExprToType(Src.get(),
7327 DestTy->castAs<ComplexType>()->getElementType(),
7328 CK_FloatingToIntegral);
7329 return CK_IntegralRealToComplex;
7330 case Type::STK_CPointer:
7333 llvm_unreachable("valid float->pointer cast?");
7335 llvm_unreachable("member pointer type in C");
7337 return CK_FloatingToFixedPoint;
7338 }
7339 llvm_unreachable("Should have returned before this");
7340
7342 switch (DestTy->getScalarTypeKind()) {
7344 return CK_FloatingComplexCast;
7346 return CK_FloatingComplexToIntegralComplex;
7347 case Type::STK_Floating: {
7348 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7349 if (Context.hasSameType(ET, DestTy))
7350 return CK_FloatingComplexToReal;
7351 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7352 return CK_FloatingCast;
7353 }
7354 case Type::STK_Bool:
7355 return CK_FloatingComplexToBoolean;
7356 case Type::STK_Integral:
7357 Src = ImpCastExprToType(Src.get(),
7358 SrcTy->castAs<ComplexType>()->getElementType(),
7359 CK_FloatingComplexToReal);
7360 return CK_FloatingToIntegral;
7361 case Type::STK_CPointer:
7364 llvm_unreachable("valid complex float->pointer cast?");
7366 llvm_unreachable("member pointer type in C");
7368 Diag(Src.get()->getExprLoc(),
7369 diag::err_unimplemented_conversion_with_fixed_point_type)
7370 << SrcTy;
7371 return CK_IntegralCast;
7372 }
7373 llvm_unreachable("Should have returned before this");
7374
7376 switch (DestTy->getScalarTypeKind()) {
7378 return CK_IntegralComplexToFloatingComplex;
7380 return CK_IntegralComplexCast;
7381 case Type::STK_Integral: {
7382 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7383 if (Context.hasSameType(ET, DestTy))
7384 return CK_IntegralComplexToReal;
7385 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7386 return CK_IntegralCast;
7387 }
7388 case Type::STK_Bool:
7389 return CK_IntegralComplexToBoolean;
7390 case Type::STK_Floating:
7391 Src = ImpCastExprToType(Src.get(),
7392 SrcTy->castAs<ComplexType>()->getElementType(),
7393 CK_IntegralComplexToReal);
7394 return CK_IntegralToFloating;
7395 case Type::STK_CPointer:
7398 llvm_unreachable("valid complex int->pointer cast?");
7400 llvm_unreachable("member pointer type in C");
7402 Diag(Src.get()->getExprLoc(),
7403 diag::err_unimplemented_conversion_with_fixed_point_type)
7404 << SrcTy;
7405 return CK_IntegralCast;
7406 }
7407 llvm_unreachable("Should have returned before this");
7408 }
7409
7410 llvm_unreachable("Unhandled scalar cast");
7411}
7412
7413static bool breakDownVectorType(QualType type, uint64_t &len,
7414 QualType &eltType) {
7415 // Vectors are simple.
7416 if (const VectorType *vecType = type->getAs<VectorType>()) {
7417 len = vecType->getNumElements();
7418 eltType = vecType->getElementType();
7419 assert(eltType->isScalarType());
7420 return true;
7421 }
7422
7423 // We allow lax conversion to and from non-vector types, but only if
7424 // they're real types (i.e. non-complex, non-pointer scalar types).
7425 if (!type->isRealType()) return false;
7426
7427 len = 1;
7428 eltType = type;
7429 return true;
7430}
7431
7433 assert(srcTy->isVectorType() || destTy->isVectorType());
7434
7435 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7436 if (!FirstType->isSVESizelessBuiltinType())
7437 return false;
7438
7439 const auto *VecTy = SecondType->getAs<VectorType>();
7440 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7441 };
7442
7443 return ValidScalableConversion(srcTy, destTy) ||
7444 ValidScalableConversion(destTy, srcTy);
7445}
7446
7448 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7449 return false;
7450
7451 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7452 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7453
7454 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7455 matSrcType->getNumColumns() == matDestType->getNumColumns();
7456}
7457
7459 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7460
7461 uint64_t SrcLen, DestLen;
7462 QualType SrcEltTy, DestEltTy;
7463 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7464 return false;
7465 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7466 return false;
7467
7468 // ASTContext::getTypeSize will return the size rounded up to a
7469 // power of 2, so instead of using that, we need to use the raw
7470 // element size multiplied by the element count.
7471 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7472 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7473
7474 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7475}
7476
7478 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7479 "expected at least one type to be a vector here");
7480
7481 bool IsSrcTyAltivec =
7482 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7484 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7486 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7488
7489 bool IsDestTyAltivec = DestTy->isVectorType() &&
7490 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7492 (DestTy->castAs<VectorType>()->getVectorKind() ==
7494 (DestTy->castAs<VectorType>()->getVectorKind() ==
7496
7497 return (IsSrcTyAltivec || IsDestTyAltivec);
7498}
7499
7501 assert(destTy->isVectorType() || srcTy->isVectorType());
7502
7503 // Disallow lax conversions between scalars and ExtVectors (these
7504 // conversions are allowed for other vector types because common headers
7505 // depend on them). Most scalar OP ExtVector cases are handled by the
7506 // splat path anyway, which does what we want (convert, not bitcast).
7507 // What this rules out for ExtVectors is crazy things like char4*float.
7508 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7509 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7510
7511 return areVectorTypesSameSize(srcTy, destTy);
7512}
7513
7515 assert(destTy->isVectorType() || srcTy->isVectorType());
7516
7517 switch (Context.getLangOpts().getLaxVectorConversions()) {
7519 return false;
7520
7522 if (!srcTy->isIntegralOrEnumerationType()) {
7523 auto *Vec = srcTy->getAs<VectorType>();
7524 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7525 return false;
7526 }
7527 if (!destTy->isIntegralOrEnumerationType()) {
7528 auto *Vec = destTy->getAs<VectorType>();
7529 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7530 return false;
7531 }
7532 // OK, integer (vector) -> integer (vector) bitcast.
7533 break;
7534
7536 break;
7537 }
7538
7539 return areLaxCompatibleVectorTypes(srcTy, destTy);
7540}
7541
7543 CastKind &Kind) {
7544 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7545 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7546 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7547 << DestTy << SrcTy << R;
7548 }
7549 } else if (SrcTy->isMatrixType()) {
7550 return Diag(R.getBegin(),
7551 diag::err_invalid_conversion_between_matrix_and_type)
7552 << SrcTy << DestTy << R;
7553 } else if (DestTy->isMatrixType()) {
7554 return Diag(R.getBegin(),
7555 diag::err_invalid_conversion_between_matrix_and_type)
7556 << DestTy << SrcTy << R;
7557 }
7558
7559 Kind = CK_MatrixCast;
7560 return false;
7561}
7562
7564 CastKind &Kind) {
7565 assert(VectorTy->isVectorType() && "Not a vector type!");
7566
7567 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7568 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7569 return Diag(R.getBegin(),
7570 Ty->isVectorType() ?
7571 diag::err_invalid_conversion_between_vectors :
7572 diag::err_invalid_conversion_between_vector_and_integer)
7573 << VectorTy << Ty << R;
7574 } else
7575 return Diag(R.getBegin(),
7576 diag::err_invalid_conversion_between_vector_and_scalar)
7577 << VectorTy << Ty << R;
7578
7579 Kind = CK_BitCast;
7580 return false;
7581}
7582
7584 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7585
7586 if (DestElemTy == SplattedExpr->getType())
7587 return SplattedExpr;
7588
7589 assert(DestElemTy->isFloatingType() ||
7590 DestElemTy->isIntegralOrEnumerationType());
7591
7592 CastKind CK;
7593 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7594 // OpenCL requires that we convert `true` boolean expressions to -1, but
7595 // only when splatting vectors.
7596 if (DestElemTy->isFloatingType()) {
7597 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7598 // in two steps: boolean to signed integral, then to floating.
7599 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7600 CK_BooleanToSignedIntegral);
7601 SplattedExpr = CastExprRes.get();
7602 CK = CK_IntegralToFloating;
7603 } else {
7604 CK = CK_BooleanToSignedIntegral;
7605 }
7606 } else {
7607 ExprResult CastExprRes = SplattedExpr;
7608 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7609 if (CastExprRes.isInvalid())
7610 return ExprError();
7611 SplattedExpr = CastExprRes.get();
7612 }
7613 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7614}
7615
7617 Expr *CastExpr, CastKind &Kind) {
7618 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7619
7620 QualType SrcTy = CastExpr->getType();
7621
7622 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7623 // an ExtVectorType.
7624 // In OpenCL, casts between vectors of different types are not allowed.
7625 // (See OpenCL 6.2).
7626 if (SrcTy->isVectorType()) {
7627 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7628 (getLangOpts().OpenCL &&
7629 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7630 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7631 << DestTy << SrcTy << R;
7632 return ExprError();
7633 }
7634 Kind = CK_BitCast;
7635 return CastExpr;
7636 }
7637
7638 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7639 // conversion will take place first from scalar to elt type, and then
7640 // splat from elt type to vector.
7641 if (SrcTy->isPointerType())
7642 return Diag(R.getBegin(),
7643 diag::err_invalid_conversion_between_vector_and_scalar)
7644 << DestTy << SrcTy << R;
7645
7646 Kind = CK_VectorSplat;
7647 return prepareVectorSplat(DestTy, CastExpr);
7648}
7649
7652 Declarator &D, ParsedType &Ty,
7653 SourceLocation RParenLoc, Expr *CastExpr) {
7654 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7655 "ActOnCastExpr(): missing type or expr");
7656
7658 if (D.isInvalidType())
7659 return ExprError();
7660
7661 if (getLangOpts().CPlusPlus) {
7662 // Check that there are no default arguments (C++ only).
7664 } else {
7665 // Make sure any TypoExprs have been dealt with.
7667 if (!Res.isUsable())
7668 return ExprError();
7669 CastExpr = Res.get();
7670 }
7671
7673
7674 QualType castType = castTInfo->getType();
7675 Ty = CreateParsedType(castType, castTInfo);
7676
7677 bool isVectorLiteral = false;
7678
7679 // Check for an altivec or OpenCL literal,
7680 // i.e. all the elements are integer constants.
7681 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7682 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7683 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7684 && castType->isVectorType() && (PE || PLE)) {
7685 if (PLE && PLE->getNumExprs() == 0) {
7686 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7687 return ExprError();
7688 }
7689 if (PE || PLE->getNumExprs() == 1) {
7690 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7691 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7692 isVectorLiteral = true;
7693 }
7694 else
7695 isVectorLiteral = true;
7696 }
7697
7698 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7699 // then handle it as such.
7700 if (isVectorLiteral)
7701 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7702
7703 // If the Expr being casted is a ParenListExpr, handle it specially.
7704 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7705 // sequence of BinOp comma operators.
7706 if (isa<ParenListExpr>(CastExpr)) {
7708 if (Result.isInvalid()) return ExprError();
7709 CastExpr = Result.get();
7710 }
7711
7712 if (getLangOpts().CPlusPlus && !castType->isVoidType())
7713 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7714
7716
7718
7720
7721 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7722}
7723
7725 SourceLocation RParenLoc, Expr *E,
7726 TypeSourceInfo *TInfo) {
7727 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7728 "Expected paren or paren list expression");
7729
7730 Expr **exprs;
7731 unsigned numExprs;
7732 Expr *subExpr;
7733 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7734 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7735 LiteralLParenLoc = PE->getLParenLoc();
7736 LiteralRParenLoc = PE->getRParenLoc();
7737 exprs = PE->getExprs();
7738 numExprs = PE->getNumExprs();
7739 } else { // isa<ParenExpr> by assertion at function entrance
7740 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7741 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7742 subExpr = cast<ParenExpr>(E)->getSubExpr();
7743 exprs = &subExpr;
7744 numExprs = 1;
7745 }
7746
7747 QualType Ty = TInfo->getType();
7748 assert(Ty->isVectorType() && "Expected vector type");
7749
7750 SmallVector<Expr *, 8> initExprs;
7751 const VectorType *VTy = Ty->castAs<VectorType>();
7752 unsigned numElems = VTy->getNumElements();
7753
7754 // '(...)' form of vector initialization in AltiVec: the number of
7755 // initializers must be one or must match the size of the vector.
7756 // If a single value is specified in the initializer then it will be
7757 // replicated to all the components of the vector
7759 VTy->getElementType()))
7760 return ExprError();
7762 // The number of initializers must be one or must match the size of the
7763 // vector. If a single value is specified in the initializer then it will
7764 // be replicated to all the components of the vector
7765 if (numExprs == 1) {
7766 QualType ElemTy = VTy->getElementType();
7767 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7768 if (Literal.isInvalid())
7769 return ExprError();
7770 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7771 PrepareScalarCast(Literal, ElemTy));
7772 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7773 }
7774 else if (numExprs < numElems) {
7775 Diag(E->getExprLoc(),
7776 diag::err_incorrect_number_of_vector_initializers);
7777 return ExprError();
7778 }
7779 else
7780 initExprs.append(exprs, exprs + numExprs);
7781 }
7782 else {
7783 // For OpenCL, when the number of initializers is a single value,
7784 // it will be replicated to all components of the vector.
7786 numExprs == 1) {
7787 QualType ElemTy = VTy->getElementType();
7788 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7789 if (Literal.isInvalid())
7790 return ExprError();
7791 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7792 PrepareScalarCast(Literal, ElemTy));
7793 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7794 }
7795
7796 initExprs.append(exprs, exprs + numExprs);
7797 }
7798 // FIXME: This means that pretty-printing the final AST will produce curly
7799 // braces instead of the original commas.
7800 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7801 initExprs, LiteralRParenLoc);
7802 initE->setType(Ty);
7803 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7804}
7805
7808 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7809 if (!E)
7810 return OrigExpr;
7811
7812 ExprResult Result(E->getExpr(0));
7813
7814 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7815 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7816 E->getExpr(i));
7817
7818 if (Result.isInvalid()) return ExprError();
7819
7820 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7821}
7822
7825 MultiExprArg Val) {
7826 return ParenListExpr::Create(Context, L, Val, R);
7827}
7828
7829bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7830 SourceLocation QuestionLoc) {
7831 const Expr *NullExpr = LHSExpr;
7832 const Expr *NonPointerExpr = RHSExpr;
7836
7837 if (NullKind == Expr::NPCK_NotNull) {
7838 NullExpr = RHSExpr;
7839 NonPointerExpr = LHSExpr;
7840 NullKind =
7843 }
7844
7845 if (NullKind == Expr::NPCK_NotNull)
7846 return false;
7847
7848 if (NullKind == Expr::NPCK_ZeroExpression)
7849 return false;
7850
7851 if (NullKind == Expr::NPCK_ZeroLiteral) {
7852 // In this case, check to make sure that we got here from a "NULL"
7853 // string in the source code.
7854 NullExpr = NullExpr->IgnoreParenImpCasts();
7855 SourceLocation loc = NullExpr->getExprLoc();
7856 if (!findMacroSpelling(loc, "NULL"))
7857 return false;
7858 }
7859
7860 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7861 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7862 << NonPointerExpr->getType() << DiagType
7863 << NonPointerExpr->getSourceRange();
7864 return true;
7865}
7866
7867/// Return false if the condition expression is valid, true otherwise.
7868static bool checkCondition(Sema &S, const Expr *Cond,
7869 SourceLocation QuestionLoc) {
7870 QualType CondTy = Cond->getType();
7871
7872 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7873 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7874 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7875 << CondTy << Cond->getSourceRange();
7876 return true;
7877 }
7878
7879 // C99 6.5.15p2
7880 if (CondTy->isScalarType()) return false;
7881
7882 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7883 << CondTy << Cond->getSourceRange();
7884 return true;
7885}
7886
7887/// Return false if the NullExpr can be promoted to PointerTy,
7888/// true otherwise.
7890 QualType PointerTy) {
7891 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7892 !NullExpr.get()->isNullPointerConstant(S.Context,
7894 return true;
7895
7896 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7897 return false;
7898}
7899
7900/// Checks compatibility between two pointers and return the resulting
7901/// type.
7903 ExprResult &RHS,
7905 QualType LHSTy = LHS.get()->getType();
7906 QualType RHSTy = RHS.get()->getType();
7907
7908 if (S.Context.hasSameType(LHSTy, RHSTy)) {
7909 // Two identical pointers types are always compatible.
7910 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
7911 }
7912
7913 QualType lhptee, rhptee;
7914
7915 // Get the pointee types.
7916 bool IsBlockPointer = false;
7917 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
7918 lhptee = LHSBTy->getPointeeType();
7919 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
7920 IsBlockPointer = true;
7921 } else {
7922 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
7923 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
7924 }
7925
7926 // C99 6.5.15p6: If both operands are pointers to compatible types or to
7927 // differently qualified versions of compatible types, the result type is
7928 // a pointer to an appropriately qualified version of the composite
7929 // type.
7930
7931 // Only CVR-qualifiers exist in the standard, and the differently-qualified
7932 // clause doesn't make sense for our extensions. E.g. address space 2 should
7933 // be incompatible with address space 3: they may live on different devices or
7934 // anything.
7935 Qualifiers lhQual = lhptee.getQualifiers();
7936 Qualifiers rhQual = rhptee.getQualifiers();
7937
7938 LangAS ResultAddrSpace = LangAS::Default;
7939 LangAS LAddrSpace = lhQual.getAddressSpace();
7940 LangAS RAddrSpace = rhQual.getAddressSpace();
7941
7942 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
7943 // spaces is disallowed.
7944 if (lhQual.isAddressSpaceSupersetOf(rhQual))
7945 ResultAddrSpace = LAddrSpace;
7946 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
7947 ResultAddrSpace = RAddrSpace;
7948 else {
7949 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7950 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
7951 << RHS.get()->getSourceRange();
7952 return QualType();
7953 }
7954
7955 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
7956 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
7957 lhQual.removeCVRQualifiers();
7958 rhQual.removeCVRQualifiers();
7959
7960 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
7961 // (C99 6.7.3) for address spaces. We assume that the check should behave in
7962 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
7963 // qual types are compatible iff
7964 // * corresponded types are compatible
7965 // * CVR qualifiers are equal
7966 // * address spaces are equal
7967 // Thus for conditional operator we merge CVR and address space unqualified
7968 // pointees and if there is a composite type we return a pointer to it with
7969 // merged qualifiers.
7970 LHSCastKind =
7971 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7972 RHSCastKind =
7973 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
7974 lhQual.removeAddressSpace();
7975 rhQual.removeAddressSpace();
7976
7977 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
7978 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
7979
7980 QualType CompositeTy = S.Context.mergeTypes(
7981 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
7982 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
7983
7984 if (CompositeTy.isNull()) {
7985 // In this situation, we assume void* type. No especially good
7986 // reason, but this is what gcc does, and we do have to pick
7987 // to get a consistent AST.
7988 QualType incompatTy;
7989 incompatTy = S.Context.getPointerType(
7990 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
7991 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
7992 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
7993
7994 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
7995 // for casts between types with incompatible address space qualifiers.
7996 // For the following code the compiler produces casts between global and
7997 // local address spaces of the corresponded innermost pointees:
7998 // local int *global *a;
7999 // global int *global *b;
8000 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8001 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8002 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8003 << RHS.get()->getSourceRange();
8004
8005 return incompatTy;
8006 }
8007
8008 // The pointer types are compatible.
8009 // In case of OpenCL ResultTy should have the address space qualifier
8010 // which is a superset of address spaces of both the 2nd and the 3rd
8011 // operands of the conditional operator.
8012 QualType ResultTy = [&, ResultAddrSpace]() {
8013 if (S.getLangOpts().OpenCL) {
8014 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8015 CompositeQuals.setAddressSpace(ResultAddrSpace);
8016 return S.Context
8017 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8018 .withCVRQualifiers(MergedCVRQual);
8019 }
8020 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8021 }();
8022 if (IsBlockPointer)
8023 ResultTy = S.Context.getBlockPointerType(ResultTy);
8024 else
8025 ResultTy = S.Context.getPointerType(ResultTy);
8026
8027 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8028 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8029 return ResultTy;
8030}
8031
8032/// Return the resulting type when the operands are both block pointers.
8034 ExprResult &LHS,
8035 ExprResult &RHS,
8037 QualType LHSTy = LHS.get()->getType();
8038 QualType RHSTy = RHS.get()->getType();
8039
8040 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8041 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8043 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8044 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8045 return destType;
8046 }
8047 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8048 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8049 << RHS.get()->getSourceRange();
8050 return QualType();
8051 }
8052
8053 // We have 2 block pointer types.
8054 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8055}
8056
8057/// Return the resulting type when the operands are both pointers.
8058static QualType
8060 ExprResult &RHS,
8062 // get the pointer types
8063 QualType LHSTy = LHS.get()->getType();
8064 QualType RHSTy = RHS.get()->getType();
8065
8066 // get the "pointed to" types
8067 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8068 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8069
8070 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8071 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8072 // Figure out necessary qualifiers (C99 6.5.15p6)
8073 QualType destPointee
8074 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8075 QualType destType = S.Context.getPointerType(destPointee);
8076 // Add qualifiers if necessary.
8077 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8078 // Promote to void*.
8079 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8080 return destType;
8081 }
8082 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8083 QualType destPointee
8084 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8085 QualType destType = S.Context.getPointerType(destPointee);
8086 // Add qualifiers if necessary.
8087 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8088 // Promote to void*.
8089 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8090 return destType;
8091 }
8092
8093 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8094}
8095
8096/// Return false if the first expression is not an integer and the second
8097/// expression is not a pointer, true otherwise.
8099 Expr* PointerExpr, SourceLocation Loc,
8100 bool IsIntFirstExpr) {
8101 if (!PointerExpr->getType()->isPointerType() ||
8102 !Int.get()->getType()->isIntegerType())
8103 return false;
8104
8105 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8106 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8107
8108 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8109 << Expr1->getType() << Expr2->getType()
8110 << Expr1->getSourceRange() << Expr2->getSourceRange();
8111 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8112 CK_IntegralToPointer);
8113 return true;
8114}
8115
8116/// Simple conversion between integer and floating point types.
8117///
8118/// Used when handling the OpenCL conditional operator where the
8119/// condition is a vector while the other operands are scalar.
8120///
8121/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8122/// types are either integer or floating type. Between the two
8123/// operands, the type with the higher rank is defined as the "result
8124/// type". The other operand needs to be promoted to the same type. No
8125/// other type promotion is allowed. We cannot use
8126/// UsualArithmeticConversions() for this purpose, since it always
8127/// promotes promotable types.
8129 ExprResult &RHS,
8130 SourceLocation QuestionLoc) {
8132 if (LHS.isInvalid())
8133 return QualType();
8135 if (RHS.isInvalid())
8136 return QualType();
8137
8138 // For conversion purposes, we ignore any qualifiers.
8139 // For example, "const float" and "float" are equivalent.
8140 QualType LHSType =
8142 QualType RHSType =
8144
8145 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8146 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8147 << LHSType << LHS.get()->getSourceRange();
8148 return QualType();
8149 }
8150
8151 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8152 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8153 << RHSType << RHS.get()->getSourceRange();
8154 return QualType();
8155 }
8156
8157 // If both types are identical, no conversion is needed.
8158 if (LHSType == RHSType)
8159 return LHSType;
8160
8161 // Now handle "real" floating types (i.e. float, double, long double).
8162 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8163 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8164 /*IsCompAssign = */ false);
8165
8166 // Finally, we have two differing integer types.
8167 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8168 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8169}
8170
8171/// Convert scalar operands to a vector that matches the
8172/// condition in length.
8173///
8174/// Used when handling the OpenCL conditional operator where the
8175/// condition is a vector while the other operands are scalar.
8176///
8177/// We first compute the "result type" for the scalar operands
8178/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8179/// into a vector of that type where the length matches the condition
8180/// vector type. s6.11.6 requires that the element types of the result
8181/// and the condition must have the same number of bits.
8182static QualType
8184 QualType CondTy, SourceLocation QuestionLoc) {
8185 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8186 if (ResTy.isNull()) return QualType();
8187
8188 const VectorType *CV = CondTy->getAs<VectorType>();
8189 assert(CV);
8190
8191 // Determine the vector result type
8192 unsigned NumElements = CV->getNumElements();
8193 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8194
8195 // Ensure that all types have the same number of bits
8197 != S.Context.getTypeSize(ResTy)) {
8198 // Since VectorTy is created internally, it does not pretty print
8199 // with an OpenCL name. Instead, we just print a description.
8200 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8201 SmallString<64> Str;
8202 llvm::raw_svector_ostream OS(Str);
8203 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8204 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8205 << CondTy << OS.str();
8206 return QualType();
8207 }
8208
8209 // Convert operands to the vector result type
8210 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8211 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8212
8213 return VectorTy;
8214}
8215
8216/// Return false if this is a valid OpenCL condition vector
8218 SourceLocation QuestionLoc) {
8219 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8220 // integral type.
8221 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8222 assert(CondTy);
8223 QualType EleTy = CondTy->getElementType();
8224 if (EleTy->isIntegerType()) return false;
8225
8226 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8227 << Cond->getType() << Cond->getSourceRange();
8228 return true;
8229}
8230
8231/// Return false if the vector condition type and the vector
8232/// result type are compatible.
8233///
8234/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8235/// number of elements, and their element types have the same number
8236/// of bits.
8237static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8238 SourceLocation QuestionLoc) {
8239 const VectorType *CV = CondTy->getAs<VectorType>();
8240 const VectorType *RV = VecResTy->getAs<VectorType>();
8241 assert(CV && RV);
8242
8243 if (CV->getNumElements() != RV->getNumElements()) {
8244 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8245 << CondTy << VecResTy;
8246 return true;
8247 }
8248
8249 QualType CVE = CV->getElementType();
8250 QualType RVE = RV->getElementType();
8251
8252 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8253 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8254 << CondTy << VecResTy;
8255 return true;
8256 }
8257
8258 return false;
8259}
8260
8261/// Return the resulting type for the conditional operator in
8262/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8263/// s6.3.i) when the condition is a vector type.
8264static QualType
8266 ExprResult &LHS, ExprResult &RHS,
8267 SourceLocation QuestionLoc) {
8269 if (Cond.isInvalid())
8270 return QualType();
8271 QualType CondTy = Cond.get()->getType();
8272
8273 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8274 return QualType();
8275
8276 // If either operand is a vector then find the vector type of the
8277 // result as specified in OpenCL v1.1 s6.3.i.
8278 if (LHS.get()->getType()->isVectorType() ||
8279 RHS.get()->getType()->isVectorType()) {
8280 bool IsBoolVecLang =
8281 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8282 QualType VecResTy =
8283 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8284 /*isCompAssign*/ false,
8285 /*AllowBothBool*/ true,
8286 /*AllowBoolConversions*/ false,
8287 /*AllowBooleanOperation*/ IsBoolVecLang,
8288 /*ReportInvalid*/ true);
8289 if (VecResTy.isNull())
8290 return QualType();
8291 // The result type must match the condition type as specified in
8292 // OpenCL v1.1 s6.11.6.
8293 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8294 return QualType();
8295 return VecResTy;
8296 }
8297
8298 // Both operands are scalar.
8299 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8300}
8301
8302/// Return true if the Expr is block type
8303static bool checkBlockType(Sema &S, const Expr *E) {
8304 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8305 QualType Ty = CE->getCallee()->getType();
8306 if (Ty->isBlockPointerType()) {
8307 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8308 return true;
8309 }
8310 }
8311 return false;
8312}
8313
8314/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8315/// In that case, LHS = cond.
8316/// C99 6.5.15
8318 ExprResult &RHS, ExprValueKind &VK,
8319 ExprObjectKind &OK,
8320 SourceLocation QuestionLoc) {
8321
8322 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8323 if (!LHSResult.isUsable()) return QualType();
8324 LHS = LHSResult;
8325
8326 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8327 if (!RHSResult.isUsable()) return QualType();
8328 RHS = RHSResult;
8329
8330 // C++ is sufficiently different to merit its own checker.
8331 if (getLangOpts().CPlusPlus)
8332 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8333
8334 VK = VK_PRValue;
8335 OK = OK_Ordinary;
8336
8338 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8339 RHS.get()->isTypeDependent())) {
8340 assert(!getLangOpts().CPlusPlus);
8341 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8342 RHS.get()->containsErrors()) &&
8343 "should only occur in error-recovery path.");
8344 return Context.DependentTy;
8345 }
8346
8347 // The OpenCL operator with a vector condition is sufficiently
8348 // different to merit its own checker.
8349 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8350 Cond.get()->getType()->isExtVectorType())
8351 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8352
8353 // First, check the condition.
8354 Cond = UsualUnaryConversions(Cond.get());
8355 if (Cond.isInvalid())
8356 return QualType();
8357 if (checkCondition(*this, Cond.get(), QuestionLoc))
8358 return QualType();
8359
8360 // Handle vectors.
8361 if (LHS.get()->getType()->isVectorType() ||
8362 RHS.get()->getType()->isVectorType())
8363 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8364 /*AllowBothBool*/ true,
8365 /*AllowBoolConversions*/ false,
8366 /*AllowBooleanOperation*/ false,
8367 /*ReportInvalid*/ true);
8368
8369 QualType ResTy =
8370 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8371 if (LHS.isInvalid() || RHS.isInvalid())
8372 return QualType();
8373
8374 // WebAssembly tables are not allowed as conditional LHS or RHS.
8375 QualType LHSTy = LHS.get()->getType();
8376 QualType RHSTy = RHS.get()->getType();
8377 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8378 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8379 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8380 return QualType();
8381 }
8382
8383 // Diagnose attempts to convert between __ibm128, __float128 and long double
8384 // where such conversions currently can't be handled.
8385 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8386 Diag(QuestionLoc,
8387 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8388 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8389 return QualType();
8390 }
8391
8392 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8393 // selection operator (?:).
8394 if (getLangOpts().OpenCL &&
8395 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8396 return QualType();
8397 }
8398
8399 // If both operands have arithmetic type, do the usual arithmetic conversions
8400 // to find a common type: C99 6.5.15p3,5.
8401 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8402 // Disallow invalid arithmetic conversions, such as those between bit-
8403 // precise integers types of different sizes, or between a bit-precise
8404 // integer and another type.
8405 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8406 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8407 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8408 << RHS.get()->getSourceRange();
8409 return QualType();
8410 }
8411
8412 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8413 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8414
8415 return ResTy;
8416 }
8417
8418 // If both operands are the same structure or union type, the result is that
8419 // type.
8420 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8421 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8422 if (LHSRT->getDecl() == RHSRT->getDecl())
8423 // "If both the operands have structure or union type, the result has
8424 // that type." This implies that CV qualifiers are dropped.
8426 RHSTy.getUnqualifiedType());
8427 // FIXME: Type of conditional expression must be complete in C mode.
8428 }
8429
8430 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8431 // The following || allows only one side to be void (a GCC-ism).
8432 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8433 QualType ResTy;
8434 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8435 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8436 } else if (RHSTy->isVoidType()) {
8437 ResTy = RHSTy;
8438 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8439 << RHS.get()->getSourceRange();
8440 } else {
8441 ResTy = LHSTy;
8442 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8443 << LHS.get()->getSourceRange();
8444 }
8445 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8446 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8447 return ResTy;
8448 }
8449
8450 // C23 6.5.15p7:
8451 // ... if both the second and third operands have nullptr_t type, the
8452 // result also has that type.
8453 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8454 return ResTy;
8455
8456 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8457 // the type of the other operand."
8458 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8459 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8460
8461 // All objective-c pointer type analysis is done here.
8462 QualType compositeType =
8463 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8464 if (LHS.isInvalid() || RHS.isInvalid())
8465 return QualType();
8466 if (!compositeType.isNull())
8467 return compositeType;
8468
8469
8470 // Handle block pointer types.
8471 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8472 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8473 QuestionLoc);
8474
8475 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8476 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8477 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8478 QuestionLoc);
8479
8480 // GCC compatibility: soften pointer/integer mismatch. Note that
8481 // null pointers have been filtered out by this point.
8482 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8483 /*IsIntFirstExpr=*/true))
8484 return RHSTy;
8485 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8486 /*IsIntFirstExpr=*/false))
8487 return LHSTy;
8488
8489 // Emit a better diagnostic if one of the expressions is a null pointer
8490 // constant and the other is not a pointer type. In this case, the user most
8491 // likely forgot to take the address of the other expression.
8492 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8493 return QualType();
8494
8495 // Finally, if the LHS and RHS types are canonically the same type, we can
8496 // use the common sugared type.
8497 if (Context.hasSameType(LHSTy, RHSTy))
8498 return Context.getCommonSugaredType(LHSTy, RHSTy);
8499
8500 // Otherwise, the operands are not compatible.
8501 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8502 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8503 << RHS.get()->getSourceRange();
8504 return QualType();
8505}
8506
8507/// SuggestParentheses - Emit a note with a fixit hint that wraps
8508/// ParenRange in parentheses.
8510 const PartialDiagnostic &Note,
8511 SourceRange ParenRange) {
8512 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8513 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8514 EndLoc.isValid()) {
8515 Self.Diag(Loc, Note)
8516 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8517 << FixItHint::CreateInsertion(EndLoc, ")");
8518 } else {
8519 // We can't display the parentheses, so just show the bare note.
8520 Self.Diag(Loc, Note) << ParenRange;
8521 }
8522}
8523
8525 return BinaryOperator::isAdditiveOp(Opc) ||
8527 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8528 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8529 // not any of the logical operators. Bitwise-xor is commonly used as a
8530 // logical-xor because there is no logical-xor operator. The logical
8531 // operators, including uses of xor, have a high false positive rate for
8532 // precedence warnings.
8533}
8534
8535/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8536/// expression, either using a built-in or overloaded operator,
8537/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8538/// expression.
8540 const Expr **RHSExprs) {
8541 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8542 E = E->IgnoreImpCasts();
8544 E = E->IgnoreImpCasts();
8545 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8546 E = MTE->getSubExpr();
8547 E = E->IgnoreImpCasts();
8548 }
8549
8550 // Built-in binary operator.
8551 if (const auto *OP = dyn_cast<BinaryOperator>(E);
8552 OP && IsArithmeticOp(OP->getOpcode())) {
8553 *Opcode = OP->getOpcode();
8554 *RHSExprs = OP->getRHS();
8555 return true;
8556 }
8557
8558 // Overloaded operator.
8559 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8560 if (Call->getNumArgs() != 2)
8561 return false;
8562
8563 // Make sure this is really a binary operator that is safe to pass into
8564 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8565 OverloadedOperatorKind OO = Call->getOperator();
8566 if (OO < OO_Plus || OO > OO_Arrow ||
8567 OO == OO_PlusPlus || OO == OO_MinusMinus)
8568 return false;
8569
8571 if (IsArithmeticOp(OpKind)) {
8572 *Opcode = OpKind;
8573 *RHSExprs = Call->getArg(1);
8574 return true;
8575 }
8576 }
8577
8578 return false;
8579}
8580
8581/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8582/// or is a logical expression such as (x==y) which has int type, but is
8583/// commonly interpreted as boolean.
8584static bool ExprLooksBoolean(const Expr *E) {
8585 E = E->IgnoreParenImpCasts();
8586
8587 if (E->getType()->isBooleanType())
8588 return true;
8589 if (const auto *OP = dyn_cast<BinaryOperator>(E))
8590 return OP->isComparisonOp() || OP->isLogicalOp();
8591 if (const auto *OP = dyn_cast<UnaryOperator>(E))
8592 return OP->getOpcode() == UO_LNot;
8593 if (E->getType()->isPointerType())
8594 return true;
8595 // FIXME: What about overloaded operator calls returning "unspecified boolean
8596 // type"s (commonly pointer-to-members)?
8597
8598 return false;
8599}
8600
8601/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8602/// and binary operator are mixed in a way that suggests the programmer assumed
8603/// the conditional operator has higher precedence, for example:
8604/// "int x = a + someBinaryCondition ? 1 : 2".
8606 Expr *Condition, const Expr *LHSExpr,
8607 const Expr *RHSExpr) {
8608 BinaryOperatorKind CondOpcode;
8609 const Expr *CondRHS;
8610
8611 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8612 return;
8613 if (!ExprLooksBoolean(CondRHS))
8614 return;
8615
8616 // The condition is an arithmetic binary expression, with a right-
8617 // hand side that looks boolean, so warn.
8618
8619 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8620 ? diag::warn_precedence_bitwise_conditional
8621 : diag::warn_precedence_conditional;
8622
8623 Self.Diag(OpLoc, DiagID)
8624 << Condition->getSourceRange()
8625 << BinaryOperator::getOpcodeStr(CondOpcode);
8626
8628 Self, OpLoc,
8629 Self.PDiag(diag::note_precedence_silence)
8630 << BinaryOperator::getOpcodeStr(CondOpcode),
8631 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8632
8633 SuggestParentheses(Self, OpLoc,
8634 Self.PDiag(diag::note_precedence_conditional_first),
8635 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8636}
8637
8638/// Compute the nullability of a conditional expression.
8640 QualType LHSTy, QualType RHSTy,
8641 ASTContext &Ctx) {
8642 if (!ResTy->isAnyPointerType())
8643 return ResTy;
8644
8645 auto GetNullability = [](QualType Ty) {
8646 std::optional<NullabilityKind> Kind = Ty->getNullability();
8647 if (Kind) {
8648 // For our purposes, treat _Nullable_result as _Nullable.
8651 return *Kind;
8652 }
8654 };
8655
8656 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8657 NullabilityKind MergedKind;
8658
8659 // Compute nullability of a binary conditional expression.
8660 if (IsBin) {
8661 if (LHSKind == NullabilityKind::NonNull)
8662 MergedKind = NullabilityKind::NonNull;
8663 else
8664 MergedKind = RHSKind;
8665 // Compute nullability of a normal conditional expression.
8666 } else {
8667 if (LHSKind == NullabilityKind::Nullable ||
8668 RHSKind == NullabilityKind::Nullable)
8669 MergedKind = NullabilityKind::Nullable;
8670 else if (LHSKind == NullabilityKind::NonNull)
8671 MergedKind = RHSKind;
8672 else if (RHSKind == NullabilityKind::NonNull)
8673 MergedKind = LHSKind;
8674 else
8675 MergedKind = NullabilityKind::Unspecified;
8676 }
8677
8678 // Return if ResTy already has the correct nullability.
8679 if (GetNullability(ResTy) == MergedKind)
8680 return ResTy;
8681
8682 // Strip all nullability from ResTy.
8683 while (ResTy->getNullability())
8684 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8685
8686 // Create a new AttributedType with the new nullability kind.
8687 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
8688 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
8689}
8690
8692 SourceLocation ColonLoc,
8693 Expr *CondExpr, Expr *LHSExpr,
8694 Expr *RHSExpr) {
8696 // C cannot handle TypoExpr nodes in the condition because it
8697 // doesn't handle dependent types properly, so make sure any TypoExprs have
8698 // been dealt with before checking the operands.
8699 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8700 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8701 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8702
8703 if (!CondResult.isUsable())
8704 return ExprError();
8705
8706 if (LHSExpr) {
8707 if (!LHSResult.isUsable())
8708 return ExprError();
8709 }
8710
8711 if (!RHSResult.isUsable())
8712 return ExprError();
8713
8714 CondExpr = CondResult.get();
8715 LHSExpr = LHSResult.get();
8716 RHSExpr = RHSResult.get();
8717 }
8718
8719 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8720 // was the condition.
8721 OpaqueValueExpr *opaqueValue = nullptr;
8722 Expr *commonExpr = nullptr;
8723 if (!LHSExpr) {
8724 commonExpr = CondExpr;
8725 // Lower out placeholder types first. This is important so that we don't
8726 // try to capture a placeholder. This happens in few cases in C++; such
8727 // as Objective-C++'s dictionary subscripting syntax.
8728 if (commonExpr->hasPlaceholderType()) {
8729 ExprResult result = CheckPlaceholderExpr(commonExpr);
8730 if (!result.isUsable()) return ExprError();
8731 commonExpr = result.get();
8732 }
8733 // We usually want to apply unary conversions *before* saving, except
8734 // in the special case of a C++ l-value conditional.
8735 if (!(getLangOpts().CPlusPlus
8736 && !commonExpr->isTypeDependent()
8737 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8738 && commonExpr->isGLValue()
8739 && commonExpr->isOrdinaryOrBitFieldObject()
8740 && RHSExpr->isOrdinaryOrBitFieldObject()
8741 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8742 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8743 if (commonRes.isInvalid())
8744 return ExprError();
8745 commonExpr = commonRes.get();
8746 }
8747
8748 // If the common expression is a class or array prvalue, materialize it
8749 // so that we can safely refer to it multiple times.
8750 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8751 commonExpr->getType()->isArrayType())) {
8752 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8753 if (MatExpr.isInvalid())
8754 return ExprError();
8755 commonExpr = MatExpr.get();
8756 }
8757
8758 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8759 commonExpr->getType(),
8760 commonExpr->getValueKind(),
8761 commonExpr->getObjectKind(),
8762 commonExpr);
8763 LHSExpr = CondExpr = opaqueValue;
8764 }
8765
8766 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8769 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8770 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8771 VK, OK, QuestionLoc);
8772 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8773 RHS.isInvalid())
8774 return ExprError();
8775
8776 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8777 RHS.get());
8778
8779 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8780
8781 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8782 Context);
8783
8784 if (!commonExpr)
8785 return new (Context)
8786 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8787 RHS.get(), result, VK, OK);
8788
8790 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8791 ColonLoc, result, VK, OK);
8792}
8793
8795 unsigned FromAttributes = 0, ToAttributes = 0;
8796 if (const auto *FromFn =
8797 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
8798 FromAttributes =
8799 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8800 if (const auto *ToFn =
8801 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
8802 ToAttributes =
8803 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8804
8805 return FromAttributes != ToAttributes;
8806}
8807
8808// Check if we have a conversion between incompatible cmse function pointer
8809// types, that is, a conversion between a function pointer with the
8810// cmse_nonsecure_call attribute and one without.
8812 QualType ToType) {
8813 if (const auto *ToFn =
8814 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8815 if (const auto *FromFn =
8816 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8817 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8818 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8819
8820 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8821 }
8822 }
8823 return false;
8824}
8825
8826// checkPointerTypesForAssignment - This is a very tricky routine (despite
8827// being closely modeled after the C99 spec:-). The odd characteristic of this
8828// routine is it effectively iqnores the qualifiers on the top level pointee.
8829// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8830// FIXME: add a couple examples in this comment.
8834 assert(LHSType.isCanonical() && "LHS not canonicalized!");
8835 assert(RHSType.isCanonical() && "RHS not canonicalized!");
8836
8837 // get the "pointed to" type (ignoring qualifiers at the top level)
8838 const Type *lhptee, *rhptee;
8839 Qualifiers lhq, rhq;
8840 std::tie(lhptee, lhq) =
8841 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8842 std::tie(rhptee, rhq) =
8843 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8844
8846
8847 // C99 6.5.16.1p1: This following citation is common to constraints
8848 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8849 // qualifiers of the type *pointed to* by the right;
8850
8851 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8852 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8854 // Ignore lifetime for further calculation.
8855 lhq.removeObjCLifetime();
8856 rhq.removeObjCLifetime();
8857 }
8858
8859 if (!lhq.compatiblyIncludes(rhq)) {
8860 // Treat address-space mismatches as fatal.
8861 if (!lhq.isAddressSpaceSupersetOf(rhq))
8863
8864 // It's okay to add or remove GC or lifetime qualifiers when converting to
8865 // and from void*.
8866 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
8869 && (lhptee->isVoidType() || rhptee->isVoidType()))
8870 ; // keep old
8871
8872 // Treat lifetime mismatches as fatal.
8873 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8875
8876 // For GCC/MS compatibility, other qualifier mismatches are treated
8877 // as still compatible in C.
8879 }
8880
8881 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8882 // incomplete type and the other is a pointer to a qualified or unqualified
8883 // version of void...
8884 if (lhptee->isVoidType()) {
8885 if (rhptee->isIncompleteOrObjectType())
8886 return ConvTy;
8887
8888 // As an extension, we allow cast to/from void* to function pointer.
8889 assert(rhptee->isFunctionType());
8891 }
8892
8893 if (rhptee->isVoidType()) {
8894 if (lhptee->isIncompleteOrObjectType())
8895 return ConvTy;
8896
8897 // As an extension, we allow cast to/from void* to function pointer.
8898 assert(lhptee->isFunctionType());
8900 }
8901
8902 if (!S.Diags.isIgnored(
8903 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
8904 Loc) &&
8905 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
8906 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
8908
8909 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8910 // unqualified versions of compatible types, ...
8911 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8912 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8913 // Check if the pointee types are compatible ignoring the sign.
8914 // We explicitly check for char so that we catch "char" vs
8915 // "unsigned char" on systems where "char" is unsigned.
8916 if (lhptee->isCharType())
8917 ltrans = S.Context.UnsignedCharTy;
8918 else if (lhptee->hasSignedIntegerRepresentation())
8919 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
8920
8921 if (rhptee->isCharType())
8922 rtrans = S.Context.UnsignedCharTy;
8923 else if (rhptee->hasSignedIntegerRepresentation())
8924 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
8925
8926 if (ltrans == rtrans) {
8927 // Types are compatible ignoring the sign. Qualifier incompatibility
8928 // takes priority over sign incompatibility because the sign
8929 // warning can be disabled.
8930 if (ConvTy != Sema::Compatible)
8931 return ConvTy;
8932
8934 }
8935
8936 // If we are a multi-level pointer, it's possible that our issue is simply
8937 // one of qualification - e.g. char ** -> const char ** is not allowed. If
8938 // the eventual target type is the same and the pointers have the same
8939 // level of indirection, this must be the issue.
8940 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
8941 do {
8942 std::tie(lhptee, lhq) =
8943 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
8944 std::tie(rhptee, rhq) =
8945 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
8946
8947 // Inconsistent address spaces at this point is invalid, even if the
8948 // address spaces would be compatible.
8949 // FIXME: This doesn't catch address space mismatches for pointers of
8950 // different nesting levels, like:
8951 // __local int *** a;
8952 // int ** b = a;
8953 // It's not clear how to actually determine when such pointers are
8954 // invalidly incompatible.
8955 if (lhq.getAddressSpace() != rhq.getAddressSpace())
8957
8958 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
8959
8960 if (lhptee == rhptee)
8962 }
8963
8964 // General pointer incompatibility takes priority over qualifiers.
8965 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
8968 }
8969 if (!S.getLangOpts().CPlusPlus &&
8970 S.IsFunctionConversion(ltrans, rtrans, ltrans))
8972 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
8974 if (S.IsInvalidSMECallConversion(rtrans, ltrans))
8976 return ConvTy;
8977}
8978
8979/// checkBlockPointerTypesForAssignment - This routine determines whether two
8980/// block pointer types are compatible or whether a block and normal pointer
8981/// are compatible. It is more restrict than comparing two function pointer
8982// types.
8985 QualType RHSType) {
8986 assert(LHSType.isCanonical() && "LHS not canonicalized!");
8987 assert(RHSType.isCanonical() && "RHS not canonicalized!");
8988
8989 QualType lhptee, rhptee;
8990
8991 // get the "pointed to" type (ignoring qualifiers at the top level)
8992 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
8993 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
8994
8995 // In C++, the types have to match exactly.
8996 if (S.getLangOpts().CPlusPlus)
8998
9000
9001 // For blocks we enforce that qualifiers are identical.
9002 Qualifiers LQuals = lhptee.getLocalQualifiers();
9003 Qualifiers RQuals = rhptee.getLocalQualifiers();
9004 if (S.getLangOpts().OpenCL) {
9005 LQuals.removeAddressSpace();
9006 RQuals.removeAddressSpace();
9007 }
9008 if (LQuals != RQuals)
9010
9011 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9012 // assignment.
9013 // The current behavior is similar to C++ lambdas. A block might be
9014 // assigned to a variable iff its return type and parameters are compatible
9015 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9016 // an assignment. Presumably it should behave in way that a function pointer
9017 // assignment does in C, so for each parameter and return type:
9018 // * CVR and address space of LHS should be a superset of CVR and address
9019 // space of RHS.
9020 // * unqualified types should be compatible.
9021 if (S.getLangOpts().OpenCL) {
9023 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9024 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9026 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9028
9029 return ConvTy;
9030}
9031
9032/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9033/// for assignment compatibility.
9036 QualType RHSType) {
9037 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9038 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9039
9040 if (LHSType->isObjCBuiltinType()) {
9041 // Class is not compatible with ObjC object pointers.
9042 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9043 !RHSType->isObjCQualifiedClassType())
9045 return Sema::Compatible;
9046 }
9047 if (RHSType->isObjCBuiltinType()) {
9048 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9049 !LHSType->isObjCQualifiedClassType())
9051 return Sema::Compatible;
9052 }
9053 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9054 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9055
9056 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9057 // make an exception for id<P>
9058 !LHSType->isObjCQualifiedIdType())
9060
9061 if (S.Context.typesAreCompatible(LHSType, RHSType))
9062 return Sema::Compatible;
9063 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9066}
9067
9070 QualType LHSType, QualType RHSType) {
9071 // Fake up an opaque expression. We don't actually care about what
9072 // cast operations are required, so if CheckAssignmentConstraints
9073 // adds casts to this they'll be wasted, but fortunately that doesn't
9074 // usually happen on valid code.
9075 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9076 ExprResult RHSPtr = &RHSExpr;
9077 CastKind K;
9078
9079 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9080}
9081
9082/// This helper function returns true if QT is a vector type that has element
9083/// type ElementType.
9084static bool isVector(QualType QT, QualType ElementType) {
9085 if (const VectorType *VT = QT->getAs<VectorType>())
9086 return VT->getElementType().getCanonicalType() == ElementType;
9087 return false;
9088}
9089
9090/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9091/// has code to accommodate several GCC extensions when type checking
9092/// pointers. Here are some objectionable examples that GCC considers warnings:
9093///
9094/// int a, *pint;
9095/// short *pshort;
9096/// struct foo *pfoo;
9097///
9098/// pint = pshort; // warning: assignment from incompatible pointer type
9099/// a = pint; // warning: assignment makes integer from pointer without a cast
9100/// pint = a; // warning: assignment makes pointer from integer without a cast
9101/// pint = pfoo; // warning: assignment from incompatible pointer type
9102///
9103/// As a result, the code for dealing with pointers is more complex than the
9104/// C99 spec dictates.
9105///
9106/// Sets 'Kind' for any result kind except Incompatible.
9109 CastKind &Kind, bool ConvertRHS) {
9110 QualType RHSType = RHS.get()->getType();
9111 QualType OrigLHSType = LHSType;
9112
9113 // Get canonical types. We're not formatting these types, just comparing
9114 // them.
9115 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9116 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9117
9118 // Common case: no conversion required.
9119 if (LHSType == RHSType) {
9120 Kind = CK_NoOp;
9121 return Compatible;
9122 }
9123
9124 // If the LHS has an __auto_type, there are no additional type constraints
9125 // to be worried about.
9126 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9127 if (AT->isGNUAutoType()) {
9128 Kind = CK_NoOp;
9129 return Compatible;
9130 }
9131 }
9132
9133 // If we have an atomic type, try a non-atomic assignment, then just add an
9134 // atomic qualification step.
9135 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9137 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9138 if (result != Compatible)
9139 return result;
9140 if (Kind != CK_NoOp && ConvertRHS)
9141 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9142 Kind = CK_NonAtomicToAtomic;
9143 return Compatible;
9144 }
9145
9146 // If the left-hand side is a reference type, then we are in a
9147 // (rare!) case where we've allowed the use of references in C,
9148 // e.g., as a parameter type in a built-in function. In this case,
9149 // just make sure that the type referenced is compatible with the
9150 // right-hand side type. The caller is responsible for adjusting
9151 // LHSType so that the resulting expression does not have reference
9152 // type.
9153 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9154 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9155 Kind = CK_LValueBitCast;
9156 return Compatible;
9157 }
9158 return Incompatible;
9159 }
9160
9161 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9162 // to the same ExtVector type.
9163 if (LHSType->isExtVectorType()) {
9164 if (RHSType->isExtVectorType())
9165 return Incompatible;
9166 if (RHSType->isArithmeticType()) {
9167 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9168 if (ConvertRHS)
9169 RHS = prepareVectorSplat(LHSType, RHS.get());
9170 Kind = CK_VectorSplat;
9171 return Compatible;
9172 }
9173 }
9174
9175 // Conversions to or from vector type.
9176 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9177 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9178 // Allow assignments of an AltiVec vector type to an equivalent GCC
9179 // vector type and vice versa
9180 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9181 Kind = CK_BitCast;
9182 return Compatible;
9183 }
9184
9185 // If we are allowing lax vector conversions, and LHS and RHS are both
9186 // vectors, the total size only needs to be the same. This is a bitcast;
9187 // no bits are changed but the result type is different.
9188 if (isLaxVectorConversion(RHSType, LHSType)) {
9189 // The default for lax vector conversions with Altivec vectors will
9190 // change, so if we are converting between vector types where
9191 // at least one is an Altivec vector, emit a warning.
9192 if (Context.getTargetInfo().getTriple().isPPC() &&
9193 anyAltivecTypes(RHSType, LHSType) &&
9194 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9195 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9196 << RHSType << LHSType;
9197 Kind = CK_BitCast;
9198 return IncompatibleVectors;
9199 }
9200 }
9201
9202 // When the RHS comes from another lax conversion (e.g. binops between
9203 // scalars and vectors) the result is canonicalized as a vector. When the
9204 // LHS is also a vector, the lax is allowed by the condition above. Handle
9205 // the case where LHS is a scalar.
9206 if (LHSType->isScalarType()) {
9207 const VectorType *VecType = RHSType->getAs<VectorType>();
9208 if (VecType && VecType->getNumElements() == 1 &&
9209 isLaxVectorConversion(RHSType, LHSType)) {
9210 if (Context.getTargetInfo().getTriple().isPPC() &&
9212 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9214 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9215 << RHSType << LHSType;
9216 ExprResult *VecExpr = &RHS;
9217 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9218 Kind = CK_BitCast;
9219 return Compatible;
9220 }
9221 }
9222
9223 // Allow assignments between fixed-length and sizeless SVE vectors.
9224 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9225 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9226 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9227 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9228 Kind = CK_BitCast;
9229 return Compatible;
9230 }
9231
9232 // Allow assignments between fixed-length and sizeless RVV vectors.
9233 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9234 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9235 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9236 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9237 Kind = CK_BitCast;
9238 return Compatible;
9239 }
9240 }
9241
9242 return Incompatible;
9243 }
9244
9245 // Diagnose attempts to convert between __ibm128, __float128 and long double
9246 // where such conversions currently can't be handled.
9247 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9248 return Incompatible;
9249
9250 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9251 // discards the imaginary part.
9252 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9253 !LHSType->getAs<ComplexType>())
9254 return Incompatible;
9255
9256 // Arithmetic conversions.
9257 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9258 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9259 if (ConvertRHS)
9260 Kind = PrepareScalarCast(RHS, LHSType);
9261 return Compatible;
9262 }
9263
9264 // Conversions to normal pointers.
9265 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9266 // U* -> T*
9267 if (isa<PointerType>(RHSType)) {
9268 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9269 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9270 if (AddrSpaceL != AddrSpaceR)
9271 Kind = CK_AddressSpaceConversion;
9272 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9273 Kind = CK_NoOp;
9274 else
9275 Kind = CK_BitCast;
9276 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9277 RHS.get()->getBeginLoc());
9278 }
9279
9280 // int -> T*
9281 if (RHSType->isIntegerType()) {
9282 Kind = CK_IntegralToPointer; // FIXME: null?
9283 return IntToPointer;
9284 }
9285
9286 // C pointers are not compatible with ObjC object pointers,
9287 // with two exceptions:
9288 if (isa<ObjCObjectPointerType>(RHSType)) {
9289 // - conversions to void*
9290 if (LHSPointer->getPointeeType()->isVoidType()) {
9291 Kind = CK_BitCast;
9292 return Compatible;
9293 }
9294
9295 // - conversions from 'Class' to the redefinition type
9296 if (RHSType->isObjCClassType() &&
9297 Context.hasSameType(LHSType,
9299 Kind = CK_BitCast;
9300 return Compatible;
9301 }
9302
9303 Kind = CK_BitCast;
9304 return IncompatiblePointer;
9305 }
9306
9307 // U^ -> void*
9308 if (RHSType->getAs<BlockPointerType>()) {
9309 if (LHSPointer->getPointeeType()->isVoidType()) {
9310 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9311 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9312 ->getPointeeType()
9313 .getAddressSpace();
9314 Kind =
9315 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9316 return Compatible;
9317 }
9318 }
9319
9320 return Incompatible;
9321 }
9322
9323 // Conversions to block pointers.
9324 if (isa<BlockPointerType>(LHSType)) {
9325 // U^ -> T^
9326 if (RHSType->isBlockPointerType()) {
9327 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9328 ->getPointeeType()
9329 .getAddressSpace();
9330 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9331 ->getPointeeType()
9332 .getAddressSpace();
9333 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9334 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9335 }
9336
9337 // int or null -> T^
9338 if (RHSType->isIntegerType()) {
9339 Kind = CK_IntegralToPointer; // FIXME: null
9340 return IntToBlockPointer;
9341 }
9342
9343 // id -> T^
9344 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9345 Kind = CK_AnyPointerToBlockPointerCast;
9346 return Compatible;
9347 }
9348
9349 // void* -> T^
9350 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9351 if (RHSPT->getPointeeType()->isVoidType()) {
9352 Kind = CK_AnyPointerToBlockPointerCast;
9353 return Compatible;
9354 }
9355
9356 return Incompatible;
9357 }
9358
9359 // Conversions to Objective-C pointers.
9360 if (isa<ObjCObjectPointerType>(LHSType)) {
9361 // A* -> B*
9362 if (RHSType->isObjCObjectPointerType()) {
9363 Kind = CK_BitCast;
9365 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9366 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9367 result == Compatible &&
9368 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9369 result = IncompatibleObjCWeakRef;
9370 return result;
9371 }
9372
9373 // int or null -> A*
9374 if (RHSType->isIntegerType()) {
9375 Kind = CK_IntegralToPointer; // FIXME: null
9376 return IntToPointer;
9377 }
9378
9379 // In general, C pointers are not compatible with ObjC object pointers,
9380 // with two exceptions:
9381 if (isa<PointerType>(RHSType)) {
9382 Kind = CK_CPointerToObjCPointerCast;
9383
9384 // - conversions from 'void*'
9385 if (RHSType->isVoidPointerType()) {
9386 return Compatible;
9387 }
9388
9389 // - conversions to 'Class' from its redefinition type
9390 if (LHSType->isObjCClassType() &&
9391 Context.hasSameType(RHSType,
9393 return Compatible;
9394 }
9395
9396 return IncompatiblePointer;
9397 }
9398
9399 // Only under strict condition T^ is compatible with an Objective-C pointer.
9400 if (RHSType->isBlockPointerType() &&
9402 if (ConvertRHS)
9404 Kind = CK_BlockPointerToObjCPointerCast;
9405 return Compatible;
9406 }
9407
9408 return Incompatible;
9409 }
9410
9411 // Conversion to nullptr_t (C23 only)
9412 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9415 // null -> nullptr_t
9416 Kind = CK_NullToPointer;
9417 return Compatible;
9418 }
9419
9420 // Conversions from pointers that are not covered by the above.
9421 if (isa<PointerType>(RHSType)) {
9422 // T* -> _Bool
9423 if (LHSType == Context.BoolTy) {
9424 Kind = CK_PointerToBoolean;
9425 return Compatible;
9426 }
9427
9428 // T* -> int
9429 if (LHSType->isIntegerType()) {
9430 Kind = CK_PointerToIntegral;
9431 return PointerToInt;
9432 }
9433
9434 return Incompatible;
9435 }
9436
9437 // Conversions from Objective-C pointers that are not covered by the above.
9438 if (isa<ObjCObjectPointerType>(RHSType)) {
9439 // T* -> _Bool
9440 if (LHSType == Context.BoolTy) {
9441 Kind = CK_PointerToBoolean;
9442 return Compatible;
9443 }
9444
9445 // T* -> int
9446 if (LHSType->isIntegerType()) {
9447 Kind = CK_PointerToIntegral;
9448 return PointerToInt;
9449 }
9450
9451 return Incompatible;
9452 }
9453
9454 // struct A -> struct B
9455 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9456 if (Context.typesAreCompatible(LHSType, RHSType)) {
9457 Kind = CK_NoOp;
9458 return Compatible;
9459 }
9460 }
9461
9462 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9463 Kind = CK_IntToOCLSampler;
9464 return Compatible;
9465 }
9466
9467 return Incompatible;
9468}
9469
9470/// Constructs a transparent union from an expression that is
9471/// used to initialize the transparent union.
9473 ExprResult &EResult, QualType UnionType,
9474 FieldDecl *Field) {
9475 // Build an initializer list that designates the appropriate member
9476 // of the transparent union.
9477 Expr *E = EResult.get();
9479 E, SourceLocation());
9480 Initializer->setType(UnionType);
9481 Initializer->setInitializedFieldInUnion(Field);
9482
9483 // Build a compound literal constructing a value of the transparent
9484 // union type from this initializer list.
9485 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9486 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9487 VK_PRValue, Initializer, false);
9488}
9489
9492 ExprResult &RHS) {
9493 QualType RHSType = RHS.get()->getType();
9494
9495 // If the ArgType is a Union type, we want to handle a potential
9496 // transparent_union GCC extension.
9497 const RecordType *UT = ArgType->getAsUnionType();
9498 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9499 return Incompatible;
9500
9501 // The field to initialize within the transparent union.
9502 RecordDecl *UD = UT->getDecl();
9503 FieldDecl *InitField = nullptr;
9504 // It's compatible if the expression matches any of the fields.
9505 for (auto *it : UD->fields()) {
9506 if (it->getType()->isPointerType()) {
9507 // If the transparent union contains a pointer type, we allow:
9508 // 1) void pointer
9509 // 2) null pointer constant
9510 if (RHSType->isPointerType())
9511 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9512 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9513 InitField = it;
9514 break;
9515 }
9516
9519 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9520 CK_NullToPointer);
9521 InitField = it;
9522 break;
9523 }
9524 }
9525
9526 CastKind Kind;
9527 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9528 == Compatible) {
9529 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9530 InitField = it;
9531 break;
9532 }
9533 }
9534
9535 if (!InitField)
9536 return Incompatible;
9537
9538 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9539 return Compatible;
9540}
9541
9544 bool Diagnose,
9545 bool DiagnoseCFAudited,
9546 bool ConvertRHS) {
9547 // We need to be able to tell the caller whether we diagnosed a problem, if
9548 // they ask us to issue diagnostics.
9549 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9550
9551 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9552 // we can't avoid *all* modifications at the moment, so we need some somewhere
9553 // to put the updated value.
9554 ExprResult LocalRHS = CallerRHS;
9555 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9556
9557 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9558 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9559 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9560 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9561 Diag(RHS.get()->getExprLoc(),
9562 diag::warn_noderef_to_dereferenceable_pointer)
9563 << RHS.get()->getSourceRange();
9564 }
9565 }
9566 }
9567
9568 if (getLangOpts().CPlusPlus) {
9569 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9570 // C++ 5.17p3: If the left operand is not of class type, the
9571 // expression is implicitly converted (C++ 4) to the
9572 // cv-unqualified type of the left operand.
9573 QualType RHSType = RHS.get()->getType();
9574 if (Diagnose) {
9575 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9576 AA_Assigning);
9577 } else {
9580 /*SuppressUserConversions=*/false,
9581 AllowedExplicit::None,
9582 /*InOverloadResolution=*/false,
9583 /*CStyle=*/false,
9584 /*AllowObjCWritebackConversion=*/false);
9585 if (ICS.isFailure())
9586 return Incompatible;
9587 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9588 ICS, AA_Assigning);
9589 }
9590 if (RHS.isInvalid())
9591 return Incompatible;
9593 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9594 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9595 result = IncompatibleObjCWeakRef;
9596 return result;
9597 }
9598
9599 // FIXME: Currently, we fall through and treat C++ classes like C
9600 // structures.
9601 // FIXME: We also fall through for atomics; not sure what should
9602 // happen there, though.
9603 } else if (RHS.get()->getType() == Context.OverloadTy) {
9604 // As a set of extensions to C, we support overloading on functions. These
9605 // functions need to be resolved here.
9606 DeclAccessPair DAP;
9608 RHS.get(), LHSType, /*Complain=*/false, DAP))
9609 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9610 else
9611 return Incompatible;
9612 }
9613
9614 // This check seems unnatural, however it is necessary to ensure the proper
9615 // conversion of functions/arrays. If the conversion were done for all
9616 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9617 // expressions that suppress this implicit conversion (&, sizeof). This needs
9618 // to happen before we check for null pointer conversions because C does not
9619 // undergo the same implicit conversions as C++ does above (by the calls to
9620 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
9621 // lvalue to rvalue cast before checking for null pointer constraints. This
9622 // addresses code like: nullptr_t val; int *ptr; ptr = val;
9623 //
9624 // Suppress this for references: C++ 8.5.3p5.
9625 if (!LHSType->isReferenceType()) {
9626 // FIXME: We potentially allocate here even if ConvertRHS is false.
9628 if (RHS.isInvalid())
9629 return Incompatible;
9630 }
9631
9632 // The constraints are expressed in terms of the atomic, qualified, or
9633 // unqualified type of the LHS.
9634 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
9635
9636 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9637 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
9638 if ((LHSTypeAfterConversion->isPointerType() ||
9639 LHSTypeAfterConversion->isObjCObjectPointerType() ||
9640 LHSTypeAfterConversion->isBlockPointerType()) &&
9641 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
9644 if (Diagnose || ConvertRHS) {
9645 CastKind Kind;
9647 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9648 /*IgnoreBaseAccess=*/false, Diagnose);
9649 if (ConvertRHS)
9650 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9651 }
9652 return Compatible;
9653 }
9654 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
9655 // unqualified bool, and the right operand is a pointer or its type is
9656 // nullptr_t.
9657 if (getLangOpts().C23 && LHSType->isBooleanType() &&
9658 RHS.get()->getType()->isNullPtrType()) {
9659 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
9660 // only handles nullptr -> _Bool due to needing an extra conversion
9661 // step.
9662 // We model this by converting from nullptr -> void * and then let the
9663 // conversion from void * -> _Bool happen naturally.
9664 if (Diagnose || ConvertRHS) {
9665 CastKind Kind;
9668 /*IgnoreBaseAccess=*/false, Diagnose);
9669 if (ConvertRHS)
9670 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
9671 &Path);
9672 }
9673 }
9674
9675 // OpenCL queue_t type assignment.
9676 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9678 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9679 return Compatible;
9680 }
9681
9682 CastKind Kind;
9684 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9685
9686 // C99 6.5.16.1p2: The value of the right operand is converted to the
9687 // type of the assignment expression.
9688 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9689 // so that we can use references in built-in functions even in C.
9690 // The getNonReferenceType() call makes sure that the resulting expression
9691 // does not have reference type.
9692 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9694 Expr *E = RHS.get();
9695
9696 // Check for various Objective-C errors. If we are not reporting
9697 // diagnostics and just checking for errors, e.g., during overload
9698 // resolution, return Incompatible to indicate the failure.
9699 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9700 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
9702 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
9703 if (!Diagnose)
9704 return Incompatible;
9705 }
9706 if (getLangOpts().ObjC &&
9707 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9708 E->getType(), E, Diagnose) ||
9709 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9710 if (!Diagnose)
9711 return Incompatible;
9712 // Replace the expression with a corrected version and continue so we
9713 // can find further errors.
9714 RHS = E;
9715 return Compatible;
9716 }
9717
9718 if (ConvertRHS)
9719 RHS = ImpCastExprToType(E, Ty, Kind);
9720 }
9721
9722 return result;
9723}
9724
9725namespace {
9726/// The original operand to an operator, prior to the application of the usual
9727/// arithmetic conversions and converting the arguments of a builtin operator
9728/// candidate.
9729struct OriginalOperand {
9730 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9731 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9732 Op = MTE->getSubExpr();
9733 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9734 Op = BTE->getSubExpr();
9735 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9736 Orig = ICE->getSubExprAsWritten();
9737 Conversion = ICE->getConversionFunction();
9738 }
9739 }
9740
9741 QualType getType() const { return Orig->getType(); }
9742
9743 Expr *Orig;
9744 NamedDecl *Conversion;
9745};
9746}
9747
9749 ExprResult &RHS) {
9750 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9751
9752 Diag(Loc, diag::err_typecheck_invalid_operands)
9753 << OrigLHS.getType() << OrigRHS.getType()
9754 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9755
9756 // If a user-defined conversion was applied to either of the operands prior
9757 // to applying the built-in operator rules, tell the user about it.
9758 if (OrigLHS.Conversion) {
9759 Diag(OrigLHS.Conversion->getLocation(),
9760 diag::note_typecheck_invalid_operands_converted)
9761 << 0 << LHS.get()->getType();
9762 }
9763 if (OrigRHS.Conversion) {
9764 Diag(OrigRHS.Conversion->getLocation(),
9765 diag::note_typecheck_invalid_operands_converted)
9766 << 1 << RHS.get()->getType();
9767 }
9768
9769 return QualType();
9770}
9771
9773 ExprResult &RHS) {
9774 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9775 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9776
9777 bool LHSNatVec = LHSType->isVectorType();
9778 bool RHSNatVec = RHSType->isVectorType();
9779
9780 if (!(LHSNatVec && RHSNatVec)) {
9781 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9782 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9783 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9784 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9785 << Vector->getSourceRange();
9786 return QualType();
9787 }
9788
9789 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9790 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9791 << RHS.get()->getSourceRange();
9792
9793 return QualType();
9794}
9795
9796/// Try to convert a value of non-vector type to a vector type by converting
9797/// the type to the element type of the vector and then performing a splat.
9798/// If the language is OpenCL, we only use conversions that promote scalar
9799/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9800/// for float->int.
9801///
9802/// OpenCL V2.0 6.2.6.p2:
9803/// An error shall occur if any scalar operand type has greater rank
9804/// than the type of the vector element.
9805///
9806/// \param scalar - if non-null, actually perform the conversions
9807/// \return true if the operation fails (but without diagnosing the failure)
9809 QualType scalarTy,
9810 QualType vectorEltTy,
9811 QualType vectorTy,
9812 unsigned &DiagID) {
9813 // The conversion to apply to the scalar before splatting it,
9814 // if necessary.
9815 CastKind scalarCast = CK_NoOp;
9816
9817 if (vectorEltTy->isIntegralType(S.Context)) {
9818 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9819 (scalarTy->isIntegerType() &&
9820 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9821 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9822 return true;
9823 }
9824 if (!scalarTy->isIntegralType(S.Context))
9825 return true;
9826 scalarCast = CK_IntegralCast;
9827 } else if (vectorEltTy->isRealFloatingType()) {
9828 if (scalarTy->isRealFloatingType()) {
9829 if (S.getLangOpts().OpenCL &&
9830 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9831 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9832 return true;
9833 }
9834 scalarCast = CK_FloatingCast;
9835 }
9836 else if (scalarTy->isIntegralType(S.Context))
9837 scalarCast = CK_IntegralToFloating;
9838 else
9839 return true;
9840 } else {
9841 return true;
9842 }
9843
9844 // Adjust scalar if desired.
9845 if (scalar) {
9846 if (scalarCast != CK_NoOp)
9847 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9848 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9849 }
9850 return false;
9851}
9852
9853/// Convert vector E to a vector with the same number of elements but different
9854/// element type.
9855static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9856 const auto *VecTy = E->getType()->getAs<VectorType>();
9857 assert(VecTy && "Expression E must be a vector");
9858 QualType NewVecTy =
9859 VecTy->isExtVectorType()
9860 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
9861 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
9862 VecTy->getVectorKind());
9863
9864 // Look through the implicit cast. Return the subexpression if its type is
9865 // NewVecTy.
9866 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9867 if (ICE->getSubExpr()->getType() == NewVecTy)
9868 return ICE->getSubExpr();
9869
9870 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9871 return S.ImpCastExprToType(E, NewVecTy, Cast);
9872}
9873
9874/// Test if a (constant) integer Int can be casted to another integer type
9875/// IntTy without losing precision.
9877 QualType OtherIntTy) {
9878 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9879
9880 // Reject cases where the value of the Int is unknown as that would
9881 // possibly cause truncation, but accept cases where the scalar can be
9882 // demoted without loss of precision.
9883 Expr::EvalResult EVResult;
9884 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9885 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9886 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9887 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9888
9889 if (CstInt) {
9890 // If the scalar is constant and is of a higher order and has more active
9891 // bits that the vector element type, reject it.
9892 llvm::APSInt Result = EVResult.Val.getInt();
9893 unsigned NumBits = IntSigned
9894 ? (Result.isNegative() ? Result.getSignificantBits()
9895 : Result.getActiveBits())
9896 : Result.getActiveBits();
9897 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9898 return true;
9899
9900 // If the signedness of the scalar type and the vector element type
9901 // differs and the number of bits is greater than that of the vector
9902 // element reject it.
9903 return (IntSigned != OtherIntSigned &&
9904 NumBits > S.Context.getIntWidth(OtherIntTy));
9905 }
9906
9907 // Reject cases where the value of the scalar is not constant and it's
9908 // order is greater than that of the vector element type.
9909 return (Order < 0);
9910}
9911
9912/// Test if a (constant) integer Int can be casted to floating point type
9913/// FloatTy without losing precision.
9915 QualType FloatTy) {
9916 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9917
9918 // Determine if the integer constant can be expressed as a floating point
9919 // number of the appropriate type.
9920 Expr::EvalResult EVResult;
9921 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9922
9923 uint64_t Bits = 0;
9924 if (CstInt) {
9925 // Reject constants that would be truncated if they were converted to
9926 // the floating point type. Test by simple to/from conversion.
9927 // FIXME: Ideally the conversion to an APFloat and from an APFloat
9928 // could be avoided if there was a convertFromAPInt method
9929 // which could signal back if implicit truncation occurred.
9930 llvm::APSInt Result = EVResult.Val.getInt();
9931 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
9932 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
9933 llvm::APFloat::rmTowardZero);
9934 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
9936 bool Ignored = false;
9937 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
9938 &Ignored);
9939 if (Result != ConvertBack)
9940 return true;
9941 } else {
9942 // Reject types that cannot be fully encoded into the mantissa of
9943 // the float.
9944 Bits = S.Context.getTypeSize(IntTy);
9945 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
9946 S.Context.getFloatTypeSemantics(FloatTy));
9947 if (Bits > FloatPrec)
9948 return true;
9949 }
9950
9951 return false;
9952}
9953
9954/// Attempt to convert and splat Scalar into a vector whose types matches
9955/// Vector following GCC conversion rules. The rule is that implicit
9956/// conversion can occur when Scalar can be casted to match Vector's element
9957/// type without causing truncation of Scalar.
9959 ExprResult *Vector) {
9960 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
9961 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
9962 QualType VectorEltTy;
9963
9964 if (const auto *VT = VectorTy->getAs<VectorType>()) {
9965 assert(!isa<ExtVectorType>(VT) &&
9966 "ExtVectorTypes should not be handled here!");
9967 VectorEltTy = VT->getElementType();
9968 } else if (VectorTy->isSveVLSBuiltinType()) {
9969 VectorEltTy =
9970 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
9971 } else {
9972 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
9973 }
9974
9975 // Reject cases where the vector element type or the scalar element type are
9976 // not integral or floating point types.
9977 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
9978 return true;
9979
9980 // The conversion to apply to the scalar before splatting it,
9981 // if necessary.
9982 CastKind ScalarCast = CK_NoOp;
9983
9984 // Accept cases where the vector elements are integers and the scalar is
9985 // an integer.
9986 // FIXME: Notionally if the scalar was a floating point value with a precise
9987 // integral representation, we could cast it to an appropriate integer
9988 // type and then perform the rest of the checks here. GCC will perform
9989 // this conversion in some cases as determined by the input language.
9990 // We should accept it on a language independent basis.
9991 if (VectorEltTy->isIntegralType(S.Context) &&
9992 ScalarTy->isIntegralType(S.Context) &&
9993 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
9994
9995 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
9996 return true;
9997
9998 ScalarCast = CK_IntegralCast;
9999 } else if (VectorEltTy->isIntegralType(S.Context) &&
10000 ScalarTy->isRealFloatingType()) {
10001 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10002 ScalarCast = CK_FloatingToIntegral;
10003 else
10004 return true;
10005 } else if (VectorEltTy->isRealFloatingType()) {
10006 if (ScalarTy->isRealFloatingType()) {
10007
10008 // Reject cases where the scalar type is not a constant and has a higher
10009 // Order than the vector element type.
10010 llvm::APFloat Result(0.0);
10011
10012 // Determine whether this is a constant scalar. In the event that the
10013 // value is dependent (and thus cannot be evaluated by the constant
10014 // evaluator), skip the evaluation. This will then diagnose once the
10015 // expression is instantiated.
10016 bool CstScalar = Scalar->get()->isValueDependent() ||
10017 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10018 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10019 if (!CstScalar && Order < 0)
10020 return true;
10021
10022 // If the scalar cannot be safely casted to the vector element type,
10023 // reject it.
10024 if (CstScalar) {
10025 bool Truncated = false;
10026 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10027 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10028 if (Truncated)
10029 return true;
10030 }
10031
10032 ScalarCast = CK_FloatingCast;
10033 } else if (ScalarTy->isIntegralType(S.Context)) {
10034 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10035 return true;
10036
10037 ScalarCast = CK_IntegralToFloating;
10038 } else
10039 return true;
10040 } else if (ScalarTy->isEnumeralType())
10041 return true;
10042
10043 // Adjust scalar if desired.
10044 if (ScalarCast != CK_NoOp)
10045 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10046 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10047 return false;
10048}
10049
10051 SourceLocation Loc, bool IsCompAssign,
10052 bool AllowBothBool,
10053 bool AllowBoolConversions,
10054 bool AllowBoolOperation,
10055 bool ReportInvalid) {
10056 if (!IsCompAssign) {
10058 if (LHS.isInvalid())
10059 return QualType();
10060 }
10062 if (RHS.isInvalid())
10063 return QualType();
10064
10065 // For conversion purposes, we ignore any qualifiers.
10066 // For example, "const float" and "float" are equivalent.
10067 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10068 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10069
10070 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10071 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10072 assert(LHSVecType || RHSVecType);
10073
10074 // AltiVec-style "vector bool op vector bool" combinations are allowed
10075 // for some operators but not others.
10076 if (!AllowBothBool && LHSVecType &&
10077 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10078 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10079 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10080
10081 // This operation may not be performed on boolean vectors.
10082 if (!AllowBoolOperation &&
10083 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10084 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10085
10086 // If the vector types are identical, return.
10087 if (Context.hasSameType(LHSType, RHSType))
10088 return Context.getCommonSugaredType(LHSType, RHSType);
10089
10090 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10091 if (LHSVecType && RHSVecType &&
10092 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10093 if (isa<ExtVectorType>(LHSVecType)) {
10094 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10095 return LHSType;
10096 }
10097
10098 if (!IsCompAssign)
10099 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10100 return RHSType;
10101 }
10102
10103 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10104 // can be mixed, with the result being the non-bool type. The non-bool
10105 // operand must have integer element type.
10106 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10107 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10108 (Context.getTypeSize(LHSVecType->getElementType()) ==
10109 Context.getTypeSize(RHSVecType->getElementType()))) {
10110 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10111 LHSVecType->getElementType()->isIntegerType() &&
10112 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10113 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10114 return LHSType;
10115 }
10116 if (!IsCompAssign &&
10117 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10118 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10119 RHSVecType->getElementType()->isIntegerType()) {
10120 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10121 return RHSType;
10122 }
10123 }
10124
10125 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10126 // invalid since the ambiguity can affect the ABI.
10127 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10128 unsigned &SVEorRVV) {
10129 const VectorType *VecType = SecondType->getAs<VectorType>();
10130 SVEorRVV = 0;
10131 if (FirstType->isSizelessBuiltinType() && VecType) {
10134 return true;
10137 SVEorRVV = 1;
10138 return true;
10139 }
10140 }
10141
10142 return false;
10143 };
10144
10145 unsigned SVEorRVV;
10146 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10147 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10148 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10149 << SVEorRVV << LHSType << RHSType;
10150 return QualType();
10151 }
10152
10153 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10154 // invalid since the ambiguity can affect the ABI.
10155 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10156 unsigned &SVEorRVV) {
10157 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10158 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10159
10160 SVEorRVV = 0;
10161 if (FirstVecType && SecondVecType) {
10162 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10163 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10164 SecondVecType->getVectorKind() ==
10166 return true;
10167 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10168 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10169 SVEorRVV = 1;
10170 return true;
10171 }
10172 }
10173 return false;
10174 }
10175
10176 if (SecondVecType &&
10177 SecondVecType->getVectorKind() == VectorKind::Generic) {
10178 if (FirstType->isSVESizelessBuiltinType())
10179 return true;
10180 if (FirstType->isRVVSizelessBuiltinType()) {
10181 SVEorRVV = 1;
10182 return true;
10183 }
10184 }
10185
10186 return false;
10187 };
10188
10189 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10190 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10191 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10192 << SVEorRVV << LHSType << RHSType;
10193 return QualType();
10194 }
10195
10196 // If there's a vector type and a scalar, try to convert the scalar to
10197 // the vector element type and splat.
10198 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10199 if (!RHSVecType) {
10200 if (isa<ExtVectorType>(LHSVecType)) {
10201 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10202 LHSVecType->getElementType(), LHSType,
10203 DiagID))
10204 return LHSType;
10205 } else {
10206 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10207 return LHSType;
10208 }
10209 }
10210 if (!LHSVecType) {
10211 if (isa<ExtVectorType>(RHSVecType)) {
10212 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10213 LHSType, RHSVecType->getElementType(),
10214 RHSType, DiagID))
10215 return RHSType;
10216 } else {
10217 if (LHS.get()->isLValue() ||
10218 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10219 return RHSType;
10220 }
10221 }
10222
10223 // FIXME: The code below also handles conversion between vectors and
10224 // non-scalars, we should break this down into fine grained specific checks
10225 // and emit proper diagnostics.
10226 QualType VecType = LHSVecType ? LHSType : RHSType;
10227 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10228 QualType OtherType = LHSVecType ? RHSType : LHSType;
10229 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10230 if (isLaxVectorConversion(OtherType, VecType)) {
10231 if (Context.getTargetInfo().getTriple().isPPC() &&
10232 anyAltivecTypes(RHSType, LHSType) &&
10233 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10234 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10235 // If we're allowing lax vector conversions, only the total (data) size
10236 // needs to be the same. For non compound assignment, if one of the types is
10237 // scalar, the result is always the vector type.
10238 if (!IsCompAssign) {
10239 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10240 return VecType;
10241 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10242 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10243 // type. Note that this is already done by non-compound assignments in
10244 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10245 // <1 x T> -> T. The result is also a vector type.
10246 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10247 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10248 ExprResult *RHSExpr = &RHS;
10249 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10250 return VecType;
10251 }
10252 }
10253
10254 // Okay, the expression is invalid.
10255
10256 // If there's a non-vector, non-real operand, diagnose that.
10257 if ((!RHSVecType && !RHSType->isRealType()) ||
10258 (!LHSVecType && !LHSType->isRealType())) {
10259 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10260 << LHSType << RHSType
10261 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10262 return QualType();
10263 }
10264
10265 // OpenCL V1.1 6.2.6.p1:
10266 // If the operands are of more than one vector type, then an error shall
10267 // occur. Implicit conversions between vector types are not permitted, per
10268 // section 6.2.1.
10269 if (getLangOpts().OpenCL &&
10270 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10271 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10272 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10273 << RHSType;
10274 return QualType();
10275 }
10276
10277
10278 // If there is a vector type that is not a ExtVector and a scalar, we reach
10279 // this point if scalar could not be converted to the vector's element type
10280 // without truncation.
10281 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10282 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10283 QualType Scalar = LHSVecType ? RHSType : LHSType;
10284 QualType Vector = LHSVecType ? LHSType : RHSType;
10285 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10286 Diag(Loc,
10287 diag::err_typecheck_vector_not_convertable_implict_truncation)
10288 << ScalarOrVector << Scalar << Vector;
10289
10290 return QualType();
10291 }
10292
10293 // Otherwise, use the generic diagnostic.
10294 Diag(Loc, DiagID)
10295 << LHSType << RHSType
10296 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10297 return QualType();
10298}
10299
10302 bool IsCompAssign,
10303 ArithConvKind OperationKind) {
10304 if (!IsCompAssign) {
10306 if (LHS.isInvalid())
10307 return QualType();
10308 }
10310 if (RHS.isInvalid())
10311 return QualType();
10312
10313 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10314 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10315
10316 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10317 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10318
10319 unsigned DiagID = diag::err_typecheck_invalid_operands;
10320 if ((OperationKind == ACK_Arithmetic) &&
10321 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10322 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10323 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10324 << RHS.get()->getSourceRange();
10325 return QualType();
10326 }
10327
10328 if (Context.hasSameType(LHSType, RHSType))
10329 return LHSType;
10330
10331 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10332 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10333 return LHSType;
10334 }
10335 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10336 if (LHS.get()->isLValue() ||
10337 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10338 return RHSType;
10339 }
10340
10341 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10342 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10343 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10344 << LHSType << RHSType << LHS.get()->getSourceRange()
10345 << RHS.get()->getSourceRange();
10346 return QualType();
10347 }
10348
10349 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10350 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10351 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10352 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10353 << LHSType << RHSType << LHS.get()->getSourceRange()
10354 << RHS.get()->getSourceRange();
10355 return QualType();
10356 }
10357
10358 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10359 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10360 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10361 bool ScalarOrVector =
10362 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10363
10364 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10365 << ScalarOrVector << Scalar << Vector;
10366
10367 return QualType();
10368 }
10369
10370 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10371 << RHS.get()->getSourceRange();
10372 return QualType();
10373}
10374
10375// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10376// expression. These are mainly cases where the null pointer is used as an
10377// integer instead of a pointer.
10379 SourceLocation Loc, bool IsCompare) {
10380 // The canonical way to check for a GNU null is with isNullPointerConstant,
10381 // but we use a bit of a hack here for speed; this is a relatively
10382 // hot path, and isNullPointerConstant is slow.
10383 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10384 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10385
10386 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10387
10388 // Avoid analyzing cases where the result will either be invalid (and
10389 // diagnosed as such) or entirely valid and not something to warn about.
10390 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10391 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10392 return;
10393
10394 // Comparison operations would not make sense with a null pointer no matter
10395 // what the other expression is.
10396 if (!IsCompare) {
10397 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10398 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10399 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10400 return;
10401 }
10402
10403 // The rest of the operations only make sense with a null pointer
10404 // if the other expression is a pointer.
10405 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10406 NonNullType->canDecayToPointerType())
10407 return;
10408
10409 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10410 << LHSNull /* LHS is NULL */ << NonNullType
10411 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10412}
10413
10416 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10417 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10418 if (!LUE || !RUE)
10419 return;
10420 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10421 RUE->getKind() != UETT_SizeOf)
10422 return;
10423
10424 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10425 QualType LHSTy = LHSArg->getType();
10426 QualType RHSTy;
10427
10428 if (RUE->isArgumentType())
10429 RHSTy = RUE->getArgumentType().getNonReferenceType();
10430 else
10431 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10432
10433 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10434 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10435 return;
10436
10437 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10438 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10439 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10440 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10441 << LHSArgDecl;
10442 }
10443 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10444 QualType ArrayElemTy = ArrayTy->getElementType();
10445 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10446 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10447 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10448 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10449 return;
10450 S.Diag(Loc, diag::warn_division_sizeof_array)
10451 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10452 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10453 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10454 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10455 << LHSArgDecl;
10456 }
10457
10458 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10459 }
10460}
10461
10463 ExprResult &RHS,
10464 SourceLocation Loc, bool IsDiv) {
10465 // Check for division/remainder by zero.
10466 Expr::EvalResult RHSValue;
10467 if (!RHS.get()->isValueDependent() &&
10468 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10469 RHSValue.Val.getInt() == 0)
10470 S.DiagRuntimeBehavior(Loc, RHS.get(),
10471 S.PDiag(diag::warn_remainder_division_by_zero)
10472 << IsDiv << RHS.get()->getSourceRange());
10473}
10474
10477 bool IsCompAssign, bool IsDiv) {
10478 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10479
10480 QualType LHSTy = LHS.get()->getType();
10481 QualType RHSTy = RHS.get()->getType();
10482 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10483 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10484 /*AllowBothBool*/ getLangOpts().AltiVec,
10485 /*AllowBoolConversions*/ false,
10486 /*AllowBooleanOperation*/ false,
10487 /*ReportInvalid*/ true);
10488 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10489 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10491 if (!IsDiv &&
10492 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10493 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10494 // For division, only matrix-by-scalar is supported. Other combinations with
10495 // matrix types are invalid.
10496 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10497 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10498
10500 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10501 if (LHS.isInvalid() || RHS.isInvalid())
10502 return QualType();
10503
10504
10505 if (compType.isNull() || !compType->isArithmeticType())
10506 return InvalidOperands(Loc, LHS, RHS);
10507 if (IsDiv) {
10508 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10509 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10510 }
10511 return compType;
10512}
10513
10515 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10516 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10517
10518 if (LHS.get()->getType()->isVectorType() ||
10519 RHS.get()->getType()->isVectorType()) {
10520 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10522 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10523 /*AllowBothBool*/ getLangOpts().AltiVec,
10524 /*AllowBoolConversions*/ false,
10525 /*AllowBooleanOperation*/ false,
10526 /*ReportInvalid*/ true);
10527 return InvalidOperands(Loc, LHS, RHS);
10528 }
10529
10530 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10531 RHS.get()->getType()->isSveVLSBuiltinType()) {
10532 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10534 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10536
10537 return InvalidOperands(Loc, LHS, RHS);
10538 }
10539
10541 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10542 if (LHS.isInvalid() || RHS.isInvalid())
10543 return QualType();
10544
10545 if (compType.isNull() || !compType->isIntegerType())
10546 return InvalidOperands(Loc, LHS, RHS);
10547 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10548 return compType;
10549}
10550
10551/// Diagnose invalid arithmetic on two void pointers.
10553 Expr *LHSExpr, Expr *RHSExpr) {
10554 S.Diag(Loc, S.getLangOpts().CPlusPlus
10555 ? diag::err_typecheck_pointer_arith_void_type
10556 : diag::ext_gnu_void_ptr)
10557 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10558 << RHSExpr->getSourceRange();
10559}
10560
10561/// Diagnose invalid arithmetic on a void pointer.
10563 Expr *Pointer) {
10564 S.Diag(Loc, S.getLangOpts().CPlusPlus
10565 ? diag::err_typecheck_pointer_arith_void_type
10566 : diag::ext_gnu_void_ptr)
10567 << 0 /* one pointer */ << Pointer->getSourceRange();
10568}
10569
10570/// Diagnose invalid arithmetic on a null pointer.
10571///
10572/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10573/// idiom, which we recognize as a GNU extension.
10574///
10576 Expr *Pointer, bool IsGNUIdiom) {
10577 if (IsGNUIdiom)
10578 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10579 << Pointer->getSourceRange();
10580 else
10581 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10582 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10583}
10584
10585/// Diagnose invalid subraction on a null pointer.
10586///
10588 Expr *Pointer, bool BothNull) {
10589 // Null - null is valid in C++ [expr.add]p7
10590 if (BothNull && S.getLangOpts().CPlusPlus)
10591 return;
10592
10593 // Is this s a macro from a system header?
10595 return;
10596
10598 S.PDiag(diag::warn_pointer_sub_null_ptr)
10599 << S.getLangOpts().CPlusPlus
10600 << Pointer->getSourceRange());
10601}
10602
10603/// Diagnose invalid arithmetic on two function pointers.
10605 Expr *LHS, Expr *RHS) {
10606 assert(LHS->getType()->isAnyPointerType());
10607 assert(RHS->getType()->isAnyPointerType());
10608 S.Diag(Loc, S.getLangOpts().CPlusPlus
10609 ? diag::err_typecheck_pointer_arith_function_type
10610 : diag::ext_gnu_ptr_func_arith)
10611 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10612 // We only show the second type if it differs from the first.
10614 RHS->getType())
10615 << RHS->getType()->getPointeeType()
10616 << LHS->getSourceRange() << RHS->getSourceRange();
10617}
10618
10619/// Diagnose invalid arithmetic on a function pointer.
10621 Expr *Pointer) {
10622 assert(Pointer->getType()->isAnyPointerType());
10623 S.Diag(Loc, S.getLangOpts().CPlusPlus
10624 ? diag::err_typecheck_pointer_arith_function_type
10625 : diag::ext_gnu_ptr_func_arith)
10626 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10627 << 0 /* one pointer, so only one type */
10628 << Pointer->getSourceRange();
10629}
10630
10631/// Emit error if Operand is incomplete pointer type
10632///
10633/// \returns True if pointer has incomplete type
10635 Expr *Operand) {
10636 QualType ResType = Operand->getType();
10637 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10638 ResType = ResAtomicType->getValueType();
10639
10640 assert(ResType->isAnyPointerType());
10641 QualType PointeeTy = ResType->getPointeeType();
10642 return S.RequireCompleteSizedType(
10643 Loc, PointeeTy,
10644 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10645 Operand->getSourceRange());
10646}
10647
10648/// Check the validity of an arithmetic pointer operand.
10649///
10650/// If the operand has pointer type, this code will check for pointer types
10651/// which are invalid in arithmetic operations. These will be diagnosed
10652/// appropriately, including whether or not the use is supported as an
10653/// extension.
10654///
10655/// \returns True when the operand is valid to use (even if as an extension).
10657 Expr *Operand) {
10658 QualType ResType = Operand->getType();
10659 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10660 ResType = ResAtomicType->getValueType();
10661
10662 if (!ResType->isAnyPointerType()) return true;
10663
10664 QualType PointeeTy = ResType->getPointeeType();
10665 if (PointeeTy->isVoidType()) {
10667 return !S.getLangOpts().CPlusPlus;
10668 }
10669 if (PointeeTy->isFunctionType()) {
10671 return !S.getLangOpts().CPlusPlus;
10672 }
10673
10674 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10675
10676 return true;
10677}
10678
10679/// Check the validity of a binary arithmetic operation w.r.t. pointer
10680/// operands.
10681///
10682/// This routine will diagnose any invalid arithmetic on pointer operands much
10683/// like \see checkArithmeticOpPointerOperand. However, it has special logic
10684/// for emitting a single diagnostic even for operations where both LHS and RHS
10685/// are (potentially problematic) pointers.
10686///
10687/// \returns True when the operand is valid to use (even if as an extension).
10689 Expr *LHSExpr, Expr *RHSExpr) {
10690 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10691 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10692 if (!isLHSPointer && !isRHSPointer) return true;
10693
10694 QualType LHSPointeeTy, RHSPointeeTy;
10695 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10696 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10697
10698 // if both are pointers check if operation is valid wrt address spaces
10699 if (isLHSPointer && isRHSPointer) {
10700 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
10701 S.Diag(Loc,
10702 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10703 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10704 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10705 return false;
10706 }
10707 }
10708
10709 // Check for arithmetic on pointers to incomplete types.
10710 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10711 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10712 if (isLHSVoidPtr || isRHSVoidPtr) {
10713 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10714 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10715 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10716
10717 return !S.getLangOpts().CPlusPlus;
10718 }
10719
10720 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10721 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10722 if (isLHSFuncPtr || isRHSFuncPtr) {
10723 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10724 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10725 RHSExpr);
10726 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10727
10728 return !S.getLangOpts().CPlusPlus;
10729 }
10730
10731 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10732 return false;
10733 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10734 return false;
10735
10736 return true;
10737}
10738
10739/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10740/// literal.
10742 Expr *LHSExpr, Expr *RHSExpr) {
10743 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10744 Expr* IndexExpr = RHSExpr;
10745 if (!StrExpr) {
10746 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10747 IndexExpr = LHSExpr;
10748 }
10749
10750 bool IsStringPlusInt = StrExpr &&
10752 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10753 return;
10754
10755 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10756 Self.Diag(OpLoc, diag::warn_string_plus_int)
10757 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10758
10759 // Only print a fixit for "str" + int, not for int + "str".
10760 if (IndexExpr == RHSExpr) {
10761 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10762 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10763 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10765 << FixItHint::CreateInsertion(EndLoc, "]");
10766 } else
10767 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10768}
10769
10770/// Emit a warning when adding a char literal to a string.
10772 Expr *LHSExpr, Expr *RHSExpr) {
10773 const Expr *StringRefExpr = LHSExpr;
10774 const CharacterLiteral *CharExpr =
10775 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10776
10777 if (!CharExpr) {
10778 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10779 StringRefExpr = RHSExpr;
10780 }
10781
10782 if (!CharExpr || !StringRefExpr)
10783 return;
10784
10785 const QualType StringType = StringRefExpr->getType();
10786
10787 // Return if not a PointerType.
10788 if (!StringType->isAnyPointerType())
10789 return;
10790
10791 // Return if not a CharacterType.
10792 if (!StringType->getPointeeType()->isAnyCharacterType())
10793 return;
10794
10795 ASTContext &Ctx = Self.getASTContext();
10796 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10797
10798 const QualType CharType = CharExpr->getType();
10799 if (!CharType->isAnyCharacterType() &&
10800 CharType->isIntegerType() &&
10801 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10802 Self.Diag(OpLoc, diag::warn_string_plus_char)
10803 << DiagRange << Ctx.CharTy;
10804 } else {
10805 Self.Diag(OpLoc, diag::warn_string_plus_char)
10806 << DiagRange << CharExpr->getType();
10807 }
10808
10809 // Only print a fixit for str + char, not for char + str.
10810 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10811 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10812 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10813 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10815 << FixItHint::CreateInsertion(EndLoc, "]");
10816 } else {
10817 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10818 }
10819}
10820
10821/// Emit error when two pointers are incompatible.
10823 Expr *LHSExpr, Expr *RHSExpr) {
10824 assert(LHSExpr->getType()->isAnyPointerType());
10825 assert(RHSExpr->getType()->isAnyPointerType());
10826 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10827 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10828 << RHSExpr->getSourceRange();
10829}
10830
10831// C99 6.5.6
10834 QualType* CompLHSTy) {
10835 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10836
10837 if (LHS.get()->getType()->isVectorType() ||
10838 RHS.get()->getType()->isVectorType()) {
10839 QualType compType =
10840 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
10841 /*AllowBothBool*/ getLangOpts().AltiVec,
10842 /*AllowBoolConversions*/ getLangOpts().ZVector,
10843 /*AllowBooleanOperation*/ false,
10844 /*ReportInvalid*/ true);
10845 if (CompLHSTy) *CompLHSTy = compType;
10846 return compType;
10847 }
10848
10849 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10850 RHS.get()->getType()->isSveVLSBuiltinType()) {
10851 QualType compType =
10852 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
10853 if (CompLHSTy)
10854 *CompLHSTy = compType;
10855 return compType;
10856 }
10857
10858 if (LHS.get()->getType()->isConstantMatrixType() ||
10859 RHS.get()->getType()->isConstantMatrixType()) {
10860 QualType compType =
10861 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10862 if (CompLHSTy)
10863 *CompLHSTy = compType;
10864 return compType;
10865 }
10866
10868 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10869 if (LHS.isInvalid() || RHS.isInvalid())
10870 return QualType();
10871
10872 // Diagnose "string literal" '+' int and string '+' "char literal".
10873 if (Opc == BO_Add) {
10874 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10875 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10876 }
10877
10878 // handle the common case first (both operands are arithmetic).
10879 if (!compType.isNull() && compType->isArithmeticType()) {
10880 if (CompLHSTy) *CompLHSTy = compType;
10881 return compType;
10882 }
10883
10884 // Type-checking. Ultimately the pointer's going to be in PExp;
10885 // note that we bias towards the LHS being the pointer.
10886 Expr *PExp = LHS.get(), *IExp = RHS.get();
10887
10888 bool isObjCPointer;
10889 if (PExp->getType()->isPointerType()) {
10890 isObjCPointer = false;
10891 } else if (PExp->getType()->isObjCObjectPointerType()) {
10892 isObjCPointer = true;
10893 } else {
10894 std::swap(PExp, IExp);
10895 if (PExp->getType()->isPointerType()) {
10896 isObjCPointer = false;
10897 } else if (PExp->getType()->isObjCObjectPointerType()) {
10898 isObjCPointer = true;
10899 } else {
10900 return InvalidOperands(Loc, LHS, RHS);
10901 }
10902 }
10903 assert(PExp->getType()->isAnyPointerType());
10904
10905 if (!IExp->getType()->isIntegerType())
10906 return InvalidOperands(Loc, LHS, RHS);
10907
10908 // Adding to a null pointer results in undefined behavior.
10911 // In C++ adding zero to a null pointer is defined.
10912 Expr::EvalResult KnownVal;
10913 if (!getLangOpts().CPlusPlus ||
10914 (!IExp->isValueDependent() &&
10915 (!IExp->EvaluateAsInt(KnownVal, Context) ||
10916 KnownVal.Val.getInt() != 0))) {
10917 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
10919 Context, BO_Add, PExp, IExp);
10920 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
10921 }
10922 }
10923
10924 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
10925 return QualType();
10926
10927 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
10928 return QualType();
10929
10930 // Arithmetic on label addresses is normally allowed, except when we add
10931 // a ptrauth signature to the addresses.
10932 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
10933 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
10934 << /*addition*/ 1;
10935 return QualType();
10936 }
10937
10938 // Check array bounds for pointer arithemtic
10939 CheckArrayAccess(PExp, IExp);
10940
10941 if (CompLHSTy) {
10943 if (LHSTy.isNull()) {
10944 LHSTy = LHS.get()->getType();
10946 LHSTy = Context.getPromotedIntegerType(LHSTy);
10947 }
10948 *CompLHSTy = LHSTy;
10949 }
10950
10951 return PExp->getType();
10952}
10953
10954// C99 6.5.6
10957 QualType* CompLHSTy) {
10958 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10959
10960 if (LHS.get()->getType()->isVectorType() ||
10961 RHS.get()->getType()->isVectorType()) {
10962 QualType compType =
10963 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
10964 /*AllowBothBool*/ getLangOpts().AltiVec,
10965 /*AllowBoolConversions*/ getLangOpts().ZVector,
10966 /*AllowBooleanOperation*/ false,
10967 /*ReportInvalid*/ true);
10968 if (CompLHSTy) *CompLHSTy = compType;
10969 return compType;
10970 }
10971
10972 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10973 RHS.get()->getType()->isSveVLSBuiltinType()) {
10974 QualType compType =
10975 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
10976 if (CompLHSTy)
10977 *CompLHSTy = compType;
10978 return compType;
10979 }
10980
10981 if (LHS.get()->getType()->isConstantMatrixType() ||
10982 RHS.get()->getType()->isConstantMatrixType()) {
10983 QualType compType =
10984 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10985 if (CompLHSTy)
10986 *CompLHSTy = compType;
10987 return compType;
10988 }
10989
10991 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10992 if (LHS.isInvalid() || RHS.isInvalid())
10993 return QualType();
10994
10995 // Enforce type constraints: C99 6.5.6p3.
10996
10997 // Handle the common case first (both operands are arithmetic).
10998 if (!compType.isNull() && compType->isArithmeticType()) {
10999 if (CompLHSTy) *CompLHSTy = compType;
11000 return compType;
11001 }
11002
11003 // Either ptr - int or ptr - ptr.
11004 if (LHS.get()->getType()->isAnyPointerType()) {
11005 QualType lpointee = LHS.get()->getType()->getPointeeType();
11006
11007 // Diagnose bad cases where we step over interface counts.
11008 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11009 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11010 return QualType();
11011
11012 // Arithmetic on label addresses is normally allowed, except when we add
11013 // a ptrauth signature to the addresses.
11014 if (isa<AddrLabelExpr>(LHS.get()) &&
11015 getLangOpts().PointerAuthIndirectGotos) {
11016 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11017 << /*subtraction*/ 0;
11018 return QualType();
11019 }
11020
11021 // The result type of a pointer-int computation is the pointer type.
11022 if (RHS.get()->getType()->isIntegerType()) {
11023 // Subtracting from a null pointer should produce a warning.
11024 // The last argument to the diagnose call says this doesn't match the
11025 // GNU int-to-pointer idiom.
11028 // In C++ adding zero to a null pointer is defined.
11029 Expr::EvalResult KnownVal;
11030 if (!getLangOpts().CPlusPlus ||
11031 (!RHS.get()->isValueDependent() &&
11032 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11033 KnownVal.Val.getInt() != 0))) {
11034 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11035 }
11036 }
11037
11038 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11039 return QualType();
11040
11041 // Check array bounds for pointer arithemtic
11042 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11043 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11044
11045 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11046 return LHS.get()->getType();
11047 }
11048
11049 // Handle pointer-pointer subtractions.
11050 if (const PointerType *RHSPTy
11051 = RHS.get()->getType()->getAs<PointerType>()) {
11052 QualType rpointee = RHSPTy->getPointeeType();
11053
11054 if (getLangOpts().CPlusPlus) {
11055 // Pointee types must be the same: C++ [expr.add]
11056 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11057 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11058 }
11059 } else {
11060 // Pointee types must be compatible C99 6.5.6p3
11064 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11065 return QualType();
11066 }
11067 }
11068
11070 LHS.get(), RHS.get()))
11071 return QualType();
11072
11073 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11075 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11077
11078 // Subtracting nullptr or from nullptr is suspect
11079 if (LHSIsNullPtr)
11080 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11081 if (RHSIsNullPtr)
11082 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11083
11084 // The pointee type may have zero size. As an extension, a structure or
11085 // union may have zero size or an array may have zero length. In this
11086 // case subtraction does not make sense.
11087 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11088 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11089 if (ElementSize.isZero()) {
11090 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11091 << rpointee.getUnqualifiedType()
11092 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11093 }
11094 }
11095
11096 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11097 return Context.getPointerDiffType();
11098 }
11099 }
11100
11101 return InvalidOperands(Loc, LHS, RHS);
11102}
11103
11105 if (const EnumType *ET = T->getAs<EnumType>())
11106 return ET->getDecl()->isScoped();
11107 return false;
11108}
11109
11112 QualType LHSType) {
11113 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11114 // so skip remaining warnings as we don't want to modify values within Sema.
11115 if (S.getLangOpts().OpenCL)
11116 return;
11117
11118 // Check right/shifter operand
11119 Expr::EvalResult RHSResult;
11120 if (RHS.get()->isValueDependent() ||
11121 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11122 return;
11123 llvm::APSInt Right = RHSResult.Val.getInt();
11124
11125 if (Right.isNegative()) {
11126 S.DiagRuntimeBehavior(Loc, RHS.get(),
11127 S.PDiag(diag::warn_shift_negative)
11128 << RHS.get()->getSourceRange());
11129 return;
11130 }
11131
11132 QualType LHSExprType = LHS.get()->getType();
11133 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11134 if (LHSExprType->isBitIntType())
11135 LeftSize = S.Context.getIntWidth(LHSExprType);
11136 else if (LHSExprType->isFixedPointType()) {
11137 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11138 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11139 }
11140 if (Right.uge(LeftSize)) {
11141 S.DiagRuntimeBehavior(Loc, RHS.get(),
11142 S.PDiag(diag::warn_shift_gt_typewidth)
11143 << RHS.get()->getSourceRange());
11144 return;
11145 }
11146
11147 // FIXME: We probably need to handle fixed point types specially here.
11148 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11149 return;
11150
11151 // When left shifting an ICE which is signed, we can check for overflow which
11152 // according to C++ standards prior to C++2a has undefined behavior
11153 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11154 // more than the maximum value representable in the result type, so never
11155 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11156 // expression is still probably a bug.)
11157 Expr::EvalResult LHSResult;
11158 if (LHS.get()->isValueDependent() ||
11160 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11161 return;
11162 llvm::APSInt Left = LHSResult.Val.getInt();
11163
11164 // Don't warn if signed overflow is defined, then all the rest of the
11165 // diagnostics will not be triggered because the behavior is defined.
11166 // Also don't warn in C++20 mode (and newer), as signed left shifts
11167 // always wrap and never overflow.
11168 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11169 return;
11170
11171 // If LHS does not have a non-negative value then, the
11172 // behavior is undefined before C++2a. Warn about it.
11173 if (Left.isNegative()) {
11174 S.DiagRuntimeBehavior(Loc, LHS.get(),
11175 S.PDiag(diag::warn_shift_lhs_negative)
11176 << LHS.get()->getSourceRange());
11177 return;
11178 }
11179
11180 llvm::APInt ResultBits =
11181 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11182 if (ResultBits.ule(LeftSize))
11183 return;
11184 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11185 Result = Result.shl(Right);
11186
11187 // Print the bit representation of the signed integer as an unsigned
11188 // hexadecimal number.
11189 SmallString<40> HexResult;
11190 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11191
11192 // If we are only missing a sign bit, this is less likely to result in actual
11193 // bugs -- if the result is cast back to an unsigned type, it will have the
11194 // expected value. Thus we place this behind a different warning that can be
11195 // turned off separately if needed.
11196 if (ResultBits - 1 == LeftSize) {
11197 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11198 << HexResult << LHSType
11199 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11200 return;
11201 }
11202
11203 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11204 << HexResult.str() << Result.getSignificantBits() << LHSType
11205 << Left.getBitWidth() << LHS.get()->getSourceRange()
11206 << RHS.get()->getSourceRange();
11207}
11208
11209/// Return the resulting type when a vector is shifted
11210/// by a scalar or vector shift amount.
11212 SourceLocation Loc, bool IsCompAssign) {
11213 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11214 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11215 !LHS.get()->getType()->isVectorType()) {
11216 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11217 << RHS.get()->getType() << LHS.get()->getType()
11218 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11219 return QualType();
11220 }
11221
11222 if (!IsCompAssign) {
11223 LHS = S.UsualUnaryConversions(LHS.get());
11224 if (LHS.isInvalid()) return QualType();
11225 }
11226
11227 RHS = S.UsualUnaryConversions(RHS.get());
11228 if (RHS.isInvalid()) return QualType();
11229
11230 QualType LHSType = LHS.get()->getType();
11231 // Note that LHS might be a scalar because the routine calls not only in
11232 // OpenCL case.
11233 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11234 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11235
11236 // Note that RHS might not be a vector.
11237 QualType RHSType = RHS.get()->getType();
11238 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11239 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11240
11241 // Do not allow shifts for boolean vectors.
11242 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11243 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11244 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11245 << LHS.get()->getType() << RHS.get()->getType()
11246 << LHS.get()->getSourceRange();
11247 return QualType();
11248 }
11249
11250 // The operands need to be integers.
11251 if (!LHSEleType->isIntegerType()) {
11252 S.Diag(Loc, diag::err_typecheck_expect_int)
11253 << LHS.get()->getType() << LHS.get()->getSourceRange();
11254 return QualType();
11255 }
11256
11257 if (!RHSEleType->isIntegerType()) {
11258 S.Diag(Loc, diag::err_typecheck_expect_int)
11259 << RHS.get()->getType() << RHS.get()->getSourceRange();
11260 return QualType();
11261 }
11262
11263 if (!LHSVecTy) {
11264 assert(RHSVecTy);
11265 if (IsCompAssign)
11266 return RHSType;
11267 if (LHSEleType != RHSEleType) {
11268 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11269 LHSEleType = RHSEleType;
11270 }
11271 QualType VecTy =
11272 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11273 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11274 LHSType = VecTy;
11275 } else if (RHSVecTy) {
11276 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11277 // are applied component-wise. So if RHS is a vector, then ensure
11278 // that the number of elements is the same as LHS...
11279 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11280 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11281 << LHS.get()->getType() << RHS.get()->getType()
11282 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11283 return QualType();
11284 }
11285 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11286 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11287 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11288 if (LHSBT != RHSBT &&
11289 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11290 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11291 << LHS.get()->getType() << RHS.get()->getType()
11292 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11293 }
11294 }
11295 } else {
11296 // ...else expand RHS to match the number of elements in LHS.
11297 QualType VecTy =
11298 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11299 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11300 }
11301
11302 return LHSType;
11303}
11304
11307 bool IsCompAssign) {
11308 if (!IsCompAssign) {
11309 LHS = S.UsualUnaryConversions(LHS.get());
11310 if (LHS.isInvalid())
11311 return QualType();
11312 }
11313
11314 RHS = S.UsualUnaryConversions(RHS.get());
11315 if (RHS.isInvalid())
11316 return QualType();
11317
11318 QualType LHSType = LHS.get()->getType();
11319 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11320 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11321 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11322 : LHSType;
11323
11324 // Note that RHS might not be a vector
11325 QualType RHSType = RHS.get()->getType();
11326 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11327 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11328 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11329 : RHSType;
11330
11331 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11332 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11333 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11334 << LHSType << RHSType << LHS.get()->getSourceRange();
11335 return QualType();
11336 }
11337
11338 if (!LHSEleType->isIntegerType()) {
11339 S.Diag(Loc, diag::err_typecheck_expect_int)
11340 << LHS.get()->getType() << LHS.get()->getSourceRange();
11341 return QualType();
11342 }
11343
11344 if (!RHSEleType->isIntegerType()) {
11345 S.Diag(Loc, diag::err_typecheck_expect_int)
11346 << RHS.get()->getType() << RHS.get()->getSourceRange();
11347 return QualType();
11348 }
11349
11350 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11351 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11352 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11353 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11354 << LHSType << RHSType << LHS.get()->getSourceRange()
11355 << RHS.get()->getSourceRange();
11356 return QualType();
11357 }
11358
11359 if (!LHSType->isSveVLSBuiltinType()) {
11360 assert(RHSType->isSveVLSBuiltinType());
11361 if (IsCompAssign)
11362 return RHSType;
11363 if (LHSEleType != RHSEleType) {
11364 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11365 LHSEleType = RHSEleType;
11366 }
11367 const llvm::ElementCount VecSize =
11368 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11369 QualType VecTy =
11370 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11371 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11372 LHSType = VecTy;
11373 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11374 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11375 S.Context.getTypeSize(LHSBuiltinTy)) {
11376 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11377 << LHSType << RHSType << LHS.get()->getSourceRange()
11378 << RHS.get()->getSourceRange();
11379 return QualType();
11380 }
11381 } else {
11382 const llvm::ElementCount VecSize =
11383 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11384 if (LHSEleType != RHSEleType) {
11385 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11386 RHSEleType = LHSEleType;
11387 }
11388 QualType VecTy =
11389 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11390 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11391 }
11392
11393 return LHSType;
11394}
11395
11396// C99 6.5.7
11399 bool IsCompAssign) {
11400 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11401
11402 // Vector shifts promote their scalar inputs to vector type.
11403 if (LHS.get()->getType()->isVectorType() ||
11404 RHS.get()->getType()->isVectorType()) {
11405 if (LangOpts.ZVector) {
11406 // The shift operators for the z vector extensions work basically
11407 // like general shifts, except that neither the LHS nor the RHS is
11408 // allowed to be a "vector bool".
11409 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11410 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11411 return InvalidOperands(Loc, LHS, RHS);
11412 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11413 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11414 return InvalidOperands(Loc, LHS, RHS);
11415 }
11416 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11417 }
11418
11419 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11420 RHS.get()->getType()->isSveVLSBuiltinType())
11421 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11422
11423 // Shifts don't perform usual arithmetic conversions, they just do integer
11424 // promotions on each operand. C99 6.5.7p3
11425
11426 // For the LHS, do usual unary conversions, but then reset them away
11427 // if this is a compound assignment.
11428 ExprResult OldLHS = LHS;
11429 LHS = UsualUnaryConversions(LHS.get());
11430 if (LHS.isInvalid())
11431 return QualType();
11432 QualType LHSType = LHS.get()->getType();
11433 if (IsCompAssign) LHS = OldLHS;
11434
11435 // The RHS is simpler.
11436 RHS = UsualUnaryConversions(RHS.get());
11437 if (RHS.isInvalid())
11438 return QualType();
11439 QualType RHSType = RHS.get()->getType();
11440
11441 // C99 6.5.7p2: Each of the operands shall have integer type.
11442 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11443 if ((!LHSType->isFixedPointOrIntegerType() &&
11444 !LHSType->hasIntegerRepresentation()) ||
11445 !RHSType->hasIntegerRepresentation())
11446 return InvalidOperands(Loc, LHS, RHS);
11447
11448 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11449 // hasIntegerRepresentation() above instead of this.
11450 if (isScopedEnumerationType(LHSType) ||
11451 isScopedEnumerationType(RHSType)) {
11452 return InvalidOperands(Loc, LHS, RHS);
11453 }
11454 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11455
11456 // "The type of the result is that of the promoted left operand."
11457 return LHSType;
11458}
11459
11460/// Diagnose bad pointer comparisons.
11462 ExprResult &LHS, ExprResult &RHS,
11463 bool IsError) {
11464 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11465 : diag::ext_typecheck_comparison_of_distinct_pointers)
11466 << LHS.get()->getType() << RHS.get()->getType()
11467 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11468}
11469
11470/// Returns false if the pointers are converted to a composite type,
11471/// true otherwise.
11473 ExprResult &LHS, ExprResult &RHS) {
11474 // C++ [expr.rel]p2:
11475 // [...] Pointer conversions (4.10) and qualification
11476 // conversions (4.4) are performed on pointer operands (or on
11477 // a pointer operand and a null pointer constant) to bring
11478 // them to their composite pointer type. [...]
11479 //
11480 // C++ [expr.eq]p1 uses the same notion for (in)equality
11481 // comparisons of pointers.
11482
11483 QualType LHSType = LHS.get()->getType();
11484 QualType RHSType = RHS.get()->getType();
11485 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11486 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11487
11488 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11489 if (T.isNull()) {
11490 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11491 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11492 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11493 else
11494 S.InvalidOperands(Loc, LHS, RHS);
11495 return true;
11496 }
11497
11498 return false;
11499}
11500
11502 ExprResult &LHS,
11503 ExprResult &RHS,
11504 bool IsError) {
11505 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11506 : diag::ext_typecheck_comparison_of_fptr_to_void)
11507 << LHS.get()->getType() << RHS.get()->getType()
11508 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11509}
11510
11512 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11513 case Stmt::ObjCArrayLiteralClass:
11514 case Stmt::ObjCDictionaryLiteralClass:
11515 case Stmt::ObjCStringLiteralClass:
11516 case Stmt::ObjCBoxedExprClass:
11517 return true;
11518 default:
11519 // Note that ObjCBoolLiteral is NOT an object literal!
11520 return false;
11521 }
11522}
11523
11524static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11527
11528 // If this is not actually an Objective-C object, bail out.
11529 if (!Type)
11530 return false;
11531
11532 // Get the LHS object's interface type.
11533 QualType InterfaceType = Type->getPointeeType();
11534
11535 // If the RHS isn't an Objective-C object, bail out.
11536 if (!RHS->getType()->isObjCObjectPointerType())
11537 return false;
11538
11539 // Try to find the -isEqual: method.
11540 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
11541 ObjCMethodDecl *Method =
11542 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
11543 /*IsInstance=*/true);
11544 if (!Method) {
11545 if (Type->isObjCIdType()) {
11546 // For 'id', just check the global pool.
11547 Method =
11549 /*receiverId=*/true);
11550 } else {
11551 // Check protocols.
11552 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
11553 /*IsInstance=*/true);
11554 }
11555 }
11556
11557 if (!Method)
11558 return false;
11559
11560 QualType T = Method->parameters()[0]->getType();
11561 if (!T->isObjCObjectPointerType())
11562 return false;
11563
11564 QualType R = Method->getReturnType();
11565 if (!R->isScalarType())
11566 return false;
11567
11568 return true;
11569}
11570
11572 ExprResult &LHS, ExprResult &RHS,
11574 Expr *Literal;
11575 Expr *Other;
11576 if (isObjCObjectLiteral(LHS)) {
11577 Literal = LHS.get();
11578 Other = RHS.get();
11579 } else {
11580 Literal = RHS.get();
11581 Other = LHS.get();
11582 }
11583
11584 // Don't warn on comparisons against nil.
11585 Other = Other->IgnoreParenCasts();
11586 if (Other->isNullPointerConstant(S.getASTContext(),
11588 return;
11589
11590 // This should be kept in sync with warn_objc_literal_comparison.
11591 // LK_String should always be after the other literals, since it has its own
11592 // warning flag.
11593 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
11594 assert(LiteralKind != SemaObjC::LK_Block);
11595 if (LiteralKind == SemaObjC::LK_None) {
11596 llvm_unreachable("Unknown Objective-C object literal kind");
11597 }
11598
11599 if (LiteralKind == SemaObjC::LK_String)
11600 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11601 << Literal->getSourceRange();
11602 else
11603 S.Diag(Loc, diag::warn_objc_literal_comparison)
11604 << LiteralKind << Literal->getSourceRange();
11605
11607 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11608 SourceLocation Start = LHS.get()->getBeginLoc();
11610 CharSourceRange OpRange =
11612
11613 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11614 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11615 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11616 << FixItHint::CreateInsertion(End, "]");
11617 }
11618}
11619
11620/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11623 BinaryOperatorKind Opc) {
11624 // Check that left hand side is !something.
11625 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11626 if (!UO || UO->getOpcode() != UO_LNot) return;
11627
11628 // Only check if the right hand side is non-bool arithmetic type.
11629 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11630
11631 // Make sure that the something in !something is not bool.
11632 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11633 if (SubExpr->isKnownToHaveBooleanValue()) return;
11634
11635 // Emit warning.
11636 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11637 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11638 << Loc << IsBitwiseOp;
11639
11640 // First note suggest !(x < y)
11641 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11642 SourceLocation FirstClose = RHS.get()->getEndLoc();
11643 FirstClose = S.getLocForEndOfToken(FirstClose);
11644 if (FirstClose.isInvalid())
11645 FirstOpen = SourceLocation();
11646 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11647 << IsBitwiseOp
11648 << FixItHint::CreateInsertion(FirstOpen, "(")
11649 << FixItHint::CreateInsertion(FirstClose, ")");
11650
11651 // Second note suggests (!x) < y
11652 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11653 SourceLocation SecondClose = LHS.get()->getEndLoc();
11654 SecondClose = S.getLocForEndOfToken(SecondClose);
11655 if (SecondClose.isInvalid())
11656 SecondOpen = SourceLocation();
11657 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11658 << FixItHint::CreateInsertion(SecondOpen, "(")
11659 << FixItHint::CreateInsertion(SecondClose, ")");
11660}
11661
11662// Returns true if E refers to a non-weak array.
11663static bool checkForArray(const Expr *E) {
11664 const ValueDecl *D = nullptr;
11665 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11666 D = DR->getDecl();
11667 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11668 if (Mem->isImplicitAccess())
11669 D = Mem->getMemberDecl();
11670 }
11671 if (!D)
11672 return false;
11673 return D->getType()->isArrayType() && !D->isWeak();
11674}
11675
11676/// Diagnose some forms of syntactically-obvious tautological comparison.
11678 Expr *LHS, Expr *RHS,
11679 BinaryOperatorKind Opc) {
11680 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11681 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11682
11683 QualType LHSType = LHS->getType();
11684 QualType RHSType = RHS->getType();
11685 if (LHSType->hasFloatingRepresentation() ||
11686 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11688 return;
11689
11690 // WebAssembly Tables cannot be compared, therefore shouldn't emit
11691 // Tautological diagnostics.
11692 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
11693 return;
11694
11695 // Comparisons between two array types are ill-formed for operator<=>, so
11696 // we shouldn't emit any additional warnings about it.
11697 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11698 return;
11699
11700 // For non-floating point types, check for self-comparisons of the form
11701 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11702 // often indicate logic errors in the program.
11703 //
11704 // NOTE: Don't warn about comparison expressions resulting from macro
11705 // expansion. Also don't warn about comparisons which are only self
11706 // comparisons within a template instantiation. The warnings should catch
11707 // obvious cases in the definition of the template anyways. The idea is to
11708 // warn when the typed comparison operator will always evaluate to the same
11709 // result.
11710
11711 // Used for indexing into %select in warn_comparison_always
11712 enum {
11713 AlwaysConstant,
11714 AlwaysTrue,
11715 AlwaysFalse,
11716 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11717 };
11718
11719 // C++2a [depr.array.comp]:
11720 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11721 // operands of array type are deprecated.
11722 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
11723 RHSStripped->getType()->isArrayType()) {
11724 S.Diag(Loc, diag::warn_depr_array_comparison)
11725 << LHS->getSourceRange() << RHS->getSourceRange()
11726 << LHSStripped->getType() << RHSStripped->getType();
11727 // Carry on to produce the tautological comparison warning, if this
11728 // expression is potentially-evaluated, we can resolve the array to a
11729 // non-weak declaration, and so on.
11730 }
11731
11732 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11733 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11734 unsigned Result;
11735 switch (Opc) {
11736 case BO_EQ:
11737 case BO_LE:
11738 case BO_GE:
11739 Result = AlwaysTrue;
11740 break;
11741 case BO_NE:
11742 case BO_LT:
11743 case BO_GT:
11744 Result = AlwaysFalse;
11745 break;
11746 case BO_Cmp:
11747 Result = AlwaysEqual;
11748 break;
11749 default:
11750 Result = AlwaysConstant;
11751 break;
11752 }
11753 S.DiagRuntimeBehavior(Loc, nullptr,
11754 S.PDiag(diag::warn_comparison_always)
11755 << 0 /*self-comparison*/
11756 << Result);
11757 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11758 // What is it always going to evaluate to?
11759 unsigned Result;
11760 switch (Opc) {
11761 case BO_EQ: // e.g. array1 == array2
11762 Result = AlwaysFalse;
11763 break;
11764 case BO_NE: // e.g. array1 != array2
11765 Result = AlwaysTrue;
11766 break;
11767 default: // e.g. array1 <= array2
11768 // The best we can say is 'a constant'
11769 Result = AlwaysConstant;
11770 break;
11771 }
11772 S.DiagRuntimeBehavior(Loc, nullptr,
11773 S.PDiag(diag::warn_comparison_always)
11774 << 1 /*array comparison*/
11775 << Result);
11776 }
11777 }
11778
11779 if (isa<CastExpr>(LHSStripped))
11780 LHSStripped = LHSStripped->IgnoreParenCasts();
11781 if (isa<CastExpr>(RHSStripped))
11782 RHSStripped = RHSStripped->IgnoreParenCasts();
11783
11784 // Warn about comparisons against a string constant (unless the other
11785 // operand is null); the user probably wants string comparison function.
11786 Expr *LiteralString = nullptr;
11787 Expr *LiteralStringStripped = nullptr;
11788 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11789 !RHSStripped->isNullPointerConstant(S.Context,
11791 LiteralString = LHS;
11792 LiteralStringStripped = LHSStripped;
11793 } else if ((isa<StringLiteral>(RHSStripped) ||
11794 isa<ObjCEncodeExpr>(RHSStripped)) &&
11795 !LHSStripped->isNullPointerConstant(S.Context,
11797 LiteralString = RHS;
11798 LiteralStringStripped = RHSStripped;
11799 }
11800
11801 if (LiteralString) {
11802 S.DiagRuntimeBehavior(Loc, nullptr,
11803 S.PDiag(diag::warn_stringcompare)
11804 << isa<ObjCEncodeExpr>(LiteralStringStripped)
11805 << LiteralString->getSourceRange());
11806 }
11807}
11808
11810 switch (CK) {
11811 default: {
11812#ifndef NDEBUG
11813 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11814 << "\n";
11815#endif
11816 llvm_unreachable("unhandled cast kind");
11817 }
11818 case CK_UserDefinedConversion:
11819 return ICK_Identity;
11820 case CK_LValueToRValue:
11821 return ICK_Lvalue_To_Rvalue;
11822 case CK_ArrayToPointerDecay:
11823 return ICK_Array_To_Pointer;
11824 case CK_FunctionToPointerDecay:
11826 case CK_IntegralCast:
11828 case CK_FloatingCast:
11830 case CK_IntegralToFloating:
11831 case CK_FloatingToIntegral:
11832 return ICK_Floating_Integral;
11833 case CK_IntegralComplexCast:
11834 case CK_FloatingComplexCast:
11835 case CK_FloatingComplexToIntegralComplex:
11836 case CK_IntegralComplexToFloatingComplex:
11838 case CK_FloatingComplexToReal:
11839 case CK_FloatingRealToComplex:
11840 case CK_IntegralComplexToReal:
11841 case CK_IntegralRealToComplex:
11842 return ICK_Complex_Real;
11843 case CK_HLSLArrayRValue:
11844 return ICK_HLSL_Array_RValue;
11845 }
11846}
11847
11849 QualType FromType,
11851 // Check for a narrowing implicit conversion.
11854 SCS.setToType(0, FromType);
11855 SCS.setToType(1, ToType);
11856 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
11857 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
11858
11859 APValue PreNarrowingValue;
11860 QualType PreNarrowingType;
11861 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
11862 PreNarrowingType,
11863 /*IgnoreFloatToIntegralConversion*/ true)) {
11865 // Implicit conversion to a narrower type, but the expression is
11866 // value-dependent so we can't tell whether it's actually narrowing.
11867 case NK_Not_Narrowing:
11868 return false;
11869
11871 // Implicit conversion to a narrower type, and the value is not a constant
11872 // expression.
11873 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11874 << /*Constant*/ 1
11875 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
11876 return true;
11877
11879 // Implicit conversion to a narrower type, and the value is not a constant
11880 // expression.
11881 case NK_Type_Narrowing:
11882 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
11883 << /*Constant*/ 0 << FromType << ToType;
11884 // TODO: It's not a constant expression, but what if the user intended it
11885 // to be? Can we produce notes to help them figure out why it isn't?
11886 return true;
11887 }
11888 llvm_unreachable("unhandled case in switch");
11889}
11890
11892 ExprResult &LHS,
11893 ExprResult &RHS,
11895 QualType LHSType = LHS.get()->getType();
11896 QualType RHSType = RHS.get()->getType();
11897 // Dig out the original argument type and expression before implicit casts
11898 // were applied. These are the types/expressions we need to check the
11899 // [expr.spaceship] requirements against.
11900 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
11901 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
11902 QualType LHSStrippedType = LHSStripped.get()->getType();
11903 QualType RHSStrippedType = RHSStripped.get()->getType();
11904
11905 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
11906 // other is not, the program is ill-formed.
11907 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
11908 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11909 return QualType();
11910 }
11911
11912 // FIXME: Consider combining this with checkEnumArithmeticConversions.
11913 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
11914 RHSStrippedType->isEnumeralType();
11915 if (NumEnumArgs == 1) {
11916 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
11917 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
11918 if (OtherTy->hasFloatingRepresentation()) {
11919 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
11920 return QualType();
11921 }
11922 }
11923 if (NumEnumArgs == 2) {
11924 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
11925 // type E, the operator yields the result of converting the operands
11926 // to the underlying type of E and applying <=> to the converted operands.
11927 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
11928 S.InvalidOperands(Loc, LHS, RHS);
11929 return QualType();
11930 }
11931 QualType IntType =
11932 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
11933 assert(IntType->isArithmeticType());
11934
11935 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
11936 // promote the boolean type, and all other promotable integer types, to
11937 // avoid this.
11938 if (S.Context.isPromotableIntegerType(IntType))
11939 IntType = S.Context.getPromotedIntegerType(IntType);
11940
11941 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
11942 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
11943 LHSType = RHSType = IntType;
11944 }
11945
11946 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
11947 // usual arithmetic conversions are applied to the operands.
11948 QualType Type =
11950 if (LHS.isInvalid() || RHS.isInvalid())
11951 return QualType();
11952 if (Type.isNull())
11953 return S.InvalidOperands(Loc, LHS, RHS);
11954
11955 std::optional<ComparisonCategoryType> CCT =
11957 if (!CCT)
11958 return S.InvalidOperands(Loc, LHS, RHS);
11959
11960 bool HasNarrowing = checkThreeWayNarrowingConversion(
11961 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
11962 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
11963 RHS.get()->getBeginLoc());
11964 if (HasNarrowing)
11965 return QualType();
11966
11967 assert(!Type.isNull() && "composite type for <=> has not been set");
11968
11971}
11972
11974 ExprResult &RHS,
11976 BinaryOperatorKind Opc) {
11977 if (Opc == BO_Cmp)
11978 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
11979
11980 // C99 6.5.8p3 / C99 6.5.9p4
11981 QualType Type =
11983 if (LHS.isInvalid() || RHS.isInvalid())
11984 return QualType();
11985 if (Type.isNull())
11986 return S.InvalidOperands(Loc, LHS, RHS);
11987 assert(Type->isArithmeticType() || Type->isEnumeralType());
11988
11990 return S.InvalidOperands(Loc, LHS, RHS);
11991
11992 // Check for comparisons of floating point operands using != and ==.
11994 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
11995
11996 // The result of comparisons is 'bool' in C++, 'int' in C.
11998}
11999
12001 if (!NullE.get()->getType()->isAnyPointerType())
12002 return;
12003 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12004 if (!E.get()->getType()->isAnyPointerType() &&
12008 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12009 if (CL->getValue() == 0)
12010 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12011 << NullValue
12013 NullValue ? "NULL" : "(void *)0");
12014 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12015 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12017 if (T == Context.CharTy)
12018 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12019 << NullValue
12021 NullValue ? "NULL" : "(void *)0");
12022 }
12023 }
12024}
12025
12026// C99 6.5.8, C++ [expr.rel]
12029 BinaryOperatorKind Opc) {
12030 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12031 bool IsThreeWay = Opc == BO_Cmp;
12032 bool IsOrdered = IsRelational || IsThreeWay;
12033 auto IsAnyPointerType = [](ExprResult E) {
12034 QualType Ty = E.get()->getType();
12035 return Ty->isPointerType() || Ty->isMemberPointerType();
12036 };
12037
12038 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12039 // type, array-to-pointer, ..., conversions are performed on both operands to
12040 // bring them to their composite type.
12041 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12042 // any type-related checks.
12043 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12045 if (LHS.isInvalid())
12046 return QualType();
12048 if (RHS.isInvalid())
12049 return QualType();
12050 } else {
12051 LHS = DefaultLvalueConversion(LHS.get());
12052 if (LHS.isInvalid())
12053 return QualType();
12054 RHS = DefaultLvalueConversion(RHS.get());
12055 if (RHS.isInvalid())
12056 return QualType();
12057 }
12058
12059 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12063 }
12064
12065 // Handle vector comparisons separately.
12066 if (LHS.get()->getType()->isVectorType() ||
12067 RHS.get()->getType()->isVectorType())
12068 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12069
12070 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12071 RHS.get()->getType()->isSveVLSBuiltinType())
12072 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12073
12074 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12075 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12076
12077 QualType LHSType = LHS.get()->getType();
12078 QualType RHSType = RHS.get()->getType();
12079 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12080 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12081 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12082
12083 if ((LHSType->isPointerType() &&
12085 (RHSType->isPointerType() &&
12087 return InvalidOperands(Loc, LHS, RHS);
12088
12089 const Expr::NullPointerConstantKind LHSNullKind =
12091 const Expr::NullPointerConstantKind RHSNullKind =
12093 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12094 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12095
12096 auto computeResultTy = [&]() {
12097 if (Opc != BO_Cmp)
12099 assert(getLangOpts().CPlusPlus);
12100 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12101
12102 QualType CompositeTy = LHS.get()->getType();
12103 assert(!CompositeTy->isReferenceType());
12104
12105 std::optional<ComparisonCategoryType> CCT =
12107 if (!CCT)
12108 return InvalidOperands(Loc, LHS, RHS);
12109
12110 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12111 // P0946R0: Comparisons between a null pointer constant and an object
12112 // pointer result in std::strong_equality, which is ill-formed under
12113 // P1959R0.
12114 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12115 << (LHSIsNull ? LHS.get()->getSourceRange()
12116 : RHS.get()->getSourceRange());
12117 return QualType();
12118 }
12119
12122 };
12123
12124 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12125 bool IsEquality = Opc == BO_EQ;
12126 if (RHSIsNull)
12127 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12128 RHS.get()->getSourceRange());
12129 else
12130 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12131 LHS.get()->getSourceRange());
12132 }
12133
12134 if (IsOrdered && LHSType->isFunctionPointerType() &&
12135 RHSType->isFunctionPointerType()) {
12136 // Valid unless a relational comparison of function pointers
12137 bool IsError = Opc == BO_Cmp;
12138 auto DiagID =
12139 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12140 : getLangOpts().CPlusPlus
12141 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12142 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12143 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12144 << RHS.get()->getSourceRange();
12145 if (IsError)
12146 return QualType();
12147 }
12148
12149 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12150 (RHSType->isIntegerType() && !RHSIsNull)) {
12151 // Skip normal pointer conversion checks in this case; we have better
12152 // diagnostics for this below.
12153 } else if (getLangOpts().CPlusPlus) {
12154 // Equality comparison of a function pointer to a void pointer is invalid,
12155 // but we allow it as an extension.
12156 // FIXME: If we really want to allow this, should it be part of composite
12157 // pointer type computation so it works in conditionals too?
12158 if (!IsOrdered &&
12159 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12160 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12161 // This is a gcc extension compatibility comparison.
12162 // In a SFINAE context, we treat this as a hard error to maintain
12163 // conformance with the C++ standard.
12165 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12166
12167 if (isSFINAEContext())
12168 return QualType();
12169
12170 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12171 return computeResultTy();
12172 }
12173
12174 // C++ [expr.eq]p2:
12175 // If at least one operand is a pointer [...] bring them to their
12176 // composite pointer type.
12177 // C++ [expr.spaceship]p6
12178 // If at least one of the operands is of pointer type, [...] bring them
12179 // to their composite pointer type.
12180 // C++ [expr.rel]p2:
12181 // If both operands are pointers, [...] bring them to their composite
12182 // pointer type.
12183 // For <=>, the only valid non-pointer types are arrays and functions, and
12184 // we already decayed those, so this is really the same as the relational
12185 // comparison rule.
12186 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12187 (IsOrdered ? 2 : 1) &&
12188 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12189 RHSType->isObjCObjectPointerType()))) {
12190 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12191 return QualType();
12192 return computeResultTy();
12193 }
12194 } else if (LHSType->isPointerType() &&
12195 RHSType->isPointerType()) { // C99 6.5.8p2
12196 // All of the following pointer-related warnings are GCC extensions, except
12197 // when handling null pointer constants.
12198 QualType LCanPointeeTy =
12200 QualType RCanPointeeTy =
12202
12203 // C99 6.5.9p2 and C99 6.5.8p2
12204 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12205 RCanPointeeTy.getUnqualifiedType())) {
12206 if (IsRelational) {
12207 // Pointers both need to point to complete or incomplete types
12208 if ((LCanPointeeTy->isIncompleteType() !=
12209 RCanPointeeTy->isIncompleteType()) &&
12210 !getLangOpts().C11) {
12211 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12212 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12213 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12214 << RCanPointeeTy->isIncompleteType();
12215 }
12216 }
12217 } else if (!IsRelational &&
12218 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12219 // Valid unless comparison between non-null pointer and function pointer
12220 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12221 && !LHSIsNull && !RHSIsNull)
12223 /*isError*/false);
12224 } else {
12225 // Invalid
12226 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12227 }
12228 if (LCanPointeeTy != RCanPointeeTy) {
12229 // Treat NULL constant as a special case in OpenCL.
12230 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12231 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12232 Diag(Loc,
12233 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12234 << LHSType << RHSType << 0 /* comparison */
12235 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12236 }
12237 }
12238 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12239 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12240 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12241 : CK_BitCast;
12242 if (LHSIsNull && !RHSIsNull)
12243 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12244 else
12245 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12246 }
12247 return computeResultTy();
12248 }
12249
12250
12251 // C++ [expr.eq]p4:
12252 // Two operands of type std::nullptr_t or one operand of type
12253 // std::nullptr_t and the other a null pointer constant compare
12254 // equal.
12255 // C23 6.5.9p5:
12256 // If both operands have type nullptr_t or one operand has type nullptr_t
12257 // and the other is a null pointer constant, they compare equal if the
12258 // former is a null pointer.
12259 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12260 if (LHSType->isNullPtrType()) {
12261 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12262 return computeResultTy();
12263 }
12264 if (RHSType->isNullPtrType()) {
12265 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12266 return computeResultTy();
12267 }
12268 }
12269
12270 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12271 // C23 6.5.9p6:
12272 // Otherwise, at least one operand is a pointer. If one is a pointer and
12273 // the other is a null pointer constant or has type nullptr_t, they
12274 // compare equal
12275 if (LHSIsNull && RHSType->isPointerType()) {
12276 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12277 return computeResultTy();
12278 }
12279 if (RHSIsNull && LHSType->isPointerType()) {
12280 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12281 return computeResultTy();
12282 }
12283 }
12284
12285 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12286 // These aren't covered by the composite pointer type rules.
12287 if (!IsOrdered && RHSType->isNullPtrType() &&
12288 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12289 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12290 return computeResultTy();
12291 }
12292 if (!IsOrdered && LHSType->isNullPtrType() &&
12293 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12294 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12295 return computeResultTy();
12296 }
12297
12298 if (getLangOpts().CPlusPlus) {
12299 if (IsRelational &&
12300 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12301 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12302 // HACK: Relational comparison of nullptr_t against a pointer type is
12303 // invalid per DR583, but we allow it within std::less<> and friends,
12304 // since otherwise common uses of it break.
12305 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12306 // friends to have std::nullptr_t overload candidates.
12307 DeclContext *DC = CurContext;
12308 if (isa<FunctionDecl>(DC))
12309 DC = DC->getParent();
12310 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12311 if (CTSD->isInStdNamespace() &&
12312 llvm::StringSwitch<bool>(CTSD->getName())
12313 .Cases("less", "less_equal", "greater", "greater_equal", true)
12314 .Default(false)) {
12315 if (RHSType->isNullPtrType())
12316 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12317 else
12318 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12319 return computeResultTy();
12320 }
12321 }
12322 }
12323
12324 // C++ [expr.eq]p2:
12325 // If at least one operand is a pointer to member, [...] bring them to
12326 // their composite pointer type.
12327 if (!IsOrdered &&
12328 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12329 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12330 return QualType();
12331 else
12332 return computeResultTy();
12333 }
12334 }
12335
12336 // Handle block pointer types.
12337 if (!IsOrdered && LHSType->isBlockPointerType() &&
12338 RHSType->isBlockPointerType()) {
12339 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12340 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12341
12342 if (!LHSIsNull && !RHSIsNull &&
12343 !Context.typesAreCompatible(lpointee, rpointee)) {
12344 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12345 << LHSType << RHSType << LHS.get()->getSourceRange()
12346 << RHS.get()->getSourceRange();
12347 }
12348 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12349 return computeResultTy();
12350 }
12351
12352 // Allow block pointers to be compared with null pointer constants.
12353 if (!IsOrdered
12354 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12355 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12356 if (!LHSIsNull && !RHSIsNull) {
12357 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12359 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12360 ->getPointeeType()->isVoidType())))
12361 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12362 << LHSType << RHSType << LHS.get()->getSourceRange()
12363 << RHS.get()->getSourceRange();
12364 }
12365 if (LHSIsNull && !RHSIsNull)
12366 LHS = ImpCastExprToType(LHS.get(), RHSType,
12367 RHSType->isPointerType() ? CK_BitCast
12368 : CK_AnyPointerToBlockPointerCast);
12369 else
12370 RHS = ImpCastExprToType(RHS.get(), LHSType,
12371 LHSType->isPointerType() ? CK_BitCast
12372 : CK_AnyPointerToBlockPointerCast);
12373 return computeResultTy();
12374 }
12375
12376 if (LHSType->isObjCObjectPointerType() ||
12377 RHSType->isObjCObjectPointerType()) {
12378 const PointerType *LPT = LHSType->getAs<PointerType>();
12379 const PointerType *RPT = RHSType->getAs<PointerType>();
12380 if (LPT || RPT) {
12381 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12382 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12383
12384 if (!LPtrToVoid && !RPtrToVoid &&
12385 !Context.typesAreCompatible(LHSType, RHSType)) {
12386 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12387 /*isError*/false);
12388 }
12389 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12390 // the RHS, but we have test coverage for this behavior.
12391 // FIXME: Consider using convertPointersToCompositeType in C++.
12392 if (LHSIsNull && !RHSIsNull) {
12393 Expr *E = LHS.get();
12394 if (getLangOpts().ObjCAutoRefCount)
12395 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
12397 LHS = ImpCastExprToType(E, RHSType,
12398 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12399 }
12400 else {
12401 Expr *E = RHS.get();
12402 if (getLangOpts().ObjCAutoRefCount)
12403 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
12405 /*Diagnose=*/true,
12406 /*DiagnoseCFAudited=*/false, Opc);
12407 RHS = ImpCastExprToType(E, LHSType,
12408 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12409 }
12410 return computeResultTy();
12411 }
12412 if (LHSType->isObjCObjectPointerType() &&
12413 RHSType->isObjCObjectPointerType()) {
12414 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12415 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12416 /*isError*/false);
12418 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12419
12420 if (LHSIsNull && !RHSIsNull)
12421 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12422 else
12423 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12424 return computeResultTy();
12425 }
12426
12427 if (!IsOrdered && LHSType->isBlockPointerType() &&
12429 LHS = ImpCastExprToType(LHS.get(), RHSType,
12430 CK_BlockPointerToObjCPointerCast);
12431 return computeResultTy();
12432 } else if (!IsOrdered &&
12434 RHSType->isBlockPointerType()) {
12435 RHS = ImpCastExprToType(RHS.get(), LHSType,
12436 CK_BlockPointerToObjCPointerCast);
12437 return computeResultTy();
12438 }
12439 }
12440 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12441 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12442 unsigned DiagID = 0;
12443 bool isError = false;
12444 if (LangOpts.DebuggerSupport) {
12445 // Under a debugger, allow the comparison of pointers to integers,
12446 // since users tend to want to compare addresses.
12447 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12448 (RHSIsNull && RHSType->isIntegerType())) {
12449 if (IsOrdered) {
12450 isError = getLangOpts().CPlusPlus;
12451 DiagID =
12452 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12453 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12454 }
12455 } else if (getLangOpts().CPlusPlus) {
12456 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12457 isError = true;
12458 } else if (IsOrdered)
12459 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12460 else
12461 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12462
12463 if (DiagID) {
12464 Diag(Loc, DiagID)
12465 << LHSType << RHSType << LHS.get()->getSourceRange()
12466 << RHS.get()->getSourceRange();
12467 if (isError)
12468 return QualType();
12469 }
12470
12471 if (LHSType->isIntegerType())
12472 LHS = ImpCastExprToType(LHS.get(), RHSType,
12473 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12474 else
12475 RHS = ImpCastExprToType(RHS.get(), LHSType,
12476 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12477 return computeResultTy();
12478 }
12479
12480 // Handle block pointers.
12481 if (!IsOrdered && RHSIsNull
12482 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12483 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12484 return computeResultTy();
12485 }
12486 if (!IsOrdered && LHSIsNull
12487 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12488 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12489 return computeResultTy();
12490 }
12491
12492 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12493 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12494 return computeResultTy();
12495 }
12496
12497 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12498 return computeResultTy();
12499 }
12500
12501 if (LHSIsNull && RHSType->isQueueT()) {
12502 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12503 return computeResultTy();
12504 }
12505
12506 if (LHSType->isQueueT() && RHSIsNull) {
12507 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12508 return computeResultTy();
12509 }
12510 }
12511
12512 return InvalidOperands(Loc, LHS, RHS);
12513}
12514
12516 const VectorType *VTy = V->castAs<VectorType>();
12517 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12518
12519 if (isa<ExtVectorType>(VTy)) {
12520 if (VTy->isExtVectorBoolType())
12522 if (TypeSize == Context.getTypeSize(Context.CharTy))
12524 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12526 if (TypeSize == Context.getTypeSize(Context.IntTy))
12528 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12530 if (TypeSize == Context.getTypeSize(Context.LongTy))
12532 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12533 "Unhandled vector element size in vector compare");
12535 }
12536
12537 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12540 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12543 if (TypeSize == Context.getTypeSize(Context.LongTy))
12546 if (TypeSize == Context.getTypeSize(Context.IntTy))
12549 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12552 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12553 "Unhandled vector element size in vector compare");
12556}
12557
12559 const BuiltinType *VTy = V->castAs<BuiltinType>();
12560 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
12561
12562 const QualType ETy = V->getSveEltType(Context);
12563 const auto TypeSize = Context.getTypeSize(ETy);
12564
12565 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12566 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12567 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12568}
12569
12572 BinaryOperatorKind Opc) {
12573 if (Opc == BO_Cmp) {
12574 Diag(Loc, diag::err_three_way_vector_comparison);
12575 return QualType();
12576 }
12577
12578 // Check to make sure we're operating on vectors of the same type and width,
12579 // Allowing one side to be a scalar of element type.
12580 QualType vType =
12581 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12582 /*AllowBothBool*/ true,
12583 /*AllowBoolConversions*/ getLangOpts().ZVector,
12584 /*AllowBooleanOperation*/ true,
12585 /*ReportInvalid*/ true);
12586 if (vType.isNull())
12587 return vType;
12588
12589 QualType LHSType = LHS.get()->getType();
12590
12591 // Determine the return type of a vector compare. By default clang will return
12592 // a scalar for all vector compares except vector bool and vector pixel.
12593 // With the gcc compiler we will always return a vector type and with the xl
12594 // compiler we will always return a scalar type. This switch allows choosing
12595 // which behavior is prefered.
12596 if (getLangOpts().AltiVec) {
12597 switch (getLangOpts().getAltivecSrcCompat()) {
12599 // If AltiVec, the comparison results in a numeric type, i.e.
12600 // bool for C++, int for C
12601 if (vType->castAs<VectorType>()->getVectorKind() ==
12604 else
12605 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12606 break;
12608 // For GCC we always return the vector type.
12609 break;
12612 break;
12613 }
12614 }
12615
12616 // For non-floating point types, check for self-comparisons of the form
12617 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12618 // often indicate logic errors in the program.
12619 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12620
12621 // Check for comparisons of floating point operands using != and ==.
12622 if (LHSType->hasFloatingRepresentation()) {
12623 assert(RHS.get()->getType()->hasFloatingRepresentation());
12624 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12625 }
12626
12627 // Return a signed type for the vector.
12628 return GetSignedVectorType(vType);
12629}
12630
12632 ExprResult &RHS,
12634 BinaryOperatorKind Opc) {
12635 if (Opc == BO_Cmp) {
12636 Diag(Loc, diag::err_three_way_vector_comparison);
12637 return QualType();
12638 }
12639
12640 // Check to make sure we're operating on vectors of the same type and width,
12641 // Allowing one side to be a scalar of element type.
12643 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12644
12645 if (vType.isNull())
12646 return vType;
12647
12648 QualType LHSType = LHS.get()->getType();
12649
12650 // For non-floating point types, check for self-comparisons of the form
12651 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12652 // often indicate logic errors in the program.
12653 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12654
12655 // Check for comparisons of floating point operands using != and ==.
12656 if (LHSType->hasFloatingRepresentation()) {
12657 assert(RHS.get()->getType()->hasFloatingRepresentation());
12658 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12659 }
12660
12661 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12662 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12663
12664 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12665 RHSBuiltinTy->isSVEBool())
12666 return LHSType;
12667
12668 // Return a signed type for the vector.
12669 return GetSignedSizelessVectorType(vType);
12670}
12671
12672static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12673 const ExprResult &XorRHS,
12674 const SourceLocation Loc) {
12675 // Do not diagnose macros.
12676 if (Loc.isMacroID())
12677 return;
12678
12679 // Do not diagnose if both LHS and RHS are macros.
12680 if (XorLHS.get()->getExprLoc().isMacroID() &&
12681 XorRHS.get()->getExprLoc().isMacroID())
12682 return;
12683
12684 bool Negative = false;
12685 bool ExplicitPlus = false;
12686 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12687 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12688
12689 if (!LHSInt)
12690 return;
12691 if (!RHSInt) {
12692 // Check negative literals.
12693 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12694 UnaryOperatorKind Opc = UO->getOpcode();
12695 if (Opc != UO_Minus && Opc != UO_Plus)
12696 return;
12697 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12698 if (!RHSInt)
12699 return;
12700 Negative = (Opc == UO_Minus);
12701 ExplicitPlus = !Negative;
12702 } else {
12703 return;
12704 }
12705 }
12706
12707 const llvm::APInt &LeftSideValue = LHSInt->getValue();
12708 llvm::APInt RightSideValue = RHSInt->getValue();
12709 if (LeftSideValue != 2 && LeftSideValue != 10)
12710 return;
12711
12712 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12713 return;
12714
12716 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12717 llvm::StringRef ExprStr =
12719
12720 CharSourceRange XorRange =
12722 llvm::StringRef XorStr =
12724 // Do not diagnose if xor keyword/macro is used.
12725 if (XorStr == "xor")
12726 return;
12727
12728 std::string LHSStr = std::string(Lexer::getSourceText(
12729 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12730 S.getSourceManager(), S.getLangOpts()));
12731 std::string RHSStr = std::string(Lexer::getSourceText(
12732 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12733 S.getSourceManager(), S.getLangOpts()));
12734
12735 if (Negative) {
12736 RightSideValue = -RightSideValue;
12737 RHSStr = "-" + RHSStr;
12738 } else if (ExplicitPlus) {
12739 RHSStr = "+" + RHSStr;
12740 }
12741
12742 StringRef LHSStrRef = LHSStr;
12743 StringRef RHSStrRef = RHSStr;
12744 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12745 // literals.
12746 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
12747 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
12748 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
12749 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
12750 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
12751 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
12752 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12753 return;
12754
12755 bool SuggestXor =
12756 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12757 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12758 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12759 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12760 std::string SuggestedExpr = "1 << " + RHSStr;
12761 bool Overflow = false;
12762 llvm::APInt One = (LeftSideValue - 1);
12763 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12764 if (Overflow) {
12765 if (RightSideIntValue < 64)
12766 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12767 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12768 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12769 else if (RightSideIntValue == 64)
12770 S.Diag(Loc, diag::warn_xor_used_as_pow)
12771 << ExprStr << toString(XorValue, 10, true);
12772 else
12773 return;
12774 } else {
12775 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12776 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12777 << toString(PowValue, 10, true)
12779 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12780 }
12781
12782 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12783 << ("0x2 ^ " + RHSStr) << SuggestXor;
12784 } else if (LeftSideValue == 10) {
12785 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12786 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12787 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12788 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12789 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12790 << ("0xA ^ " + RHSStr) << SuggestXor;
12791 }
12792}
12793
12796 // Ensure that either both operands are of the same vector type, or
12797 // one operand is of a vector type and the other is of its element type.
12798 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12799 /*AllowBothBool*/ true,
12800 /*AllowBoolConversions*/ false,
12801 /*AllowBooleanOperation*/ false,
12802 /*ReportInvalid*/ false);
12803 if (vType.isNull())
12804 return InvalidOperands(Loc, LHS, RHS);
12805 if (getLangOpts().OpenCL &&
12806 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12808 return InvalidOperands(Loc, LHS, RHS);
12809 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12810 // usage of the logical operators && and || with vectors in C. This
12811 // check could be notionally dropped.
12812 if (!getLangOpts().CPlusPlus &&
12813 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12814 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12815
12816 return GetSignedVectorType(LHS.get()->getType());
12817}
12818
12821 bool IsCompAssign) {
12822 if (!IsCompAssign) {
12824 if (LHS.isInvalid())
12825 return QualType();
12826 }
12828 if (RHS.isInvalid())
12829 return QualType();
12830
12831 // For conversion purposes, we ignore any qualifiers.
12832 // For example, "const float" and "float" are equivalent.
12833 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
12834 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
12835
12836 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
12837 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
12838 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12839
12840 if (Context.hasSameType(LHSType, RHSType))
12841 return Context.getCommonSugaredType(LHSType, RHSType);
12842
12843 // Type conversion may change LHS/RHS. Keep copies to the original results, in
12844 // case we have to return InvalidOperands.
12845 ExprResult OriginalLHS = LHS;
12846 ExprResult OriginalRHS = RHS;
12847 if (LHSMatType && !RHSMatType) {
12848 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
12849 if (!RHS.isInvalid())
12850 return LHSType;
12851
12852 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12853 }
12854
12855 if (!LHSMatType && RHSMatType) {
12856 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
12857 if (!LHS.isInvalid())
12858 return RHSType;
12859 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
12860 }
12861
12862 return InvalidOperands(Loc, LHS, RHS);
12863}
12864
12867 bool IsCompAssign) {
12868 if (!IsCompAssign) {
12870 if (LHS.isInvalid())
12871 return QualType();
12872 }
12874 if (RHS.isInvalid())
12875 return QualType();
12876
12877 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
12878 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
12879 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
12880
12881 if (LHSMatType && RHSMatType) {
12882 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
12883 return InvalidOperands(Loc, LHS, RHS);
12884
12885 if (Context.hasSameType(LHSMatType, RHSMatType))
12887 LHS.get()->getType().getUnqualifiedType(),
12888 RHS.get()->getType().getUnqualifiedType());
12889
12890 QualType LHSELTy = LHSMatType->getElementType(),
12891 RHSELTy = RHSMatType->getElementType();
12892 if (!Context.hasSameType(LHSELTy, RHSELTy))
12893 return InvalidOperands(Loc, LHS, RHS);
12894
12896 Context.getCommonSugaredType(LHSELTy, RHSELTy),
12897 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
12898 }
12899 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
12900}
12901
12903 switch (Opc) {
12904 default:
12905 return false;
12906 case BO_And:
12907 case BO_AndAssign:
12908 case BO_Or:
12909 case BO_OrAssign:
12910 case BO_Xor:
12911 case BO_XorAssign:
12912 return true;
12913 }
12914}
12915
12918 BinaryOperatorKind Opc) {
12919 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12920
12921 bool IsCompAssign =
12922 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
12923
12924 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
12925
12926 if (LHS.get()->getType()->isVectorType() ||
12927 RHS.get()->getType()->isVectorType()) {
12928 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12930 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
12931 /*AllowBothBool*/ true,
12932 /*AllowBoolConversions*/ getLangOpts().ZVector,
12933 /*AllowBooleanOperation*/ LegalBoolVecOperator,
12934 /*ReportInvalid*/ true);
12935 return InvalidOperands(Loc, LHS, RHS);
12936 }
12937
12938 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12939 RHS.get()->getType()->isSveVLSBuiltinType()) {
12940 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12942 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
12944 return InvalidOperands(Loc, LHS, RHS);
12945 }
12946
12947 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12948 RHS.get()->getType()->isSveVLSBuiltinType()) {
12949 if (LHS.get()->getType()->hasIntegerRepresentation() &&
12951 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
12953 return InvalidOperands(Loc, LHS, RHS);
12954 }
12955
12956 if (Opc == BO_And)
12957 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12958
12959 if (LHS.get()->getType()->hasFloatingRepresentation() ||
12961 return InvalidOperands(Loc, LHS, RHS);
12962
12963 ExprResult LHSResult = LHS, RHSResult = RHS;
12965 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
12966 if (LHSResult.isInvalid() || RHSResult.isInvalid())
12967 return QualType();
12968 LHS = LHSResult.get();
12969 RHS = RHSResult.get();
12970
12971 if (Opc == BO_Xor)
12972 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
12973
12974 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
12975 return compType;
12976 return InvalidOperands(Loc, LHS, RHS);
12977}
12978
12979// C99 6.5.[13,14]
12982 BinaryOperatorKind Opc) {
12983 // Check vector operands differently.
12984 if (LHS.get()->getType()->isVectorType() ||
12985 RHS.get()->getType()->isVectorType())
12986 return CheckVectorLogicalOperands(LHS, RHS, Loc);
12987
12988 bool EnumConstantInBoolContext = false;
12989 for (const ExprResult &HS : {LHS, RHS}) {
12990 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
12991 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
12992 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
12993 EnumConstantInBoolContext = true;
12994 }
12995 }
12996
12997 if (EnumConstantInBoolContext)
12998 Diag(Loc, diag::warn_enum_constant_in_bool_context);
12999
13000 // WebAssembly tables can't be used with logical operators.
13001 QualType LHSTy = LHS.get()->getType();
13002 QualType RHSTy = RHS.get()->getType();
13003 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13004 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13005 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13006 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13007 return InvalidOperands(Loc, LHS, RHS);
13008 }
13009
13010 // Diagnose cases where the user write a logical and/or but probably meant a
13011 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13012 // is a constant.
13013 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13014 !LHS.get()->getType()->isBooleanType() &&
13015 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13016 // Don't warn in macros or template instantiations.
13018 // If the RHS can be constant folded, and if it constant folds to something
13019 // that isn't 0 or 1 (which indicate a potential logical operation that
13020 // happened to fold to true/false) then warn.
13021 // Parens on the RHS are ignored.
13022 Expr::EvalResult EVResult;
13023 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13024 llvm::APSInt Result = EVResult.Val.getInt();
13025 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13026 !RHS.get()->getExprLoc().isMacroID()) ||
13027 (Result != 0 && Result != 1)) {
13028 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13029 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13030 // Suggest replacing the logical operator with the bitwise version
13031 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13032 << (Opc == BO_LAnd ? "&" : "|")
13035 Opc == BO_LAnd ? "&" : "|");
13036 if (Opc == BO_LAnd)
13037 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13038 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13041 RHS.get()->getEndLoc()));
13042 }
13043 }
13044 }
13045
13046 if (!Context.getLangOpts().CPlusPlus) {
13047 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13048 // not operate on the built-in scalar and vector float types.
13049 if (Context.getLangOpts().OpenCL &&
13050 Context.getLangOpts().OpenCLVersion < 120) {
13051 if (LHS.get()->getType()->isFloatingType() ||
13052 RHS.get()->getType()->isFloatingType())
13053 return InvalidOperands(Loc, LHS, RHS);
13054 }
13055
13056 LHS = UsualUnaryConversions(LHS.get());
13057 if (LHS.isInvalid())
13058 return QualType();
13059
13060 RHS = UsualUnaryConversions(RHS.get());
13061 if (RHS.isInvalid())
13062 return QualType();
13063
13064 if (!LHS.get()->getType()->isScalarType() ||
13065 !RHS.get()->getType()->isScalarType())
13066 return InvalidOperands(Loc, LHS, RHS);
13067
13068 return Context.IntTy;
13069 }
13070
13071 // The following is safe because we only use this method for
13072 // non-overloadable operands.
13073
13074 // C++ [expr.log.and]p1
13075 // C++ [expr.log.or]p1
13076 // The operands are both contextually converted to type bool.
13078 if (LHSRes.isInvalid())
13079 return InvalidOperands(Loc, LHS, RHS);
13080 LHS = LHSRes;
13081
13083 if (RHSRes.isInvalid())
13084 return InvalidOperands(Loc, LHS, RHS);
13085 RHS = RHSRes;
13086
13087 // C++ [expr.log.and]p2
13088 // C++ [expr.log.or]p2
13089 // The result is a bool.
13090 return Context.BoolTy;
13091}
13092
13093static bool IsReadonlyMessage(Expr *E, Sema &S) {
13094 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13095 if (!ME) return false;
13096 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13097 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13099 if (!Base) return false;
13100 return Base->getMethodDecl() != nullptr;
13101}
13102
13103/// Is the given expression (which must be 'const') a reference to a
13104/// variable which was originally non-const, but which has become
13105/// 'const' due to being captured within a block?
13108 assert(E->isLValue() && E->getType().isConstQualified());
13109 E = E->IgnoreParens();
13110
13111 // Must be a reference to a declaration from an enclosing scope.
13112 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13113 if (!DRE) return NCCK_None;
13115
13116 // The declaration must be a variable which is not declared 'const'.
13117 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13118 if (!var) return NCCK_None;
13119 if (var->getType().isConstQualified()) return NCCK_None;
13120 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
13121
13122 // Decide whether the first capture was for a block or a lambda.
13123 DeclContext *DC = S.CurContext, *Prev = nullptr;
13124 // Decide whether the first capture was for a block or a lambda.
13125 while (DC) {
13126 // For init-capture, it is possible that the variable belongs to the
13127 // template pattern of the current context.
13128 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13129 if (var->isInitCapture() &&
13130 FD->getTemplateInstantiationPattern() == var->getDeclContext())
13131 break;
13132 if (DC == var->getDeclContext())
13133 break;
13134 Prev = DC;
13135 DC = DC->getParent();
13136 }
13137 // Unless we have an init-capture, we've gone one step too far.
13138 if (!var->isInitCapture())
13139 DC = Prev;
13140 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13141}
13142
13143static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13144 Ty = Ty.getNonReferenceType();
13145 if (IsDereference && Ty->isPointerType())
13146 Ty = Ty->getPointeeType();
13147 return !Ty.isConstQualified();
13148}
13149
13150// Update err_typecheck_assign_const and note_typecheck_assign_const
13151// when this enum is changed.
13152enum {
13158 ConstUnknown, // Keep as last element
13159};
13160
13161/// Emit the "read-only variable not assignable" error and print notes to give
13162/// more information about why the variable is not assignable, such as pointing
13163/// to the declaration of a const variable, showing that a method is const, or
13164/// that the function is returning a const reference.
13165static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13167 SourceRange ExprRange = E->getSourceRange();
13168
13169 // Only emit one error on the first const found. All other consts will emit
13170 // a note to the error.
13171 bool DiagnosticEmitted = false;
13172
13173 // Track if the current expression is the result of a dereference, and if the
13174 // next checked expression is the result of a dereference.
13175 bool IsDereference = false;
13176 bool NextIsDereference = false;
13177
13178 // Loop to process MemberExpr chains.
13179 while (true) {
13180 IsDereference = NextIsDereference;
13181
13183 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13184 NextIsDereference = ME->isArrow();
13185 const ValueDecl *VD = ME->getMemberDecl();
13186 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13187 // Mutable fields can be modified even if the class is const.
13188 if (Field->isMutable()) {
13189 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13190 break;
13191 }
13192
13193 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13194 if (!DiagnosticEmitted) {
13195 S.Diag(Loc, diag::err_typecheck_assign_const)
13196 << ExprRange << ConstMember << false /*static*/ << Field
13197 << Field->getType();
13198 DiagnosticEmitted = true;
13199 }
13200 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13201 << ConstMember << false /*static*/ << Field << Field->getType()
13202 << Field->getSourceRange();
13203 }
13204 E = ME->getBase();
13205 continue;
13206 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13207 if (VDecl->getType().isConstQualified()) {
13208 if (!DiagnosticEmitted) {
13209 S.Diag(Loc, diag::err_typecheck_assign_const)
13210 << ExprRange << ConstMember << true /*static*/ << VDecl
13211 << VDecl->getType();
13212 DiagnosticEmitted = true;
13213 }
13214 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13215 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13216 << VDecl->getSourceRange();
13217 }
13218 // Static fields do not inherit constness from parents.
13219 break;
13220 }
13221 break; // End MemberExpr
13222 } else if (const ArraySubscriptExpr *ASE =
13223 dyn_cast<ArraySubscriptExpr>(E)) {
13224 E = ASE->getBase()->IgnoreParenImpCasts();
13225 continue;
13226 } else if (const ExtVectorElementExpr *EVE =
13227 dyn_cast<ExtVectorElementExpr>(E)) {
13228 E = EVE->getBase()->IgnoreParenImpCasts();
13229 continue;
13230 }
13231 break;
13232 }
13233
13234 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13235 // Function calls
13236 const FunctionDecl *FD = CE->getDirectCallee();
13237 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13238 if (!DiagnosticEmitted) {
13239 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13240 << ConstFunction << FD;
13241 DiagnosticEmitted = true;
13242 }
13244 diag::note_typecheck_assign_const)
13245 << ConstFunction << FD << FD->getReturnType()
13246 << FD->getReturnTypeSourceRange();
13247 }
13248 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13249 // Point to variable declaration.
13250 if (const ValueDecl *VD = DRE->getDecl()) {
13251 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13252 if (!DiagnosticEmitted) {
13253 S.Diag(Loc, diag::err_typecheck_assign_const)
13254 << ExprRange << ConstVariable << VD << VD->getType();
13255 DiagnosticEmitted = true;
13256 }
13257 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13258 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13259 }
13260 }
13261 } else if (isa<CXXThisExpr>(E)) {
13262 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13263 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13264 if (MD->isConst()) {
13265 if (!DiagnosticEmitted) {
13266 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13267 << ConstMethod << MD;
13268 DiagnosticEmitted = true;
13269 }
13270 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13271 << ConstMethod << MD << MD->getSourceRange();
13272 }
13273 }
13274 }
13275 }
13276
13277 if (DiagnosticEmitted)
13278 return;
13279
13280 // Can't determine a more specific message, so display the generic error.
13281 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13282}
13283
13289
13291 const RecordType *Ty,
13293 OriginalExprKind OEK,
13294 bool &DiagnosticEmitted) {
13295 std::vector<const RecordType *> RecordTypeList;
13296 RecordTypeList.push_back(Ty);
13297 unsigned NextToCheckIndex = 0;
13298 // We walk the record hierarchy breadth-first to ensure that we print
13299 // diagnostics in field nesting order.
13300 while (RecordTypeList.size() > NextToCheckIndex) {
13301 bool IsNested = NextToCheckIndex > 0;
13302 for (const FieldDecl *Field :
13303 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13304 // First, check every field for constness.
13305 QualType FieldTy = Field->getType();
13306 if (FieldTy.isConstQualified()) {
13307 if (!DiagnosticEmitted) {
13308 S.Diag(Loc, diag::err_typecheck_assign_const)
13309 << Range << NestedConstMember << OEK << VD
13310 << IsNested << Field;
13311 DiagnosticEmitted = true;
13312 }
13313 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13314 << NestedConstMember << IsNested << Field
13315 << FieldTy << Field->getSourceRange();
13316 }
13317
13318 // Then we append it to the list to check next in order.
13319 FieldTy = FieldTy.getCanonicalType();
13320 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13321 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13322 RecordTypeList.push_back(FieldRecTy);
13323 }
13324 }
13325 ++NextToCheckIndex;
13326 }
13327}
13328
13329/// Emit an error for the case where a record we are trying to assign to has a
13330/// const-qualified field somewhere in its hierarchy.
13333 QualType Ty = E->getType();
13334 assert(Ty->isRecordType() && "lvalue was not record?");
13336 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13337 bool DiagEmitted = false;
13338
13339 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13340 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13341 Range, OEK_Member, DiagEmitted);
13342 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13343 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13344 Range, OEK_Variable, DiagEmitted);
13345 else
13346 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13347 Range, OEK_LValue, DiagEmitted);
13348 if (!DiagEmitted)
13350}
13351
13352/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13353/// emit an error and return true. If so, return false.
13355 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13356
13358
13359 SourceLocation OrigLoc = Loc;
13361 &Loc);
13362 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13364 if (IsLV == Expr::MLV_Valid)
13365 return false;
13366
13367 unsigned DiagID = 0;
13368 bool NeedType = false;
13369 switch (IsLV) { // C99 6.5.16p2
13371 // Use a specialized diagnostic when we're assigning to an object
13372 // from an enclosing function or block.
13374 if (NCCK == NCCK_Block)
13375 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13376 else
13377 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13378 break;
13379 }
13380
13381 // In ARC, use some specialized diagnostics for occasions where we
13382 // infer 'const'. These are always pseudo-strong variables.
13383 if (S.getLangOpts().ObjCAutoRefCount) {
13384 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13385 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13386 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13387
13388 // Use the normal diagnostic if it's pseudo-__strong but the
13389 // user actually wrote 'const'.
13390 if (var->isARCPseudoStrong() &&
13391 (!var->getTypeSourceInfo() ||
13392 !var->getTypeSourceInfo()->getType().isConstQualified())) {
13393 // There are three pseudo-strong cases:
13394 // - self
13395 ObjCMethodDecl *method = S.getCurMethodDecl();
13396 if (method && var == method->getSelfDecl()) {
13397 DiagID = method->isClassMethod()
13398 ? diag::err_typecheck_arc_assign_self_class_method
13399 : diag::err_typecheck_arc_assign_self;
13400
13401 // - Objective-C externally_retained attribute.
13402 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13403 isa<ParmVarDecl>(var)) {
13404 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13405
13406 // - fast enumeration variables
13407 } else {
13408 DiagID = diag::err_typecheck_arr_assign_enumeration;
13409 }
13410
13411 SourceRange Assign;
13412 if (Loc != OrigLoc)
13413 Assign = SourceRange(OrigLoc, OrigLoc);
13414 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13415 // We need to preserve the AST regardless, so migration tool
13416 // can do its job.
13417 return false;
13418 }
13419 }
13420 }
13421
13422 // If none of the special cases above are triggered, then this is a
13423 // simple const assignment.
13424 if (DiagID == 0) {
13426 return true;
13427 }
13428
13429 break;
13432 return true;
13435 return true;
13438 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13439 NeedType = true;
13440 break;
13442 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13443 NeedType = true;
13444 break;
13446 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13447 break;
13448 case Expr::MLV_Valid:
13449 llvm_unreachable("did not take early return for MLV_Valid");
13453 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13454 break;
13457 return S.RequireCompleteType(Loc, E->getType(),
13458 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13460 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13461 break;
13463 llvm_unreachable("readonly properties should be processed differently");
13465 DiagID = diag::err_readonly_message_assignment;
13466 break;
13468 DiagID = diag::err_no_subobject_property_setting;
13469 break;
13470 }
13471
13472 SourceRange Assign;
13473 if (Loc != OrigLoc)
13474 Assign = SourceRange(OrigLoc, OrigLoc);
13475 if (NeedType)
13476 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13477 else
13478 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13479 return true;
13480}
13481
13482static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13484 Sema &Sema) {
13486 return;
13488 return;
13489 if (Loc.isInvalid() || Loc.isMacroID())
13490 return;
13491 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13492 return;
13493
13494 // C / C++ fields
13495 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13496 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13497 if (ML && MR) {
13498 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13499 return;
13500 const ValueDecl *LHSDecl =
13501 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13502 const ValueDecl *RHSDecl =
13503 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13504 if (LHSDecl != RHSDecl)
13505 return;
13506 if (LHSDecl->getType().isVolatileQualified())
13507 return;
13508 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13509 if (RefTy->getPointeeType().isVolatileQualified())
13510 return;
13511
13512 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13513 }
13514
13515 // Objective-C instance variables
13516 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13517 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13518 if (OL && OR && OL->getDecl() == OR->getDecl()) {
13519 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13520 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13521 if (RL && RR && RL->getDecl() == RR->getDecl())
13522 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13523 }
13524}
13525
13526// C99 6.5.16.1
13529 QualType CompoundType,
13530 BinaryOperatorKind Opc) {
13531 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13532
13533 // Verify that LHS is a modifiable lvalue, and emit error if not.
13534 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13535 return QualType();
13536
13537 QualType LHSType = LHSExpr->getType();
13538 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13539 CompoundType;
13540 // OpenCL v1.2 s6.1.1.1 p2:
13541 // The half data type can only be used to declare a pointer to a buffer that
13542 // contains half values
13543 if (getLangOpts().OpenCL &&
13544 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13545 LHSType->isHalfType()) {
13546 Diag(Loc, diag::err_opencl_half_load_store) << 1
13547 << LHSType.getUnqualifiedType();
13548 return QualType();
13549 }
13550
13551 // WebAssembly tables can't be used on RHS of an assignment expression.
13552 if (RHSType->isWebAssemblyTableType()) {
13553 Diag(Loc, diag::err_wasm_table_art) << 0;
13554 return QualType();
13555 }
13556
13557 AssignConvertType ConvTy;
13558 if (CompoundType.isNull()) {
13559 Expr *RHSCheck = RHS.get();
13560
13561 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13562
13563 QualType LHSTy(LHSType);
13564 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13565 if (RHS.isInvalid())
13566 return QualType();
13567 // Special case of NSObject attributes on c-style pointer types.
13568 if (ConvTy == IncompatiblePointer &&
13569 ((Context.isObjCNSObjectType(LHSType) &&
13570 RHSType->isObjCObjectPointerType()) ||
13571 (Context.isObjCNSObjectType(RHSType) &&
13572 LHSType->isObjCObjectPointerType())))
13573 ConvTy = Compatible;
13574
13575 if (ConvTy == Compatible &&
13576 LHSType->isObjCObjectType())
13577 Diag(Loc, diag::err_objc_object_assignment)
13578 << LHSType;
13579
13580 // If the RHS is a unary plus or minus, check to see if they = and + are
13581 // right next to each other. If so, the user may have typo'd "x =+ 4"
13582 // instead of "x += 4".
13583 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13584 RHSCheck = ICE->getSubExpr();
13585 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13586 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13587 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13588 // Only if the two operators are exactly adjacent.
13589 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13590 // And there is a space or other character before the subexpr of the
13591 // unary +/-. We don't want to warn on "x=-1".
13592 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13593 UO->getSubExpr()->getBeginLoc().isFileID()) {
13594 Diag(Loc, diag::warn_not_compound_assign)
13595 << (UO->getOpcode() == UO_Plus ? "+" : "-")
13596 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13597 }
13598 }
13599
13600 if (ConvTy == Compatible) {
13601 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13602 // Warn about retain cycles where a block captures the LHS, but
13603 // not if the LHS is a simple variable into which the block is
13604 // being stored...unless that variable can be captured by reference!
13605 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13606 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13607 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13608 ObjC().checkRetainCycles(LHSExpr, RHS.get());
13609 }
13610
13611 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13613 // It is safe to assign a weak reference into a strong variable.
13614 // Although this code can still have problems:
13615 // id x = self.weakProp;
13616 // id y = self.weakProp;
13617 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13618 // paths through the function. This should be revisited if
13619 // -Wrepeated-use-of-weak is made flow-sensitive.
13620 // For ObjCWeak only, we do not warn if the assign is to a non-weak
13621 // variable, which will be valid for the current autorelease scope.
13622 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13623 RHS.get()->getBeginLoc()))
13625
13626 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13627 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13628 }
13629 }
13630 } else {
13631 // Compound assignment "x += y"
13632 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13633 }
13634
13635 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
13636 RHS.get(), AA_Assigning))
13637 return QualType();
13638
13639 CheckForNullPointerDereference(*this, LHSExpr);
13640
13641 AssignedEntity AE{LHSExpr};
13642 checkExprLifetime(*this, AE, RHS.get());
13643
13644 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13645 if (CompoundType.isNull()) {
13646 // C++2a [expr.ass]p5:
13647 // A simple-assignment whose left operand is of a volatile-qualified
13648 // type is deprecated unless the assignment is either a discarded-value
13649 // expression or an unevaluated operand
13650 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13651 }
13652 }
13653
13654 // C11 6.5.16p3: The type of an assignment expression is the type of the
13655 // left operand would have after lvalue conversion.
13656 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13657 // qualified type, the value has the unqualified version of the type of the
13658 // lvalue; additionally, if the lvalue has atomic type, the value has the
13659 // non-atomic version of the type of the lvalue.
13660 // C++ 5.17p1: the type of the assignment expression is that of its left
13661 // operand.
13662 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13663}
13664
13665// Scenarios to ignore if expression E is:
13666// 1. an explicit cast expression into void
13667// 2. a function call expression that returns void
13668static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
13669 E = E->IgnoreParens();
13670
13671 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13672 if (CE->getCastKind() == CK_ToVoid) {
13673 return true;
13674 }
13675
13676 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13677 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13678 CE->getSubExpr()->getType()->isDependentType()) {
13679 return true;
13680 }
13681 }
13682
13683 if (const auto *CE = dyn_cast<CallExpr>(E))
13684 return CE->getCallReturnType(Context)->isVoidType();
13685 return false;
13686}
13687
13689 // No warnings in macros
13690 if (Loc.isMacroID())
13691 return;
13692
13693 // Don't warn in template instantiations.
13695 return;
13696
13697 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13698 // instead, skip more than needed, then call back into here with the
13699 // CommaVisitor in SemaStmt.cpp.
13700 // The listed locations are the initialization and increment portions
13701 // of a for loop. The additional checks are on the condition of
13702 // if statements, do/while loops, and for loops.
13703 // Differences in scope flags for C89 mode requires the extra logic.
13704 const unsigned ForIncrementFlags =
13705 getLangOpts().C99 || getLangOpts().CPlusPlus
13708 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13709 const unsigned ScopeFlags = getCurScope()->getFlags();
13710 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13711 (ScopeFlags & ForInitFlags) == ForInitFlags)
13712 return;
13713
13714 // If there are multiple comma operators used together, get the RHS of the
13715 // of the comma operator as the LHS.
13716 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13717 if (BO->getOpcode() != BO_Comma)
13718 break;
13719 LHS = BO->getRHS();
13720 }
13721
13722 // Only allow some expressions on LHS to not warn.
13723 if (IgnoreCommaOperand(LHS, Context))
13724 return;
13725
13726 Diag(Loc, diag::warn_comma_operator);
13727 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13728 << LHS->getSourceRange()
13730 LangOpts.CPlusPlus ? "static_cast<void>("
13731 : "(void)(")
13733 ")");
13734}
13735
13736// C99 6.5.17
13739 LHS = S.CheckPlaceholderExpr(LHS.get());
13740 RHS = S.CheckPlaceholderExpr(RHS.get());
13741 if (LHS.isInvalid() || RHS.isInvalid())
13742 return QualType();
13743
13744 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13745 // operands, but not unary promotions.
13746 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13747
13748 // So we treat the LHS as a ignored value, and in C++ we allow the
13749 // containing site to determine what should be done with the RHS.
13750 LHS = S.IgnoredValueConversions(LHS.get());
13751 if (LHS.isInvalid())
13752 return QualType();
13753
13754 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13755
13756 if (!S.getLangOpts().CPlusPlus) {
13758 if (RHS.isInvalid())
13759 return QualType();
13760 if (!RHS.get()->getType()->isVoidType())
13761 S.RequireCompleteType(Loc, RHS.get()->getType(),
13762 diag::err_incomplete_type);
13763 }
13764
13765 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13766 S.DiagnoseCommaOperator(LHS.get(), Loc);
13767
13768 return RHS.get()->getType();
13769}
13770
13771/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13772/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13774 ExprValueKind &VK,
13775 ExprObjectKind &OK,
13776 SourceLocation OpLoc, bool IsInc,
13777 bool IsPrefix) {
13778 QualType ResType = Op->getType();
13779 // Atomic types can be used for increment / decrement where the non-atomic
13780 // versions can, so ignore the _Atomic() specifier for the purpose of
13781 // checking.
13782 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13783 ResType = ResAtomicType->getValueType();
13784
13785 assert(!ResType.isNull() && "no type for increment/decrement expression");
13786
13787 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13788 // Decrement of bool is not allowed.
13789 if (!IsInc) {
13790 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13791 return QualType();
13792 }
13793 // Increment of bool sets it to true, but is deprecated.
13794 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13795 : diag::warn_increment_bool)
13796 << Op->getSourceRange();
13797 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13798 // Error on enum increments and decrements in C++ mode
13799 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13800 return QualType();
13801 } else if (ResType->isRealType()) {
13802 // OK!
13803 } else if (ResType->isPointerType()) {
13804 // C99 6.5.2.4p2, 6.5.6p2
13805 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13806 return QualType();
13807 } else if (ResType->isObjCObjectPointerType()) {
13808 // On modern runtimes, ObjC pointer arithmetic is forbidden.
13809 // Otherwise, we just need a complete type.
13810 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
13811 checkArithmeticOnObjCPointer(S, OpLoc, Op))
13812 return QualType();
13813 } else if (ResType->isAnyComplexType()) {
13814 // C99 does not support ++/-- on complex types, we allow as an extension.
13815 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
13816 : diag::ext_c2y_increment_complex)
13817 << IsInc << Op->getSourceRange();
13818 } else if (ResType->isPlaceholderType()) {
13820 if (PR.isInvalid()) return QualType();
13821 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
13822 IsInc, IsPrefix);
13823 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
13824 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
13825 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
13826 (ResType->castAs<VectorType>()->getVectorKind() !=
13828 // The z vector extensions allow ++ and -- for non-bool vectors.
13829 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
13830 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
13831 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
13832 } else {
13833 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
13834 << ResType << int(IsInc) << Op->getSourceRange();
13835 return QualType();
13836 }
13837 // At this point, we know we have a real, complex or pointer type.
13838 // Now make sure the operand is a modifiable lvalue.
13839 if (CheckForModifiableLvalue(Op, OpLoc, S))
13840 return QualType();
13841 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
13842 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
13843 // An operand with volatile-qualified type is deprecated
13844 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
13845 << IsInc << ResType;
13846 }
13847 // In C++, a prefix increment is the same type as the operand. Otherwise
13848 // (in C or with postfix), the increment is the unqualified type of the
13849 // operand.
13850 if (IsPrefix && S.getLangOpts().CPlusPlus) {
13851 VK = VK_LValue;
13852 OK = Op->getObjectKind();
13853 return ResType;
13854 } else {
13855 VK = VK_PRValue;
13856 return ResType.getUnqualifiedType();
13857 }
13858}
13859
13860/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
13861/// This routine allows us to typecheck complex/recursive expressions
13862/// where the declaration is needed for type checking. We only need to
13863/// handle cases when the expression references a function designator
13864/// or is an lvalue. Here are some examples:
13865/// - &(x) => x
13866/// - &*****f => f for f a function designator.
13867/// - &s.xx => s
13868/// - &s.zz[1].yy -> s, if zz is an array
13869/// - *(x + 1) -> x, if x is an array
13870/// - &"123"[2] -> 0
13871/// - & __real__ x -> x
13872///
13873/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
13874/// members.
13876 switch (E->getStmtClass()) {
13877 case Stmt::DeclRefExprClass:
13878 return cast<DeclRefExpr>(E)->getDecl();
13879 case Stmt::MemberExprClass:
13880 // If this is an arrow operator, the address is an offset from
13881 // the base's value, so the object the base refers to is
13882 // irrelevant.
13883 if (cast<MemberExpr>(E)->isArrow())
13884 return nullptr;
13885 // Otherwise, the expression refers to a part of the base
13886 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
13887 case Stmt::ArraySubscriptExprClass: {
13888 // FIXME: This code shouldn't be necessary! We should catch the implicit
13889 // promotion of register arrays earlier.
13890 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
13891 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
13892 if (ICE->getSubExpr()->getType()->isArrayType())
13893 return getPrimaryDecl(ICE->getSubExpr());
13894 }
13895 return nullptr;
13896 }
13897 case Stmt::UnaryOperatorClass: {
13898 UnaryOperator *UO = cast<UnaryOperator>(E);
13899
13900 switch(UO->getOpcode()) {
13901 case UO_Real:
13902 case UO_Imag:
13903 case UO_Extension:
13904 return getPrimaryDecl(UO->getSubExpr());
13905 default:
13906 return nullptr;
13907 }
13908 }
13909 case Stmt::ParenExprClass:
13910 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
13911 case Stmt::ImplicitCastExprClass:
13912 // If the result of an implicit cast is an l-value, we care about
13913 // the sub-expression; otherwise, the result here doesn't matter.
13914 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
13915 case Stmt::CXXUuidofExprClass:
13916 return cast<CXXUuidofExpr>(E)->getGuidDecl();
13917 default:
13918 return nullptr;
13919 }
13920}
13921
13922namespace {
13923enum {
13924 AO_Bit_Field = 0,
13925 AO_Vector_Element = 1,
13926 AO_Property_Expansion = 2,
13927 AO_Register_Variable = 3,
13928 AO_Matrix_Element = 4,
13929 AO_No_Error = 5
13930};
13931}
13932/// Diagnose invalid operand for address of operations.
13933///
13934/// \param Type The type of operand which cannot have its address taken.
13936 Expr *E, unsigned Type) {
13937 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
13938}
13939
13941 const Expr *Op,
13942 const CXXMethodDecl *MD) {
13943 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
13944
13945 if (Op != DRE)
13946 return Diag(OpLoc, diag::err_parens_pointer_member_function)
13947 << Op->getSourceRange();
13948
13949 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
13950 if (isa<CXXDestructorDecl>(MD))
13951 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
13952 << DRE->getSourceRange();
13953
13954 if (DRE->getQualifier())
13955 return false;
13956
13957 if (MD->getParent()->getName().empty())
13958 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13959 << DRE->getSourceRange();
13960
13961 SmallString<32> Str;
13962 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
13963 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
13964 << DRE->getSourceRange()
13965 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
13966}
13967
13969 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
13970 if (PTy->getKind() == BuiltinType::Overload) {
13971 Expr *E = OrigOp.get()->IgnoreParens();
13972 if (!isa<OverloadExpr>(E)) {
13973 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
13974 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
13975 << OrigOp.get()->getSourceRange();
13976 return QualType();
13977 }
13978
13979 OverloadExpr *Ovl = cast<OverloadExpr>(E);
13980 if (isa<UnresolvedMemberExpr>(Ovl))
13982 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13983 << OrigOp.get()->getSourceRange();
13984 return QualType();
13985 }
13986
13987 return Context.OverloadTy;
13988 }
13989
13990 if (PTy->getKind() == BuiltinType::UnknownAny)
13991 return Context.UnknownAnyTy;
13992
13993 if (PTy->getKind() == BuiltinType::BoundMember) {
13994 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
13995 << OrigOp.get()->getSourceRange();
13996 return QualType();
13997 }
13998
13999 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14000 if (OrigOp.isInvalid()) return QualType();
14001 }
14002
14003 if (OrigOp.get()->isTypeDependent())
14004 return Context.DependentTy;
14005
14006 assert(!OrigOp.get()->hasPlaceholderType());
14007
14008 // Make sure to ignore parentheses in subsequent checks
14009 Expr *op = OrigOp.get()->IgnoreParens();
14010
14011 // In OpenCL captures for blocks called as lambda functions
14012 // are located in the private address space. Blocks used in
14013 // enqueue_kernel can be located in a different address space
14014 // depending on a vendor implementation. Thus preventing
14015 // taking an address of the capture to avoid invalid AS casts.
14016 if (LangOpts.OpenCL) {
14017 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14018 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14019 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14020 return QualType();
14021 }
14022 }
14023
14024 if (getLangOpts().C99) {
14025 // Implement C99-only parts of addressof rules.
14026 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14027 if (uOp->getOpcode() == UO_Deref)
14028 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14029 // (assuming the deref expression is valid).
14030 return uOp->getSubExpr()->getType();
14031 }
14032 // Technically, there should be a check for array subscript
14033 // expressions here, but the result of one is always an lvalue anyway.
14034 }
14035 ValueDecl *dcl = getPrimaryDecl(op);
14036
14037 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14038 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14039 op->getBeginLoc()))
14040 return QualType();
14041
14043 unsigned AddressOfError = AO_No_Error;
14044
14045 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14046 bool sfinae = (bool)isSFINAEContext();
14047 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14048 : diag::ext_typecheck_addrof_temporary)
14049 << op->getType() << op->getSourceRange();
14050 if (sfinae)
14051 return QualType();
14052 // Materialize the temporary as an lvalue so that we can take its address.
14053 OrigOp = op =
14054 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14055 } else if (isa<ObjCSelectorExpr>(op)) {
14056 return Context.getPointerType(op->getType());
14057 } else if (lval == Expr::LV_MemberFunction) {
14058 // If it's an instance method, make a member pointer.
14059 // The expression must have exactly the form &A::foo.
14060
14061 // If the underlying expression isn't a decl ref, give up.
14062 if (!isa<DeclRefExpr>(op)) {
14063 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14064 << OrigOp.get()->getSourceRange();
14065 return QualType();
14066 }
14067 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14068 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14069
14070 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14071
14074
14075 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14076 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14077 // When pointer authentication is enabled, argument and return types of
14078 // vitual member functions must be complete. This is because vitrual
14079 // member function pointers are implemented using virtual dispatch
14080 // thunks and the thunks cannot be emitted if the argument or return
14081 // types are incomplete.
14082 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14083 SourceLocation DeclRefLoc,
14084 SourceLocation RetArgTypeLoc) {
14085 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
14086 Diag(DeclRefLoc,
14087 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14088 Diag(RetArgTypeLoc,
14089 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14090 << T;
14091 return true;
14092 }
14093 return false;
14094 };
14095 QualType RetTy = MD->getReturnType();
14096 bool IsIncomplete =
14097 !RetTy->isVoidType() &&
14098 ReturnOrParamTypeIsIncomplete(
14099 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14100 for (auto *PVD : MD->parameters())
14101 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14102 PVD->getBeginLoc());
14103 if (IsIncomplete)
14104 return QualType();
14105 }
14106
14107 // Under the MS ABI, lock down the inheritance model now.
14109 (void)isCompleteType(OpLoc, MPTy);
14110 return MPTy;
14111 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14112 // C99 6.5.3.2p1
14113 // The operand must be either an l-value or a function designator
14114 if (!op->getType()->isFunctionType()) {
14115 // Use a special diagnostic for loads from property references.
14116 if (isa<PseudoObjectExpr>(op)) {
14117 AddressOfError = AO_Property_Expansion;
14118 } else {
14119 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14120 << op->getType() << op->getSourceRange();
14121 return QualType();
14122 }
14123 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14124 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14125 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14126 }
14127
14128 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14129 // The operand cannot be a bit-field
14130 AddressOfError = AO_Bit_Field;
14131 } else if (op->getObjectKind() == OK_VectorComponent) {
14132 // The operand cannot be an element of a vector
14133 AddressOfError = AO_Vector_Element;
14134 } else if (op->getObjectKind() == OK_MatrixComponent) {
14135 // The operand cannot be an element of a matrix.
14136 AddressOfError = AO_Matrix_Element;
14137 } else if (dcl) { // C99 6.5.3.2p1
14138 // We have an lvalue with a decl. Make sure the decl is not declared
14139 // with the register storage-class specifier.
14140 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14141 // in C++ it is not error to take address of a register
14142 // variable (c++03 7.1.1P3)
14143 if (vd->getStorageClass() == SC_Register &&
14145 AddressOfError = AO_Register_Variable;
14146 }
14147 } else if (isa<MSPropertyDecl>(dcl)) {
14148 AddressOfError = AO_Property_Expansion;
14149 } else if (isa<FunctionTemplateDecl>(dcl)) {
14150 return Context.OverloadTy;
14151 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14152 // Okay: we can take the address of a field.
14153 // Could be a pointer to member, though, if there is an explicit
14154 // scope qualifier for the class.
14155
14156 // [C++26] [expr.prim.id.general]
14157 // If an id-expression E denotes a non-static non-type member
14158 // of some class C [...] and if E is a qualified-id, E is
14159 // not the un-parenthesized operand of the unary & operator [...]
14160 // the id-expression is transformed into a class member access expression.
14161 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
14162 !isa<ParenExpr>(OrigOp.get())) {
14163 DeclContext *Ctx = dcl->getDeclContext();
14164 if (Ctx && Ctx->isRecord()) {
14165 if (dcl->getType()->isReferenceType()) {
14166 Diag(OpLoc,
14167 diag::err_cannot_form_pointer_to_member_of_reference_type)
14168 << dcl->getDeclName() << dcl->getType();
14169 return QualType();
14170 }
14171
14172 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14173 Ctx = Ctx->getParent();
14174
14176 op->getType(),
14177 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14178 // Under the MS ABI, lock down the inheritance model now.
14180 (void)isCompleteType(OpLoc, MPTy);
14181 return MPTy;
14182 }
14183 }
14186 llvm_unreachable("Unknown/unexpected decl type");
14187 }
14188
14189 if (AddressOfError != AO_No_Error) {
14190 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14191 return QualType();
14192 }
14193
14194 if (lval == Expr::LV_IncompleteVoidType) {
14195 // Taking the address of a void variable is technically illegal, but we
14196 // allow it in cases which are otherwise valid.
14197 // Example: "extern void x; void* y = &x;".
14198 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14199 }
14200
14201 // If the operand has type "type", the result has type "pointer to type".
14202 if (op->getType()->isObjCObjectType())
14204
14205 // Cannot take the address of WebAssembly references or tables.
14206 if (Context.getTargetInfo().getTriple().isWasm()) {
14207 QualType OpTy = op->getType();
14208 if (OpTy.isWebAssemblyReferenceType()) {
14209 Diag(OpLoc, diag::err_wasm_ca_reference)
14210 << 1 << OrigOp.get()->getSourceRange();
14211 return QualType();
14212 }
14213 if (OpTy->isWebAssemblyTableType()) {
14214 Diag(OpLoc, diag::err_wasm_table_pr)
14215 << 1 << OrigOp.get()->getSourceRange();
14216 return QualType();
14217 }
14218 }
14219
14220 CheckAddressOfPackedMember(op);
14221
14222 return Context.getPointerType(op->getType());
14223}
14224
14225static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14226 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14227 if (!DRE)
14228 return;
14229 const Decl *D = DRE->getDecl();
14230 if (!D)
14231 return;
14232 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14233 if (!Param)
14234 return;
14235 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14236 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14237 return;
14238 if (FunctionScopeInfo *FD = S.getCurFunction())
14239 FD->ModifiedNonNullParams.insert(Param);
14240}
14241
14242/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14244 SourceLocation OpLoc,
14245 bool IsAfterAmp = false) {
14246 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14247 if (ConvResult.isInvalid())
14248 return QualType();
14249 Op = ConvResult.get();
14250 QualType OpTy = Op->getType();
14252
14253 if (isa<CXXReinterpretCastExpr>(Op)) {
14254 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14255 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14256 Op->getSourceRange());
14257 }
14258
14259 if (const PointerType *PT = OpTy->getAs<PointerType>())
14260 {
14261 Result = PT->getPointeeType();
14262 }
14263 else if (const ObjCObjectPointerType *OPT =
14265 Result = OPT->getPointeeType();
14266 else {
14268 if (PR.isInvalid()) return QualType();
14269 if (PR.get() != Op)
14270 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14271 }
14272
14273 if (Result.isNull()) {
14274 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14275 << OpTy << Op->getSourceRange();
14276 return QualType();
14277 }
14278
14279 if (Result->isVoidType()) {
14280 // C++ [expr.unary.op]p1:
14281 // [...] the expression to which [the unary * operator] is applied shall
14282 // be a pointer to an object type, or a pointer to a function type
14283 LangOptions LO = S.getLangOpts();
14284 if (LO.CPlusPlus)
14285 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14286 << OpTy << Op->getSourceRange();
14287 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14288 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14289 << OpTy << Op->getSourceRange();
14290 }
14291
14292 // Dereferences are usually l-values...
14293 VK = VK_LValue;
14294
14295 // ...except that certain expressions are never l-values in C.
14296 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14297 VK = VK_PRValue;
14298
14299 return Result;
14300}
14301
14302BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14304 switch (Kind) {
14305 default: llvm_unreachable("Unknown binop!");
14306 case tok::periodstar: Opc = BO_PtrMemD; break;
14307 case tok::arrowstar: Opc = BO_PtrMemI; break;
14308 case tok::star: Opc = BO_Mul; break;
14309 case tok::slash: Opc = BO_Div; break;
14310 case tok::percent: Opc = BO_Rem; break;
14311 case tok::plus: Opc = BO_Add; break;
14312 case tok::minus: Opc = BO_Sub; break;
14313 case tok::lessless: Opc = BO_Shl; break;
14314 case tok::greatergreater: Opc = BO_Shr; break;
14315 case tok::lessequal: Opc = BO_LE; break;
14316 case tok::less: Opc = BO_LT; break;
14317 case tok::greaterequal: Opc = BO_GE; break;
14318 case tok::greater: Opc = BO_GT; break;
14319 case tok::exclaimequal: Opc = BO_NE; break;
14320 case tok::equalequal: Opc = BO_EQ; break;
14321 case tok::spaceship: Opc = BO_Cmp; break;
14322 case tok::amp: Opc = BO_And; break;
14323 case tok::caret: Opc = BO_Xor; break;
14324 case tok::pipe: Opc = BO_Or; break;
14325 case tok::ampamp: Opc = BO_LAnd; break;
14326 case tok::pipepipe: Opc = BO_LOr; break;
14327 case tok::equal: Opc = BO_Assign; break;
14328 case tok::starequal: Opc = BO_MulAssign; break;
14329 case tok::slashequal: Opc = BO_DivAssign; break;
14330 case tok::percentequal: Opc = BO_RemAssign; break;
14331 case tok::plusequal: Opc = BO_AddAssign; break;
14332 case tok::minusequal: Opc = BO_SubAssign; break;
14333 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14334 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14335 case tok::ampequal: Opc = BO_AndAssign; break;
14336 case tok::caretequal: Opc = BO_XorAssign; break;
14337 case tok::pipeequal: Opc = BO_OrAssign; break;
14338 case tok::comma: Opc = BO_Comma; break;
14339 }
14340 return Opc;
14341}
14342
14344 tok::TokenKind Kind) {
14346 switch (Kind) {
14347 default: llvm_unreachable("Unknown unary op!");
14348 case tok::plusplus: Opc = UO_PreInc; break;
14349 case tok::minusminus: Opc = UO_PreDec; break;
14350 case tok::amp: Opc = UO_AddrOf; break;
14351 case tok::star: Opc = UO_Deref; break;
14352 case tok::plus: Opc = UO_Plus; break;
14353 case tok::minus: Opc = UO_Minus; break;
14354 case tok::tilde: Opc = UO_Not; break;
14355 case tok::exclaim: Opc = UO_LNot; break;
14356 case tok::kw___real: Opc = UO_Real; break;
14357 case tok::kw___imag: Opc = UO_Imag; break;
14358 case tok::kw___extension__: Opc = UO_Extension; break;
14359 }
14360 return Opc;
14361}
14362
14363const FieldDecl *
14365 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14366 // common for setters.
14367 // struct A {
14368 // int X;
14369 // -void setX(int X) { X = X; }
14370 // +void setX(int X) { this->X = X; }
14371 // };
14372
14373 // Only consider parameters for self assignment fixes.
14374 if (!isa<ParmVarDecl>(SelfAssigned))
14375 return nullptr;
14376 const auto *Method =
14377 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14378 if (!Method)
14379 return nullptr;
14380
14381 const CXXRecordDecl *Parent = Method->getParent();
14382 // In theory this is fixable if the lambda explicitly captures this, but
14383 // that's added complexity that's rarely going to be used.
14384 if (Parent->isLambda())
14385 return nullptr;
14386
14387 // FIXME: Use an actual Lookup operation instead of just traversing fields
14388 // in order to get base class fields.
14389 auto Field =
14390 llvm::find_if(Parent->fields(),
14391 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14392 return F->getDeclName() == Name;
14393 });
14394 return (Field != Parent->field_end()) ? *Field : nullptr;
14395}
14396
14397/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14398/// This warning suppressed in the event of macro expansions.
14399static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14400 SourceLocation OpLoc, bool IsBuiltin) {
14402 return;
14403 if (S.isUnevaluatedContext())
14404 return;
14405 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14406 return;
14407 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14408 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14409 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14410 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14411 if (!LHSDeclRef || !RHSDeclRef ||
14412 LHSDeclRef->getLocation().isMacroID() ||
14413 RHSDeclRef->getLocation().isMacroID())
14414 return;
14415 const ValueDecl *LHSDecl =
14416 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14417 const ValueDecl *RHSDecl =
14418 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14419 if (LHSDecl != RHSDecl)
14420 return;
14421 if (LHSDecl->getType().isVolatileQualified())
14422 return;
14423 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14424 if (RefTy->getPointeeType().isVolatileQualified())
14425 return;
14426
14427 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14428 : diag::warn_self_assignment_overloaded)
14429 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14430 << RHSExpr->getSourceRange();
14431 if (const FieldDecl *SelfAssignField =
14433 Diag << 1 << SelfAssignField
14434 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14435 else
14436 Diag << 0;
14437}
14438
14439/// Check if a bitwise-& is performed on an Objective-C pointer. This
14440/// is usually indicative of introspection within the Objective-C pointer.
14442 SourceLocation OpLoc) {
14443 if (!S.getLangOpts().ObjC)
14444 return;
14445
14446 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14447 const Expr *LHS = L.get();
14448 const Expr *RHS = R.get();
14449
14451 ObjCPointerExpr = LHS;
14452 OtherExpr = RHS;
14453 }
14454 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14455 ObjCPointerExpr = RHS;
14456 OtherExpr = LHS;
14457 }
14458
14459 // This warning is deliberately made very specific to reduce false
14460 // positives with logic that uses '&' for hashing. This logic mainly
14461 // looks for code trying to introspect into tagged pointers, which
14462 // code should generally never do.
14463 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14464 unsigned Diag = diag::warn_objc_pointer_masking;
14465 // Determine if we are introspecting the result of performSelectorXXX.
14466 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14467 // Special case messages to -performSelector and friends, which
14468 // can return non-pointer values boxed in a pointer value.
14469 // Some clients may wish to silence warnings in this subcase.
14470 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14471 Selector S = ME->getSelector();
14472 StringRef SelArg0 = S.getNameForSlot(0);
14473 if (SelArg0.starts_with("performSelector"))
14474 Diag = diag::warn_objc_pointer_masking_performSelector;
14475 }
14476
14477 S.Diag(OpLoc, Diag)
14478 << ObjCPointerExpr->getSourceRange();
14479 }
14480}
14481
14483 if (!E)
14484 return nullptr;
14485 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14486 return DRE->getDecl();
14487 if (auto *ME = dyn_cast<MemberExpr>(E))
14488 return ME->getMemberDecl();
14489 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14490 return IRE->getDecl();
14491 return nullptr;
14492}
14493
14494// This helper function promotes a binary operator's operands (which are of a
14495// half vector type) to a vector of floats and then truncates the result to
14496// a vector of either half or short.
14498 BinaryOperatorKind Opc, QualType ResultTy,
14500 bool IsCompAssign, SourceLocation OpLoc,
14501 FPOptionsOverride FPFeatures) {
14502 auto &Context = S.getASTContext();
14503 assert((isVector(ResultTy, Context.HalfTy) ||
14504 isVector(ResultTy, Context.ShortTy)) &&
14505 "Result must be a vector of half or short");
14506 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14507 isVector(RHS.get()->getType(), Context.HalfTy) &&
14508 "both operands expected to be a half vector");
14509
14510 RHS = convertVector(RHS.get(), Context.FloatTy, S);
14511 QualType BinOpResTy = RHS.get()->getType();
14512
14513 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14514 // change BinOpResTy to a vector of ints.
14515 if (isVector(ResultTy, Context.ShortTy))
14516 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14517
14518 if (IsCompAssign)
14519 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14520 ResultTy, VK, OK, OpLoc, FPFeatures,
14521 BinOpResTy, BinOpResTy);
14522
14523 LHS = convertVector(LHS.get(), Context.FloatTy, S);
14524 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14525 BinOpResTy, VK, OK, OpLoc, FPFeatures);
14526 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14527}
14528
14529static std::pair<ExprResult, ExprResult>
14531 Expr *RHSExpr) {
14532 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14533 if (!S.Context.isDependenceAllowed()) {
14534 // C cannot handle TypoExpr nodes on either side of a binop because it
14535 // doesn't handle dependent types properly, so make sure any TypoExprs have
14536 // been dealt with before checking the operands.
14537 LHS = S.CorrectDelayedTyposInExpr(LHS);
14539 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14540 [Opc, LHS](Expr *E) {
14541 if (Opc != BO_Assign)
14542 return ExprResult(E);
14543 // Avoid correcting the RHS to the same Expr as the LHS.
14544 Decl *D = getDeclFromExpr(E);
14545 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14546 });
14547 }
14548 return std::make_pair(LHS, RHS);
14549}
14550
14551/// Returns true if conversion between vectors of halfs and vectors of floats
14552/// is needed.
14553static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14554 Expr *E0, Expr *E1 = nullptr) {
14555 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14557 return false;
14558
14559 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14560 QualType Ty = E->IgnoreImplicit()->getType();
14561
14562 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14563 // to vectors of floats. Although the element type of the vectors is __fp16,
14564 // the vectors shouldn't be treated as storage-only types. See the
14565 // discussion here: https://reviews.llvm.org/rG825235c140e7
14566 if (const VectorType *VT = Ty->getAs<VectorType>()) {
14567 if (VT->getVectorKind() == VectorKind::Neon)
14568 return false;
14569 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14570 }
14571 return false;
14572 };
14573
14574 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14575}
14576
14579 Expr *LHSExpr, Expr *RHSExpr) {
14580 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14581 // The syntax only allows initializer lists on the RHS of assignment,
14582 // so we don't need to worry about accepting invalid code for
14583 // non-assignment operators.
14584 // C++11 5.17p9:
14585 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14586 // of x = {} is x = T().
14588 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14589 InitializedEntity Entity =
14591 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14592 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14593 if (Init.isInvalid())
14594 return Init;
14595 RHSExpr = Init.get();
14596 }
14597
14598 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14599 QualType ResultTy; // Result type of the binary operator.
14600 // The following two variables are used for compound assignment operators
14601 QualType CompLHSTy; // Type of LHS after promotions for computation
14602 QualType CompResultTy; // Type of computation result
14605 bool ConvertHalfVec = false;
14606
14607 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14608 if (!LHS.isUsable() || !RHS.isUsable())
14609 return ExprError();
14610
14611 if (getLangOpts().OpenCL) {
14612 QualType LHSTy = LHSExpr->getType();
14613 QualType RHSTy = RHSExpr->getType();
14614 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14615 // the ATOMIC_VAR_INIT macro.
14616 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14617 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14618 if (BO_Assign == Opc)
14619 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14620 else
14621 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14622 return ExprError();
14623 }
14624
14625 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14626 // only with a builtin functions and therefore should be disallowed here.
14627 if (LHSTy->isImageType() || RHSTy->isImageType() ||
14628 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14629 LHSTy->isPipeType() || RHSTy->isPipeType() ||
14630 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14631 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14632 return ExprError();
14633 }
14634 }
14635
14636 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14637 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14638
14639 switch (Opc) {
14640 case BO_Assign:
14641 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
14642 if (getLangOpts().CPlusPlus &&
14643 LHS.get()->getObjectKind() != OK_ObjCProperty) {
14644 VK = LHS.get()->getValueKind();
14645 OK = LHS.get()->getObjectKind();
14646 }
14647 if (!ResultTy.isNull()) {
14648 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14649 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14650
14651 // Avoid copying a block to the heap if the block is assigned to a local
14652 // auto variable that is declared in the same scope as the block. This
14653 // optimization is unsafe if the local variable is declared in an outer
14654 // scope. For example:
14655 //
14656 // BlockTy b;
14657 // {
14658 // b = ^{...};
14659 // }
14660 // // It is unsafe to invoke the block here if it wasn't copied to the
14661 // // heap.
14662 // b();
14663
14664 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14665 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14666 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14667 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14668 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14669
14671 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14673 }
14674 RecordModifiableNonNullParam(*this, LHS.get());
14675 break;
14676 case BO_PtrMemD:
14677 case BO_PtrMemI:
14678 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14679 Opc == BO_PtrMemI);
14680 break;
14681 case BO_Mul:
14682 case BO_Div:
14683 ConvertHalfVec = true;
14684 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14685 Opc == BO_Div);
14686 break;
14687 case BO_Rem:
14688 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14689 break;
14690 case BO_Add:
14691 ConvertHalfVec = true;
14692 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14693 break;
14694 case BO_Sub:
14695 ConvertHalfVec = true;
14696 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14697 break;
14698 case BO_Shl:
14699 case BO_Shr:
14700 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14701 break;
14702 case BO_LE:
14703 case BO_LT:
14704 case BO_GE:
14705 case BO_GT:
14706 ConvertHalfVec = true;
14707 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14708
14709 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
14710 BI && BI->isComparisonOp())
14711 Diag(OpLoc, diag::warn_consecutive_comparison);
14712
14713 break;
14714 case BO_EQ:
14715 case BO_NE:
14716 ConvertHalfVec = true;
14717 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14718 break;
14719 case BO_Cmp:
14720 ConvertHalfVec = true;
14721 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14722 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14723 break;
14724 case BO_And:
14725 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14726 [[fallthrough]];
14727 case BO_Xor:
14728 case BO_Or:
14729 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14730 break;
14731 case BO_LAnd:
14732 case BO_LOr:
14733 ConvertHalfVec = true;
14734 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14735 break;
14736 case BO_MulAssign:
14737 case BO_DivAssign:
14738 ConvertHalfVec = true;
14739 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14740 Opc == BO_DivAssign);
14741 CompLHSTy = CompResultTy;
14742 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14743 ResultTy =
14744 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14745 break;
14746 case BO_RemAssign:
14747 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14748 CompLHSTy = CompResultTy;
14749 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14750 ResultTy =
14751 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14752 break;
14753 case BO_AddAssign:
14754 ConvertHalfVec = true;
14755 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14756 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14757 ResultTy =
14758 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14759 break;
14760 case BO_SubAssign:
14761 ConvertHalfVec = true;
14762 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14763 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14764 ResultTy =
14765 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14766 break;
14767 case BO_ShlAssign:
14768 case BO_ShrAssign:
14769 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, 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_AndAssign:
14776 case BO_OrAssign: // fallthrough
14777 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14778 [[fallthrough]];
14779 case BO_XorAssign:
14780 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14781 CompLHSTy = CompResultTy;
14782 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14783 ResultTy =
14784 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14785 break;
14786 case BO_Comma:
14787 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14788 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14789 VK = RHS.get()->getValueKind();
14790 OK = RHS.get()->getObjectKind();
14791 }
14792 break;
14793 }
14794 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14795 return ExprError();
14796
14797 // Some of the binary operations require promoting operands of half vector to
14798 // float vectors and truncating the result back to half vector. For now, we do
14799 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14800 // arm64).
14801 assert(
14802 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14803 isVector(LHS.get()->getType(), Context.HalfTy)) &&
14804 "both sides are half vectors or neither sides are");
14805 ConvertHalfVec =
14806 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14807
14808 // Check for array bounds violations for both sides of the BinaryOperator
14809 CheckArrayAccess(LHS.get());
14810 CheckArrayAccess(RHS.get());
14811
14812 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
14813 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
14814 &Context.Idents.get("object_setClass"),
14816 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
14817 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
14818 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
14820 "object_setClass(")
14821 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
14822 ",")
14823 << FixItHint::CreateInsertion(RHSLocEnd, ")");
14824 }
14825 else
14826 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
14827 }
14828 else if (const ObjCIvarRefExpr *OIRE =
14829 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
14830 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
14831
14832 // Opc is not a compound assignment if CompResultTy is null.
14833 if (CompResultTy.isNull()) {
14834 if (ConvertHalfVec)
14835 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
14836 OpLoc, CurFPFeatureOverrides());
14837 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
14838 VK, OK, OpLoc, CurFPFeatureOverrides());
14839 }
14840
14841 // Handle compound assignments.
14842 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
14844 VK = VK_LValue;
14845 OK = LHS.get()->getObjectKind();
14846 }
14847
14848 // The LHS is not converted to the result type for fixed-point compound
14849 // assignment as the common type is computed on demand. Reset the CompLHSTy
14850 // to the LHS type we would have gotten after unary conversions.
14851 if (CompResultTy->isFixedPointType())
14852 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
14853
14854 if (ConvertHalfVec)
14855 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
14856 OpLoc, CurFPFeatureOverrides());
14857
14859 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
14860 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
14861}
14862
14863/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
14864/// operators are mixed in a way that suggests that the programmer forgot that
14865/// comparison operators have higher precedence. The most typical example of
14866/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
14868 SourceLocation OpLoc, Expr *LHSExpr,
14869 Expr *RHSExpr) {
14870 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
14871 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
14872
14873 // Check that one of the sides is a comparison operator and the other isn't.
14874 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
14875 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
14876 if (isLeftComp == isRightComp)
14877 return;
14878
14879 // Bitwise operations are sometimes used as eager logical ops.
14880 // Don't diagnose this.
14881 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
14882 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
14883 if (isLeftBitwise || isRightBitwise)
14884 return;
14885
14886 SourceRange DiagRange = isLeftComp
14887 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
14888 : SourceRange(OpLoc, RHSExpr->getEndLoc());
14889 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
14890 SourceRange ParensRange =
14891 isLeftComp
14892 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
14893 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
14894
14895 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
14896 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
14897 SuggestParentheses(Self, OpLoc,
14898 Self.PDiag(diag::note_precedence_silence) << OpStr,
14899 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
14900 SuggestParentheses(Self, OpLoc,
14901 Self.PDiag(diag::note_precedence_bitwise_first)
14903 ParensRange);
14904}
14905
14906/// It accepts a '&&' expr that is inside a '||' one.
14907/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
14908/// in parentheses.
14909static void
14911 BinaryOperator *Bop) {
14912 assert(Bop->getOpcode() == BO_LAnd);
14913 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
14914 << Bop->getSourceRange() << OpLoc;
14916 Self.PDiag(diag::note_precedence_silence)
14917 << Bop->getOpcodeStr(),
14918 Bop->getSourceRange());
14919}
14920
14921/// Look for '&&' in the left hand of a '||' expr.
14923 Expr *LHSExpr, Expr *RHSExpr) {
14924 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
14925 if (Bop->getOpcode() == BO_LAnd) {
14926 // If it's "string_literal && a || b" don't warn since the precedence
14927 // doesn't matter.
14928 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
14929 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14930 } else if (Bop->getOpcode() == BO_LOr) {
14931 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
14932 // If it's "a || b && string_literal || c" we didn't warn earlier for
14933 // "a || b && string_literal", but warn now.
14934 if (RBop->getOpcode() == BO_LAnd &&
14935 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
14936 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
14937 }
14938 }
14939 }
14940}
14941
14942/// Look for '&&' in the right hand of a '||' expr.
14944 Expr *LHSExpr, Expr *RHSExpr) {
14945 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
14946 if (Bop->getOpcode() == BO_LAnd) {
14947 // If it's "a || b && string_literal" don't warn since the precedence
14948 // doesn't matter.
14949 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
14950 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
14951 }
14952 }
14953}
14954
14955/// Look for bitwise op in the left or right hand of a bitwise op with
14956/// lower precedence and emit a diagnostic together with a fixit hint that wraps
14957/// the '&' expression in parentheses.
14959 SourceLocation OpLoc, Expr *SubExpr) {
14960 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14961 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
14962 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
14963 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
14964 << Bop->getSourceRange() << OpLoc;
14965 SuggestParentheses(S, Bop->getOperatorLoc(),
14966 S.PDiag(diag::note_precedence_silence)
14967 << Bop->getOpcodeStr(),
14968 Bop->getSourceRange());
14969 }
14970 }
14971}
14972
14974 Expr *SubExpr, StringRef Shift) {
14975 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
14976 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
14977 StringRef Op = Bop->getOpcodeStr();
14978 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
14979 << Bop->getSourceRange() << OpLoc << Shift << Op;
14980 SuggestParentheses(S, Bop->getOperatorLoc(),
14981 S.PDiag(diag::note_precedence_silence) << Op,
14982 Bop->getSourceRange());
14983 }
14984 }
14985}
14986
14988 Expr *LHSExpr, Expr *RHSExpr) {
14989 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
14990 if (!OCE)
14991 return;
14992
14993 FunctionDecl *FD = OCE->getDirectCallee();
14994 if (!FD || !FD->isOverloadedOperator())
14995 return;
14996
14998 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
14999 return;
15000
15001 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15002 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15003 << (Kind == OO_LessLess);
15005 S.PDiag(diag::note_precedence_silence)
15006 << (Kind == OO_LessLess ? "<<" : ">>"),
15007 OCE->getSourceRange());
15009 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15010 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15011}
15012
15013/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15014/// precedence.
15016 SourceLocation OpLoc, Expr *LHSExpr,
15017 Expr *RHSExpr){
15018 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15020 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15021
15022 // Diagnose "arg1 & arg2 | arg3"
15023 if ((Opc == BO_Or || Opc == BO_Xor) &&
15024 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15025 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15026 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15027 }
15028
15029 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15030 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15031 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15032 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15033 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15034 }
15035
15036 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15037 || Opc == BO_Shr) {
15038 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15039 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15040 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15041 }
15042
15043 // Warn on overloaded shift operators and comparisons, such as:
15044 // cout << 5 == 4;
15046 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15047}
15048
15050 tok::TokenKind Kind,
15051 Expr *LHSExpr, Expr *RHSExpr) {
15052 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15053 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15054 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15055
15056 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15057 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15058
15059 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15060}
15061
15063 UnresolvedSetImpl &Functions) {
15065 if (OverOp != OO_None && OverOp != OO_Equal)
15066 LookupOverloadedOperatorName(OverOp, S, Functions);
15067
15068 // In C++20 onwards, we may have a second operator to look up.
15069 if (getLangOpts().CPlusPlus20) {
15071 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15072 }
15073}
15074
15075/// Build an overloaded binary operator expression in the given scope.
15078 Expr *LHS, Expr *RHS) {
15079 switch (Opc) {
15080 case BO_Assign:
15081 // In the non-overloaded case, we warn about self-assignment (x = x) for
15082 // both simple assignment and certain compound assignments where algebra
15083 // tells us the operation yields a constant result. When the operator is
15084 // overloaded, we can't do the latter because we don't want to assume that
15085 // those algebraic identities still apply; for example, a path-building
15086 // library might use operator/= to append paths. But it's still reasonable
15087 // to assume that simple assignment is just moving/copying values around
15088 // and so self-assignment is likely a bug.
15089 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15090 [[fallthrough]];
15091 case BO_DivAssign:
15092 case BO_RemAssign:
15093 case BO_SubAssign:
15094 case BO_AndAssign:
15095 case BO_OrAssign:
15096 case BO_XorAssign:
15097 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15098 break;
15099 default:
15100 break;
15101 }
15102
15103 // Find all of the overloaded operators visible from this point.
15104 UnresolvedSet<16> Functions;
15105 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15106
15107 // Build the (potentially-overloaded, potentially-dependent)
15108 // binary operation.
15109 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15110}
15111
15114 Expr *LHSExpr, Expr *RHSExpr) {
15115 ExprResult LHS, RHS;
15116 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15117 if (!LHS.isUsable() || !RHS.isUsable())
15118 return ExprError();
15119 LHSExpr = LHS.get();
15120 RHSExpr = RHS.get();
15121
15122 // We want to end up calling one of SemaPseudoObject::checkAssignment
15123 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15124 // both expressions are overloadable or either is type-dependent),
15125 // or CreateBuiltinBinOp (in any other case). We also want to get
15126 // any placeholder types out of the way.
15127
15128 // Handle pseudo-objects in the LHS.
15129 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15130 // Assignments with a pseudo-object l-value need special analysis.
15131 if (pty->getKind() == BuiltinType::PseudoObject &&
15133 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15134
15135 // Don't resolve overloads if the other type is overloadable.
15136 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15137 // We can't actually test that if we still have a placeholder,
15138 // though. Fortunately, none of the exceptions we see in that
15139 // code below are valid when the LHS is an overload set. Note
15140 // that an overload set can be dependently-typed, but it never
15141 // instantiates to having an overloadable type.
15142 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15143 if (resolvedRHS.isInvalid()) return ExprError();
15144 RHSExpr = resolvedRHS.get();
15145
15146 if (RHSExpr->isTypeDependent() ||
15147 RHSExpr->getType()->isOverloadableType())
15148 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15149 }
15150
15151 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15152 // template, diagnose the missing 'template' keyword instead of diagnosing
15153 // an invalid use of a bound member function.
15154 //
15155 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15156 // to C++1z [over.over]/1.4, but we already checked for that case above.
15157 if (Opc == BO_LT && inTemplateInstantiation() &&
15158 (pty->getKind() == BuiltinType::BoundMember ||
15159 pty->getKind() == BuiltinType::Overload)) {
15160 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15161 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15162 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15163 return isa<FunctionTemplateDecl>(ND);
15164 })) {
15165 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15166 : OE->getNameLoc(),
15167 diag::err_template_kw_missing)
15168 << OE->getName().getAsString() << "";
15169 return ExprError();
15170 }
15171 }
15172
15173 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15174 if (LHS.isInvalid()) return ExprError();
15175 LHSExpr = LHS.get();
15176 }
15177
15178 // Handle pseudo-objects in the RHS.
15179 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15180 // An overload in the RHS can potentially be resolved by the type
15181 // being assigned to.
15182 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15183 if (getLangOpts().CPlusPlus &&
15184 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15185 LHSExpr->getType()->isOverloadableType()))
15186 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15187
15188 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15189 }
15190
15191 // Don't resolve overloads if the other type is overloadable.
15192 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15193 LHSExpr->getType()->isOverloadableType())
15194 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15195
15196 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15197 if (!resolvedRHS.isUsable()) return ExprError();
15198 RHSExpr = resolvedRHS.get();
15199 }
15200
15201 if (getLangOpts().CPlusPlus) {
15202 // Otherwise, build an overloaded op if either expression is type-dependent
15203 // or has an overloadable type.
15204 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15205 LHSExpr->getType()->isOverloadableType() ||
15206 RHSExpr->getType()->isOverloadableType())
15207 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15208 }
15209
15210 if (getLangOpts().RecoveryAST &&
15211 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15212 assert(!getLangOpts().CPlusPlus);
15213 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15214 "Should only occur in error-recovery path.");
15216 // C [6.15.16] p3:
15217 // An assignment expression has the value of the left operand after the
15218 // assignment, but is not an lvalue.
15220 Context, LHSExpr, RHSExpr, Opc,
15222 OpLoc, CurFPFeatureOverrides());
15223 QualType ResultType;
15224 switch (Opc) {
15225 case BO_Assign:
15226 ResultType = LHSExpr->getType().getUnqualifiedType();
15227 break;
15228 case BO_LT:
15229 case BO_GT:
15230 case BO_LE:
15231 case BO_GE:
15232 case BO_EQ:
15233 case BO_NE:
15234 case BO_LAnd:
15235 case BO_LOr:
15236 // These operators have a fixed result type regardless of operands.
15237 ResultType = Context.IntTy;
15238 break;
15239 case BO_Comma:
15240 ResultType = RHSExpr->getType();
15241 break;
15242 default:
15243 ResultType = Context.DependentTy;
15244 break;
15245 }
15246 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15247 VK_PRValue, OK_Ordinary, OpLoc,
15249 }
15250
15251 // Build a built-in binary operation.
15252 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15253}
15254
15256 if (T.isNull() || T->isDependentType())
15257 return false;
15258
15259 if (!Ctx.isPromotableIntegerType(T))
15260 return true;
15261
15262 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15263}
15264
15266 UnaryOperatorKind Opc, Expr *InputExpr,
15267 bool IsAfterAmp) {
15268 ExprResult Input = InputExpr;
15271 QualType resultType;
15272 bool CanOverflow = false;
15273
15274 bool ConvertHalfVec = false;
15275 if (getLangOpts().OpenCL) {
15276 QualType Ty = InputExpr->getType();
15277 // The only legal unary operation for atomics is '&'.
15278 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15279 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15280 // only with a builtin functions and therefore should be disallowed here.
15281 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15282 || Ty->isBlockPointerType())) {
15283 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15284 << InputExpr->getType()
15285 << Input.get()->getSourceRange());
15286 }
15287 }
15288
15289 if (getLangOpts().HLSL && OpLoc.isValid()) {
15290 if (Opc == UO_AddrOf)
15291 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15292 if (Opc == UO_Deref)
15293 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15294 }
15295
15296 if (InputExpr->isTypeDependent() &&
15297 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
15298 resultType = Context.DependentTy;
15299 } else {
15300 switch (Opc) {
15301 case UO_PreInc:
15302 case UO_PreDec:
15303 case UO_PostInc:
15304 case UO_PostDec:
15305 resultType =
15306 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
15307 Opc == UO_PreInc || Opc == UO_PostInc,
15308 Opc == UO_PreInc || Opc == UO_PreDec);
15309 CanOverflow = isOverflowingIntegerType(Context, resultType);
15310 break;
15311 case UO_AddrOf:
15312 resultType = CheckAddressOfOperand(Input, OpLoc);
15313 CheckAddressOfNoDeref(InputExpr);
15314 RecordModifiableNonNullParam(*this, InputExpr);
15315 break;
15316 case UO_Deref: {
15318 if (Input.isInvalid())
15319 return ExprError();
15320 resultType =
15321 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15322 break;
15323 }
15324 case UO_Plus:
15325 case UO_Minus:
15326 CanOverflow = Opc == UO_Minus &&
15328 Input = UsualUnaryConversions(Input.get());
15329 if (Input.isInvalid())
15330 return ExprError();
15331 // Unary plus and minus require promoting an operand of half vector to a
15332 // float vector and truncating the result back to a half vector. For now,
15333 // we do this only when HalfArgsAndReturns is set (that is, when the
15334 // target is arm or arm64).
15335 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15336
15337 // If the operand is a half vector, promote it to a float vector.
15338 if (ConvertHalfVec)
15339 Input = convertVector(Input.get(), Context.FloatTy, *this);
15340 resultType = Input.get()->getType();
15341 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15342 break;
15343 else if (resultType->isVectorType() &&
15344 // The z vector extensions don't allow + or - with bool vectors.
15345 (!Context.getLangOpts().ZVector ||
15346 resultType->castAs<VectorType>()->getVectorKind() !=
15348 break;
15349 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
15350 break;
15351 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15352 Opc == UO_Plus && resultType->isPointerType())
15353 break;
15354
15355 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15356 << resultType << Input.get()->getSourceRange());
15357
15358 case UO_Not: // bitwise complement
15359 Input = UsualUnaryConversions(Input.get());
15360 if (Input.isInvalid())
15361 return ExprError();
15362 resultType = Input.get()->getType();
15363 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15364 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15365 // C99 does not support '~' for complex conjugation.
15366 Diag(OpLoc, diag::ext_integer_complement_complex)
15367 << resultType << Input.get()->getSourceRange();
15368 else if (resultType->hasIntegerRepresentation())
15369 break;
15370 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15371 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15372 // on vector float types.
15373 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15374 if (!T->isIntegerType())
15375 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15376 << resultType << Input.get()->getSourceRange());
15377 } else {
15378 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15379 << resultType << Input.get()->getSourceRange());
15380 }
15381 break;
15382
15383 case UO_LNot: // logical negation
15384 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15386 if (Input.isInvalid())
15387 return ExprError();
15388 resultType = Input.get()->getType();
15389
15390 // Though we still have to promote half FP to float...
15391 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15392 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
15393 .get();
15394 resultType = Context.FloatTy;
15395 }
15396
15397 // WebAsembly tables can't be used in unary expressions.
15398 if (resultType->isPointerType() &&
15400 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15401 << resultType << Input.get()->getSourceRange());
15402 }
15403
15404 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15405 // C99 6.5.3.3p1: ok, fallthrough;
15406 if (Context.getLangOpts().CPlusPlus) {
15407 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15408 // operand contextually converted to bool.
15409 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15410 ScalarTypeToBooleanCastKind(resultType));
15411 } else if (Context.getLangOpts().OpenCL &&
15412 Context.getLangOpts().OpenCLVersion < 120) {
15413 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15414 // operate on scalar float types.
15415 if (!resultType->isIntegerType() && !resultType->isPointerType())
15416 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15417 << resultType << Input.get()->getSourceRange());
15418 }
15419 } else if (resultType->isExtVectorType()) {
15420 if (Context.getLangOpts().OpenCL &&
15422 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15423 // operate on vector float types.
15424 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15425 if (!T->isIntegerType())
15426 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15427 << resultType << Input.get()->getSourceRange());
15428 }
15429 // Vector logical not returns the signed variant of the operand type.
15430 resultType = GetSignedVectorType(resultType);
15431 break;
15432 } else if (Context.getLangOpts().CPlusPlus &&
15433 resultType->isVectorType()) {
15434 const VectorType *VTy = resultType->castAs<VectorType>();
15435 if (VTy->getVectorKind() != VectorKind::Generic)
15436 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15437 << resultType << Input.get()->getSourceRange());
15438
15439 // Vector logical not returns the signed variant of the operand type.
15440 resultType = GetSignedVectorType(resultType);
15441 break;
15442 } else {
15443 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15444 << resultType << Input.get()->getSourceRange());
15445 }
15446
15447 // LNot always has type int. C99 6.5.3.3p5.
15448 // In C++, it's bool. C++ 5.3.1p8
15449 resultType = Context.getLogicalOperationType();
15450 break;
15451 case UO_Real:
15452 case UO_Imag:
15453 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15454 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
15455 // ordinary complex l-values to ordinary l-values and all other values to
15456 // r-values.
15457 if (Input.isInvalid())
15458 return ExprError();
15459 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15460 if (Input.get()->isGLValue() &&
15461 Input.get()->getObjectKind() == OK_Ordinary)
15462 VK = Input.get()->getValueKind();
15463 } else if (!getLangOpts().CPlusPlus) {
15464 // In C, a volatile scalar is read by __imag. In C++, it is not.
15465 Input = DefaultLvalueConversion(Input.get());
15466 }
15467 break;
15468 case UO_Extension:
15469 resultType = Input.get()->getType();
15470 VK = Input.get()->getValueKind();
15471 OK = Input.get()->getObjectKind();
15472 break;
15473 case UO_Coawait:
15474 // It's unnecessary to represent the pass-through operator co_await in the
15475 // AST; just return the input expression instead.
15476 assert(!Input.get()->getType()->isDependentType() &&
15477 "the co_await expression must be non-dependant before "
15478 "building operator co_await");
15479 return Input;
15480 }
15481 }
15482 if (resultType.isNull() || Input.isInvalid())
15483 return ExprError();
15484
15485 // Check for array bounds violations in the operand of the UnaryOperator,
15486 // except for the '*' and '&' operators that have to be handled specially
15487 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15488 // that are explicitly defined as valid by the standard).
15489 if (Opc != UO_AddrOf && Opc != UO_Deref)
15490 CheckArrayAccess(Input.get());
15491
15492 auto *UO =
15493 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15494 OpLoc, CanOverflow, CurFPFeatureOverrides());
15495
15496 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15497 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15499 ExprEvalContexts.back().PossibleDerefs.insert(UO);
15500
15501 // Convert the result back to a half vector.
15502 if (ConvertHalfVec)
15503 return convertVector(UO, Context.HalfTy, *this);
15504 return UO;
15505}
15506
15508 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15509 if (!DRE->getQualifier())
15510 return false;
15511
15512 ValueDecl *VD = DRE->getDecl();
15513 if (!VD->isCXXClassMember())
15514 return false;
15515
15516 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15517 return true;
15518 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15519 return Method->isImplicitObjectMemberFunction();
15520
15521 return false;
15522 }
15523
15524 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15525 if (!ULE->getQualifier())
15526 return false;
15527
15528 for (NamedDecl *D : ULE->decls()) {
15529 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15530 if (Method->isImplicitObjectMemberFunction())
15531 return true;
15532 } else {
15533 // Overload set does not contain methods.
15534 break;
15535 }
15536 }
15537
15538 return false;
15539 }
15540
15541 return false;
15542}
15543
15545 UnaryOperatorKind Opc, Expr *Input,
15546 bool IsAfterAmp) {
15547 // First things first: handle placeholders so that the
15548 // overloaded-operator check considers the right type.
15549 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15550 // Increment and decrement of pseudo-object references.
15551 if (pty->getKind() == BuiltinType::PseudoObject &&
15553 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
15554
15555 // extension is always a builtin operator.
15556 if (Opc == UO_Extension)
15557 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15558
15559 // & gets special logic for several kinds of placeholder.
15560 // The builtin code knows what to do.
15561 if (Opc == UO_AddrOf &&
15562 (pty->getKind() == BuiltinType::Overload ||
15563 pty->getKind() == BuiltinType::UnknownAny ||
15564 pty->getKind() == BuiltinType::BoundMember))
15565 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15566
15567 // Anything else needs to be handled now.
15569 if (Result.isInvalid()) return ExprError();
15570 Input = Result.get();
15571 }
15572
15573 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15575 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15576 // Find all of the overloaded operators visible from this point.
15577 UnresolvedSet<16> Functions;
15579 if (S && OverOp != OO_None)
15580 LookupOverloadedOperatorName(OverOp, S, Functions);
15581
15582 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15583 }
15584
15585 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
15586}
15587
15589 Expr *Input, bool IsAfterAmp) {
15590 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
15591 IsAfterAmp);
15592}
15593
15595 LabelDecl *TheDecl) {
15596 TheDecl->markUsed(Context);
15597 // Create the AST node. The address of a label always has type 'void*'.
15598 auto *Res = new (Context) AddrLabelExpr(
15599 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
15600
15601 if (getCurFunction())
15602 getCurFunction()->AddrLabels.push_back(Res);
15603
15604 return Res;
15605}
15606
15609 // Make sure we diagnose jumping into a statement expression.
15611}
15612
15614 // Note that function is also called by TreeTransform when leaving a
15615 // StmtExpr scope without rebuilding anything.
15616
15619}
15620
15622 SourceLocation RPLoc) {
15623 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15624}
15625
15627 SourceLocation RPLoc, unsigned TemplateDepth) {
15628 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15629 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15630
15633 assert(!Cleanup.exprNeedsCleanups() &&
15634 "cleanups within StmtExpr not correctly bound!");
15636
15637 // FIXME: there are a variety of strange constraints to enforce here, for
15638 // example, it is not possible to goto into a stmt expression apparently.
15639 // More semantic analysis is needed.
15640
15641 // If there are sub-stmts in the compound stmt, take the type of the last one
15642 // as the type of the stmtexpr.
15643 QualType Ty = Context.VoidTy;
15644 bool StmtExprMayBindToTemp = false;
15645 if (!Compound->body_empty()) {
15646 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15647 if (const auto *LastStmt =
15648 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15649 if (const Expr *Value = LastStmt->getExprStmt()) {
15650 StmtExprMayBindToTemp = true;
15651 Ty = Value->getType();
15652 }
15653 }
15654 }
15655
15656 // FIXME: Check that expression type is complete/non-abstract; statement
15657 // expressions are not lvalues.
15658 Expr *ResStmtExpr =
15659 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15660 if (StmtExprMayBindToTemp)
15661 return MaybeBindToTemporary(ResStmtExpr);
15662 return ResStmtExpr;
15663}
15664
15666 if (ER.isInvalid())
15667 return ExprError();
15668
15669 // Do function/array conversion on the last expression, but not
15670 // lvalue-to-rvalue. However, initialize an unqualified type.
15672 if (ER.isInvalid())
15673 return ExprError();
15674 Expr *E = ER.get();
15675
15676 if (E->isTypeDependent())
15677 return E;
15678
15679 // In ARC, if the final expression ends in a consume, splice
15680 // the consume out and bind it later. In the alternate case
15681 // (when dealing with a retainable type), the result
15682 // initialization will create a produce. In both cases the
15683 // result will be +1, and we'll need to balance that out with
15684 // a bind.
15685 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15686 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15687 return Cast->getSubExpr();
15688
15689 // FIXME: Provide a better location for the initialization.
15693 SourceLocation(), E);
15694}
15695
15697 TypeSourceInfo *TInfo,
15698 ArrayRef<OffsetOfComponent> Components,
15699 SourceLocation RParenLoc) {
15700 QualType ArgTy = TInfo->getType();
15701 bool Dependent = ArgTy->isDependentType();
15702 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15703
15704 // We must have at least one component that refers to the type, and the first
15705 // one is known to be a field designator. Verify that the ArgTy represents
15706 // a struct/union/class.
15707 if (!Dependent && !ArgTy->isRecordType())
15708 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15709 << ArgTy << TypeRange);
15710
15711 // Type must be complete per C99 7.17p3 because a declaring a variable
15712 // with an incomplete type would be ill-formed.
15713 if (!Dependent
15714 && RequireCompleteType(BuiltinLoc, ArgTy,
15715 diag::err_offsetof_incomplete_type, TypeRange))
15716 return ExprError();
15717
15718 bool DidWarnAboutNonPOD = false;
15719 QualType CurrentType = ArgTy;
15722 for (const OffsetOfComponent &OC : Components) {
15723 if (OC.isBrackets) {
15724 // Offset of an array sub-field. TODO: Should we allow vector elements?
15725 if (!CurrentType->isDependentType()) {
15726 const ArrayType *AT = Context.getAsArrayType(CurrentType);
15727 if(!AT)
15728 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15729 << CurrentType);
15730 CurrentType = AT->getElementType();
15731 } else
15732 CurrentType = Context.DependentTy;
15733
15734 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15735 if (IdxRval.isInvalid())
15736 return ExprError();
15737 Expr *Idx = IdxRval.get();
15738
15739 // The expression must be an integral expression.
15740 // FIXME: An integral constant expression?
15741 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15742 !Idx->getType()->isIntegerType())
15743 return ExprError(
15744 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15745 << Idx->getSourceRange());
15746
15747 // Record this array index.
15748 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15749 Exprs.push_back(Idx);
15750 continue;
15751 }
15752
15753 // Offset of a field.
15754 if (CurrentType->isDependentType()) {
15755 // We have the offset of a field, but we can't look into the dependent
15756 // type. Just record the identifier of the field.
15757 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15758 CurrentType = Context.DependentTy;
15759 continue;
15760 }
15761
15762 // We need to have a complete type to look into.
15763 if (RequireCompleteType(OC.LocStart, CurrentType,
15764 diag::err_offsetof_incomplete_type))
15765 return ExprError();
15766
15767 // Look for the designated field.
15768 const RecordType *RC = CurrentType->getAs<RecordType>();
15769 if (!RC)
15770 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
15771 << CurrentType);
15772 RecordDecl *RD = RC->getDecl();
15773
15774 // C++ [lib.support.types]p5:
15775 // The macro offsetof accepts a restricted set of type arguments in this
15776 // International Standard. type shall be a POD structure or a POD union
15777 // (clause 9).
15778 // C++11 [support.types]p4:
15779 // If type is not a standard-layout class (Clause 9), the results are
15780 // undefined.
15781 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15782 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
15783 unsigned DiagID =
15784 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
15785 : diag::ext_offsetof_non_pod_type;
15786
15787 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
15788 Diag(BuiltinLoc, DiagID)
15789 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
15790 DidWarnAboutNonPOD = true;
15791 }
15792 }
15793
15794 // Look for the field.
15795 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
15796 LookupQualifiedName(R, RD);
15797 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
15798 IndirectFieldDecl *IndirectMemberDecl = nullptr;
15799 if (!MemberDecl) {
15800 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
15801 MemberDecl = IndirectMemberDecl->getAnonField();
15802 }
15803
15804 if (!MemberDecl) {
15805 // Lookup could be ambiguous when looking up a placeholder variable
15806 // __builtin_offsetof(S, _).
15807 // In that case we would already have emitted a diagnostic
15808 if (!R.isAmbiguous())
15809 Diag(BuiltinLoc, diag::err_no_member)
15810 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
15811 return ExprError();
15812 }
15813
15814 // C99 7.17p3:
15815 // (If the specified member is a bit-field, the behavior is undefined.)
15816 //
15817 // We diagnose this as an error.
15818 if (MemberDecl->isBitField()) {
15819 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
15820 << MemberDecl->getDeclName()
15821 << SourceRange(BuiltinLoc, RParenLoc);
15822 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
15823 return ExprError();
15824 }
15825
15826 RecordDecl *Parent = MemberDecl->getParent();
15827 if (IndirectMemberDecl)
15828 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
15829
15830 // If the member was found in a base class, introduce OffsetOfNodes for
15831 // the base class indirections.
15832 CXXBasePaths Paths;
15833 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
15834 Paths)) {
15835 if (Paths.getDetectedVirtual()) {
15836 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
15837 << MemberDecl->getDeclName()
15838 << SourceRange(BuiltinLoc, RParenLoc);
15839 return ExprError();
15840 }
15841
15842 CXXBasePath &Path = Paths.front();
15843 for (const CXXBasePathElement &B : Path)
15844 Comps.push_back(OffsetOfNode(B.Base));
15845 }
15846
15847 if (IndirectMemberDecl) {
15848 for (auto *FI : IndirectMemberDecl->chain()) {
15849 assert(isa<FieldDecl>(FI));
15850 Comps.push_back(OffsetOfNode(OC.LocStart,
15851 cast<FieldDecl>(FI), OC.LocEnd));
15852 }
15853 } else
15854 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
15855
15856 CurrentType = MemberDecl->getType().getNonReferenceType();
15857 }
15858
15859 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
15860 Comps, Exprs, RParenLoc);
15861}
15862
15864 SourceLocation BuiltinLoc,
15866 ParsedType ParsedArgTy,
15867 ArrayRef<OffsetOfComponent> Components,
15868 SourceLocation RParenLoc) {
15869
15870 TypeSourceInfo *ArgTInfo;
15871 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
15872 if (ArgTy.isNull())
15873 return ExprError();
15874
15875 if (!ArgTInfo)
15876 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
15877
15878 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
15879}
15880
15881
15883 Expr *CondExpr,
15884 Expr *LHSExpr, Expr *RHSExpr,
15885 SourceLocation RPLoc) {
15886 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
15887
15890 QualType resType;
15891 bool CondIsTrue = false;
15892 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
15893 resType = Context.DependentTy;
15894 } else {
15895 // The conditional expression is required to be a constant expression.
15896 llvm::APSInt condEval(32);
15898 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
15899 if (CondICE.isInvalid())
15900 return ExprError();
15901 CondExpr = CondICE.get();
15902 CondIsTrue = condEval.getZExtValue();
15903
15904 // If the condition is > zero, then the AST type is the same as the LHSExpr.
15905 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
15906
15907 resType = ActiveExpr->getType();
15908 VK = ActiveExpr->getValueKind();
15909 OK = ActiveExpr->getObjectKind();
15910 }
15911
15912 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
15913 resType, VK, OK, RPLoc, CondIsTrue);
15914}
15915
15916//===----------------------------------------------------------------------===//
15917// Clang Extensions.
15918//===----------------------------------------------------------------------===//
15919
15920void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
15922
15923 if (LangOpts.CPlusPlus) {
15925 Decl *ManglingContextDecl;
15926 std::tie(MCtx, ManglingContextDecl) =
15927 getCurrentMangleNumberContext(Block->getDeclContext());
15928 if (MCtx) {
15929 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
15930 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
15931 }
15932 }
15933
15934 PushBlockScope(CurScope, Block);
15936 if (CurScope)
15937 PushDeclContext(CurScope, Block);
15938 else
15939 CurContext = Block;
15940
15942
15943 // Enter a new evaluation context to insulate the block from any
15944 // cleanups from the enclosing full-expression.
15947}
15948
15950 Scope *CurScope) {
15951 assert(ParamInfo.getIdentifier() == nullptr &&
15952 "block-id should have no identifier!");
15953 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
15954 BlockScopeInfo *CurBlock = getCurBlock();
15955
15956 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
15957 QualType T = Sig->getType();
15958
15959 // FIXME: We should allow unexpanded parameter packs here, but that would,
15960 // in turn, make the block expression contain unexpanded parameter packs.
15961 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
15962 // Drop the parameters.
15964 EPI.HasTrailingReturn = false;
15965 EPI.TypeQuals.addConst();
15966 T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
15968 }
15969
15970 // GetTypeForDeclarator always produces a function type for a block
15971 // literal signature. Furthermore, it is always a FunctionProtoType
15972 // unless the function was written with a typedef.
15973 assert(T->isFunctionType() &&
15974 "GetTypeForDeclarator made a non-function block signature");
15975
15976 // Look for an explicit signature in that function type.
15977 FunctionProtoTypeLoc ExplicitSignature;
15978
15979 if ((ExplicitSignature = Sig->getTypeLoc()
15981
15982 // Check whether that explicit signature was synthesized by
15983 // GetTypeForDeclarator. If so, don't save that as part of the
15984 // written signature.
15985 if (ExplicitSignature.getLocalRangeBegin() ==
15986 ExplicitSignature.getLocalRangeEnd()) {
15987 // This would be much cheaper if we stored TypeLocs instead of
15988 // TypeSourceInfos.
15989 TypeLoc Result = ExplicitSignature.getReturnLoc();
15990 unsigned Size = Result.getFullDataSize();
15991 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
15992 Sig->getTypeLoc().initializeFullCopy(Result, Size);
15993
15994 ExplicitSignature = FunctionProtoTypeLoc();
15995 }
15996 }
15997
15998 CurBlock->TheDecl->setSignatureAsWritten(Sig);
15999 CurBlock->FunctionType = T;
16000
16001 const auto *Fn = T->castAs<FunctionType>();
16002 QualType RetTy = Fn->getReturnType();
16003 bool isVariadic =
16004 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16005
16006 CurBlock->TheDecl->setIsVariadic(isVariadic);
16007
16008 // Context.DependentTy is used as a placeholder for a missing block
16009 // return type. TODO: what should we do with declarators like:
16010 // ^ * { ... }
16011 // If the answer is "apply template argument deduction"....
16012 if (RetTy != Context.DependentTy) {
16013 CurBlock->ReturnType = RetTy;
16014 CurBlock->TheDecl->setBlockMissingReturnType(false);
16015 CurBlock->HasImplicitReturnType = false;
16016 }
16017
16018 // Push block parameters from the declarator if we had them.
16020 if (ExplicitSignature) {
16021 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16022 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16023 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16024 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16025 // Diagnose this as an extension in C17 and earlier.
16026 if (!getLangOpts().C23)
16027 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16028 }
16029 Params.push_back(Param);
16030 }
16031
16032 // Fake up parameter variables if we have a typedef, like
16033 // ^ fntype { ... }
16034 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16035 for (const auto &I : Fn->param_types()) {
16037 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16038 Params.push_back(Param);
16039 }
16040 }
16041
16042 // Set the parameters on the block decl.
16043 if (!Params.empty()) {
16044 CurBlock->TheDecl->setParams(Params);
16046 /*CheckParameterNames=*/false);
16047 }
16048
16049 // Finally we can process decl attributes.
16050 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16051
16052 // Put the parameter variables in scope.
16053 for (auto *AI : CurBlock->TheDecl->parameters()) {
16054 AI->setOwningFunction(CurBlock->TheDecl);
16055
16056 // If this has an identifier, add it to the scope stack.
16057 if (AI->getIdentifier()) {
16058 CheckShadow(CurBlock->TheScope, AI);
16059
16060 PushOnScopeChains(AI, CurBlock->TheScope);
16061 }
16062
16063 if (AI->isInvalidDecl())
16064 CurBlock->TheDecl->setInvalidDecl();
16065 }
16066}
16067
16068void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16069 // Leave the expression-evaluation context.
16072
16073 // Pop off CurBlock, handle nested blocks.
16076}
16077
16079 Stmt *Body, Scope *CurScope) {
16080 // If blocks are disabled, emit an error.
16081 if (!LangOpts.Blocks)
16082 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16083
16084 // Leave the expression-evaluation context.
16087 assert(!Cleanup.exprNeedsCleanups() &&
16088 "cleanups within block not correctly bound!");
16090
16091 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16092 BlockDecl *BD = BSI->TheDecl;
16093
16094 if (BSI->HasImplicitReturnType)
16096
16097 QualType RetTy = Context.VoidTy;
16098 if (!BSI->ReturnType.isNull())
16099 RetTy = BSI->ReturnType;
16100
16101 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16102 QualType BlockTy;
16103
16104 // If the user wrote a function type in some form, try to use that.
16105 if (!BSI->FunctionType.isNull()) {
16106 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16107
16108 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16109 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16110
16111 // Turn protoless block types into nullary block types.
16112 if (isa<FunctionNoProtoType>(FTy)) {
16114 EPI.ExtInfo = Ext;
16115 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16116
16117 // Otherwise, if we don't need to change anything about the function type,
16118 // preserve its sugar structure.
16119 } else if (FTy->getReturnType() == RetTy &&
16120 (!NoReturn || FTy->getNoReturnAttr())) {
16121 BlockTy = BSI->FunctionType;
16122
16123 // Otherwise, make the minimal modifications to the function type.
16124 } else {
16125 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16127 EPI.TypeQuals = Qualifiers();
16128 EPI.ExtInfo = Ext;
16129 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16130 }
16131
16132 // If we don't have a function type, just build one from nothing.
16133 } else {
16135 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16136 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16137 }
16138
16140 BlockTy = Context.getBlockPointerType(BlockTy);
16141
16142 // If needed, diagnose invalid gotos and switches in the block.
16143 if (getCurFunction()->NeedsScopeChecking() &&
16145 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16146
16147 BD->setBody(cast<CompoundStmt>(Body));
16148
16149 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16151
16152 // Try to apply the named return value optimization. We have to check again
16153 // if we can do this, though, because blocks keep return statements around
16154 // to deduce an implicit return type.
16155 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16156 !BD->isDependentContext())
16157 computeNRVO(Body, BSI);
16158
16163
16165
16166 // Set the captured variables on the block.
16168 for (Capture &Cap : BSI->Captures) {
16169 if (Cap.isInvalid() || Cap.isThisCapture())
16170 continue;
16171 // Cap.getVariable() is always a VarDecl because
16172 // blocks cannot capture structured bindings or other ValueDecl kinds.
16173 auto *Var = cast<VarDecl>(Cap.getVariable());
16174 Expr *CopyExpr = nullptr;
16175 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16176 if (const RecordType *Record =
16177 Cap.getCaptureType()->getAs<RecordType>()) {
16178 // The capture logic needs the destructor, so make sure we mark it.
16179 // Usually this is unnecessary because most local variables have
16180 // their destructors marked at declaration time, but parameters are
16181 // an exception because it's technically only the call site that
16182 // actually requires the destructor.
16183 if (isa<ParmVarDecl>(Var))
16185
16186 // Enter a separate potentially-evaluated context while building block
16187 // initializers to isolate their cleanups from those of the block
16188 // itself.
16189 // FIXME: Is this appropriate even when the block itself occurs in an
16190 // unevaluated operand?
16193
16195
16197 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16198
16199 // According to the blocks spec, the capture of a variable from
16200 // the stack requires a const copy constructor. This is not true
16201 // of the copy/move done to move a __block variable to the heap.
16202 if (!Result.isInvalid() &&
16203 !Result.get()->getType().isConstQualified()) {
16205 Result.get()->getType().withConst(),
16206 CK_NoOp, VK_LValue);
16207 }
16208
16209 if (!Result.isInvalid()) {
16211 InitializedEntity::InitializeBlock(Var->getLocation(),
16212 Cap.getCaptureType()),
16213 Loc, Result.get());
16214 }
16215
16216 // Build a full-expression copy expression if initialization
16217 // succeeded and used a non-trivial constructor. Recover from
16218 // errors by pretending that the copy isn't necessary.
16219 if (!Result.isInvalid() &&
16220 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16221 ->isTrivial()) {
16223 CopyExpr = Result.get();
16224 }
16225 }
16226 }
16227
16228 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16229 CopyExpr);
16230 Captures.push_back(NewCap);
16231 }
16232 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16233
16234 // Pop the block scope now but keep it alive to the end of this function.
16236 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16237
16238 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16239
16240 // If the block isn't obviously global, i.e. it captures anything at
16241 // all, then we need to do a few things in the surrounding context:
16242 if (Result->getBlockDecl()->hasCaptures()) {
16243 // First, this expression has a new cleanup object.
16244 ExprCleanupObjects.push_back(Result->getBlockDecl());
16246
16247 // It also gets a branch-protected scope if any of the captured
16248 // variables needs destruction.
16249 for (const auto &CI : Result->getBlockDecl()->captures()) {
16250 const VarDecl *var = CI.getVariable();
16251 if (var->getType().isDestructedType() != QualType::DK_none) {
16253 break;
16254 }
16255 }
16256 }
16257
16258 if (getCurFunction())
16259 getCurFunction()->addBlock(BD);
16260
16261 if (BD->isInvalidDecl())
16262 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16263 {Result}, Result->getType());
16264 return Result;
16265}
16266
16268 SourceLocation RPLoc) {
16269 TypeSourceInfo *TInfo;
16270 GetTypeFromParser(Ty, &TInfo);
16271 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16272}
16273
16275 Expr *E, TypeSourceInfo *TInfo,
16276 SourceLocation RPLoc) {
16277 Expr *OrigExpr = E;
16278 bool IsMS = false;
16279
16280 // CUDA device code does not support varargs.
16281 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16282 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16286 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16287 }
16288 }
16289
16290 // NVPTX does not support va_arg expression.
16291 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16292 Context.getTargetInfo().getTriple().isNVPTX())
16293 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16294
16295 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16296 // as Microsoft ABI on an actual Microsoft platform, where
16297 // __builtin_ms_va_list and __builtin_va_list are the same.)
16300 QualType MSVaListType = Context.getBuiltinMSVaListType();
16301 if (Context.hasSameType(MSVaListType, E->getType())) {
16302 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16303 return ExprError();
16304 IsMS = true;
16305 }
16306 }
16307
16308 // Get the va_list type
16309 QualType VaListType = Context.getBuiltinVaListType();
16310 if (!IsMS) {
16311 if (VaListType->isArrayType()) {
16312 // Deal with implicit array decay; for example, on x86-64,
16313 // va_list is an array, but it's supposed to decay to
16314 // a pointer for va_arg.
16315 VaListType = Context.getArrayDecayedType(VaListType);
16316 // Make sure the input expression also decays appropriately.
16318 if (Result.isInvalid())
16319 return ExprError();
16320 E = Result.get();
16321 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16322 // If va_list is a record type and we are compiling in C++ mode,
16323 // check the argument using reference binding.
16325 Context, Context.getLValueReferenceType(VaListType), false);
16327 if (Init.isInvalid())
16328 return ExprError();
16329 E = Init.getAs<Expr>();
16330 } else {
16331 // Otherwise, the va_list argument must be an l-value because
16332 // it is modified by va_arg.
16333 if (!E->isTypeDependent() &&
16334 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16335 return ExprError();
16336 }
16337 }
16338
16339 if (!IsMS && !E->isTypeDependent() &&
16340 !Context.hasSameType(VaListType, E->getType()))
16341 return ExprError(
16342 Diag(E->getBeginLoc(),
16343 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16344 << OrigExpr->getType() << E->getSourceRange());
16345
16346 if (!TInfo->getType()->isDependentType()) {
16347 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16348 diag::err_second_parameter_to_va_arg_incomplete,
16349 TInfo->getTypeLoc()))
16350 return ExprError();
16351
16353 TInfo->getType(),
16354 diag::err_second_parameter_to_va_arg_abstract,
16355 TInfo->getTypeLoc()))
16356 return ExprError();
16357
16358 if (!TInfo->getType().isPODType(Context)) {
16359 Diag(TInfo->getTypeLoc().getBeginLoc(),
16360 TInfo->getType()->isObjCLifetimeType()
16361 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16362 : diag::warn_second_parameter_to_va_arg_not_pod)
16363 << TInfo->getType()
16364 << TInfo->getTypeLoc().getSourceRange();
16365 }
16366
16367 // Check for va_arg where arguments of the given type will be promoted
16368 // (i.e. this va_arg is guaranteed to have undefined behavior).
16369 QualType PromoteType;
16370 if (Context.isPromotableIntegerType(TInfo->getType())) {
16371 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16372 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16373 // and C23 7.16.1.1p2 says, in part:
16374 // If type is not compatible with the type of the actual next argument
16375 // (as promoted according to the default argument promotions), the
16376 // behavior is undefined, except for the following cases:
16377 // - both types are pointers to qualified or unqualified versions of
16378 // compatible types;
16379 // - one type is compatible with a signed integer type, the other
16380 // type is compatible with the corresponding unsigned integer type,
16381 // and the value is representable in both types;
16382 // - one type is pointer to qualified or unqualified void and the
16383 // other is a pointer to a qualified or unqualified character type;
16384 // - or, the type of the next argument is nullptr_t and type is a
16385 // pointer type that has the same representation and alignment
16386 // requirements as a pointer to a character type.
16387 // Given that type compatibility is the primary requirement (ignoring
16388 // qualifications), you would think we could call typesAreCompatible()
16389 // directly to test this. However, in C++, that checks for *same type*,
16390 // which causes false positives when passing an enumeration type to
16391 // va_arg. Instead, get the underlying type of the enumeration and pass
16392 // that.
16393 QualType UnderlyingType = TInfo->getType();
16394 if (const auto *ET = UnderlyingType->getAs<EnumType>())
16395 UnderlyingType = ET->getDecl()->getIntegerType();
16396 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16397 /*CompareUnqualified*/ true))
16398 PromoteType = QualType();
16399
16400 // If the types are still not compatible, we need to test whether the
16401 // promoted type and the underlying type are the same except for
16402 // signedness. Ask the AST for the correctly corresponding type and see
16403 // if that's compatible.
16404 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16405 PromoteType->isUnsignedIntegerType() !=
16406 UnderlyingType->isUnsignedIntegerType()) {
16407 UnderlyingType =
16408 UnderlyingType->isUnsignedIntegerType()
16409 ? Context.getCorrespondingSignedType(UnderlyingType)
16410 : Context.getCorrespondingUnsignedType(UnderlyingType);
16411 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16412 /*CompareUnqualified*/ true))
16413 PromoteType = QualType();
16414 }
16415 }
16416 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16417 PromoteType = Context.DoubleTy;
16418 if (!PromoteType.isNull())
16420 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16421 << TInfo->getType()
16422 << PromoteType
16423 << TInfo->getTypeLoc().getSourceRange());
16424 }
16425
16427 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16428}
16429
16431 // The type of __null will be int or long, depending on the size of
16432 // pointers on the target.
16433 QualType Ty;
16435 if (pw == Context.getTargetInfo().getIntWidth())
16436 Ty = Context.IntTy;
16437 else if (pw == Context.getTargetInfo().getLongWidth())
16438 Ty = Context.LongTy;
16439 else if (pw == Context.getTargetInfo().getLongLongWidth())
16440 Ty = Context.LongLongTy;
16441 else {
16442 llvm_unreachable("I don't know size of pointer!");
16443 }
16444
16445 return new (Context) GNUNullExpr(Ty, TokenLoc);
16446}
16447
16449 CXXRecordDecl *ImplDecl = nullptr;
16450
16451 // Fetch the std::source_location::__impl decl.
16452 if (NamespaceDecl *Std = S.getStdNamespace()) {
16453 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16455 if (S.LookupQualifiedName(ResultSL, Std)) {
16456 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16457 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16459 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16460 S.LookupQualifiedName(ResultImpl, SLDecl)) {
16461 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16462 }
16463 }
16464 }
16465 }
16466
16467 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16468 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16469 return nullptr;
16470 }
16471
16472 // Verify that __impl is a trivial struct type, with no base classes, and with
16473 // only the four expected fields.
16474 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16475 ImplDecl->getNumBases() != 0) {
16476 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16477 return nullptr;
16478 }
16479
16480 unsigned Count = 0;
16481 for (FieldDecl *F : ImplDecl->fields()) {
16482 StringRef Name = F->getName();
16483
16484 if (Name == "_M_file_name") {
16485 if (F->getType() !=
16487 break;
16488 Count++;
16489 } else if (Name == "_M_function_name") {
16490 if (F->getType() !=
16492 break;
16493 Count++;
16494 } else if (Name == "_M_line") {
16495 if (!F->getType()->isIntegerType())
16496 break;
16497 Count++;
16498 } else if (Name == "_M_column") {
16499 if (!F->getType()->isIntegerType())
16500 break;
16501 Count++;
16502 } else {
16503 Count = 100; // invalid
16504 break;
16505 }
16506 }
16507 if (Count != 4) {
16508 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16509 return nullptr;
16510 }
16511
16512 return ImplDecl;
16513}
16514
16516 SourceLocation BuiltinLoc,
16517 SourceLocation RPLoc) {
16518 QualType ResultTy;
16519 switch (Kind) {
16525 ResultTy =
16527 break;
16528 }
16531 ResultTy = Context.UnsignedIntTy;
16532 break;
16536 LookupStdSourceLocationImpl(*this, BuiltinLoc);
16538 return ExprError();
16539 }
16540 ResultTy = Context.getPointerType(
16542 break;
16543 }
16544
16545 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16546}
16547
16549 SourceLocation BuiltinLoc,
16550 SourceLocation RPLoc,
16551 DeclContext *ParentContext) {
16552 return new (Context)
16553 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16554}
16555
16557 StringLiteral *BinaryData) {
16559 Data->BinaryData = BinaryData;
16560 return new (Context)
16561 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
16562 Data->getDataElementCount());
16563}
16564
16566 const Expr *SrcExpr) {
16567 if (!DstType->isFunctionPointerType() ||
16568 !SrcExpr->getType()->isFunctionType())
16569 return false;
16570
16571 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16572 if (!DRE)
16573 return false;
16574
16575 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16576 if (!FD)
16577 return false;
16578
16580 /*Complain=*/true,
16581 SrcExpr->getBeginLoc());
16582}
16583
16586 QualType DstType, QualType SrcType,
16587 Expr *SrcExpr, AssignmentAction Action,
16588 bool *Complained) {
16589 if (Complained)
16590 *Complained = false;
16591
16592 // Decode the result (notice that AST's are still created for extensions).
16593 bool CheckInferredResultType = false;
16594 bool isInvalid = false;
16595 unsigned DiagKind = 0;
16596 ConversionFixItGenerator ConvHints;
16597 bool MayHaveConvFixit = false;
16598 bool MayHaveFunctionDiff = false;
16599 const ObjCInterfaceDecl *IFace = nullptr;
16600 const ObjCProtocolDecl *PDecl = nullptr;
16601
16602 switch (ConvTy) {
16603 case Compatible:
16604 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16605 return false;
16606
16607 case PointerToInt:
16608 if (getLangOpts().CPlusPlus) {
16609 DiagKind = diag::err_typecheck_convert_pointer_int;
16610 isInvalid = true;
16611 } else {
16612 DiagKind = diag::ext_typecheck_convert_pointer_int;
16613 }
16614 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16615 MayHaveConvFixit = true;
16616 break;
16617 case IntToPointer:
16618 if (getLangOpts().CPlusPlus) {
16619 DiagKind = diag::err_typecheck_convert_int_pointer;
16620 isInvalid = true;
16621 } else {
16622 DiagKind = diag::ext_typecheck_convert_int_pointer;
16623 }
16624 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16625 MayHaveConvFixit = true;
16626 break;
16628 DiagKind =
16629 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
16630 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16631 MayHaveConvFixit = true;
16632 break;
16634 if (getLangOpts().CPlusPlus) {
16635 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16636 isInvalid = true;
16637 } else {
16638 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16639 }
16640 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16641 MayHaveConvFixit = true;
16642 break;
16644 if (Action == AA_Passing_CFAudited) {
16645 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16646 } else if (getLangOpts().CPlusPlus) {
16647 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16648 isInvalid = true;
16649 } else {
16650 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16651 }
16652 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16653 SrcType->isObjCObjectPointerType();
16654 if (CheckInferredResultType) {
16655 SrcType = SrcType.getUnqualifiedType();
16656 DstType = DstType.getUnqualifiedType();
16657 } else {
16658 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16659 }
16660 MayHaveConvFixit = true;
16661 break;
16663 if (getLangOpts().CPlusPlus) {
16664 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16665 isInvalid = true;
16666 } else {
16667 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16668 }
16669 break;
16671 if (getLangOpts().CPlusPlus) {
16672 DiagKind = diag::err_typecheck_convert_pointer_void_func;
16673 isInvalid = true;
16674 } else {
16675 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16676 }
16677 break;
16679 // Perform array-to-pointer decay if necessary.
16680 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16681
16682 isInvalid = true;
16683
16684 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16685 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16686 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16687 DiagKind = diag::err_typecheck_incompatible_address_space;
16688 break;
16689 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16690 DiagKind = diag::err_typecheck_incompatible_ownership;
16691 break;
16692 }
16693
16694 llvm_unreachable("unknown error case for discarding qualifiers!");
16695 // fallthrough
16696 }
16698 // If the qualifiers lost were because we were applying the
16699 // (deprecated) C++ conversion from a string literal to a char*
16700 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16701 // Ideally, this check would be performed in
16702 // checkPointerTypesForAssignment. However, that would require a
16703 // bit of refactoring (so that the second argument is an
16704 // expression, rather than a type), which should be done as part
16705 // of a larger effort to fix checkPointerTypesForAssignment for
16706 // C++ semantics.
16707 if (getLangOpts().CPlusPlus &&
16709 return false;
16710 if (getLangOpts().CPlusPlus) {
16711 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
16712 isInvalid = true;
16713 } else {
16714 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
16715 }
16716
16717 break;
16719 if (getLangOpts().CPlusPlus) {
16720 isInvalid = true;
16721 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16722 } else {
16723 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16724 }
16725 break;
16727 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16728 isInvalid = true;
16729 break;
16730 case IntToBlockPointer:
16731 DiagKind = diag::err_int_to_block_pointer;
16732 isInvalid = true;
16733 break;
16735 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16736 isInvalid = true;
16737 break;
16739 if (SrcType->isObjCQualifiedIdType()) {
16740 const ObjCObjectPointerType *srcOPT =
16741 SrcType->castAs<ObjCObjectPointerType>();
16742 for (auto *srcProto : srcOPT->quals()) {
16743 PDecl = srcProto;
16744 break;
16745 }
16746 if (const ObjCInterfaceType *IFaceT =
16748 IFace = IFaceT->getDecl();
16749 }
16750 else if (DstType->isObjCQualifiedIdType()) {
16751 const ObjCObjectPointerType *dstOPT =
16752 DstType->castAs<ObjCObjectPointerType>();
16753 for (auto *dstProto : dstOPT->quals()) {
16754 PDecl = dstProto;
16755 break;
16756 }
16757 if (const ObjCInterfaceType *IFaceT =
16759 IFace = IFaceT->getDecl();
16760 }
16761 if (getLangOpts().CPlusPlus) {
16762 DiagKind = diag::err_incompatible_qualified_id;
16763 isInvalid = true;
16764 } else {
16765 DiagKind = diag::warn_incompatible_qualified_id;
16766 }
16767 break;
16768 }
16770 if (getLangOpts().CPlusPlus) {
16771 DiagKind = diag::err_incompatible_vectors;
16772 isInvalid = true;
16773 } else {
16774 DiagKind = diag::warn_incompatible_vectors;
16775 }
16776 break;
16778 DiagKind = diag::err_arc_weak_unavailable_assign;
16779 isInvalid = true;
16780 break;
16781 case Incompatible:
16782 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
16783 if (Complained)
16784 *Complained = true;
16785 return true;
16786 }
16787
16788 DiagKind = diag::err_typecheck_convert_incompatible;
16789 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16790 MayHaveConvFixit = true;
16791 isInvalid = true;
16792 MayHaveFunctionDiff = true;
16793 break;
16794 }
16795
16796 QualType FirstType, SecondType;
16797 switch (Action) {
16798 case AA_Assigning:
16799 case AA_Initializing:
16800 // The destination type comes first.
16801 FirstType = DstType;
16802 SecondType = SrcType;
16803 break;
16804
16805 case AA_Returning:
16806 case AA_Passing:
16808 case AA_Converting:
16809 case AA_Sending:
16810 case AA_Casting:
16811 // The source type comes first.
16812 FirstType = SrcType;
16813 SecondType = DstType;
16814 break;
16815 }
16816
16817 PartialDiagnostic FDiag = PDiag(DiagKind);
16818 AssignmentAction ActionForDiag = Action;
16819 if (Action == AA_Passing_CFAudited)
16820 ActionForDiag = AA_Passing;
16821
16822 FDiag << FirstType << SecondType << ActionForDiag
16823 << SrcExpr->getSourceRange();
16824
16825 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
16826 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
16827 auto isPlainChar = [](const clang::Type *Type) {
16828 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
16829 Type->isSpecificBuiltinType(BuiltinType::Char_U);
16830 };
16831 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
16832 isPlainChar(SecondType->getPointeeOrArrayElementType()));
16833 }
16834
16835 // If we can fix the conversion, suggest the FixIts.
16836 if (!ConvHints.isNull()) {
16837 for (FixItHint &H : ConvHints.Hints)
16838 FDiag << H;
16839 }
16840
16841 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
16842
16843 if (MayHaveFunctionDiff)
16844 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
16845
16846 Diag(Loc, FDiag);
16847 if ((DiagKind == diag::warn_incompatible_qualified_id ||
16848 DiagKind == diag::err_incompatible_qualified_id) &&
16849 PDecl && IFace && !IFace->hasDefinition())
16850 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
16851 << IFace << PDecl;
16852
16853 if (SecondType == Context.OverloadTy)
16855 FirstType, /*TakingAddress=*/true);
16856
16857 if (CheckInferredResultType)
16859
16860 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
16862
16863 if (Complained)
16864 *Complained = true;
16865 return isInvalid;
16866}
16867
16869 llvm::APSInt *Result,
16870 AllowFoldKind CanFold) {
16871 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
16872 public:
16873 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
16874 QualType T) override {
16875 return S.Diag(Loc, diag::err_ice_not_integral)
16876 << T << S.LangOpts.CPlusPlus;
16877 }
16878 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16879 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
16880 }
16881 } Diagnoser;
16882
16883 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16884}
16885
16887 llvm::APSInt *Result,
16888 unsigned DiagID,
16889 AllowFoldKind CanFold) {
16890 class IDDiagnoser : public VerifyICEDiagnoser {
16891 unsigned DiagID;
16892
16893 public:
16894 IDDiagnoser(unsigned DiagID)
16895 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
16896
16897 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
16898 return S.Diag(Loc, DiagID);
16899 }
16900 } Diagnoser(DiagID);
16901
16902 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
16903}
16904
16907 QualType T) {
16908 return diagnoseNotICE(S, Loc);
16909}
16910
16913 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
16914}
16915
16918 VerifyICEDiagnoser &Diagnoser,
16919 AllowFoldKind CanFold) {
16920 SourceLocation DiagLoc = E->getBeginLoc();
16921
16922 if (getLangOpts().CPlusPlus11) {
16923 // C++11 [expr.const]p5:
16924 // If an expression of literal class type is used in a context where an
16925 // integral constant expression is required, then that class type shall
16926 // have a single non-explicit conversion function to an integral or
16927 // unscoped enumeration type
16928 ExprResult Converted;
16929 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
16930 VerifyICEDiagnoser &BaseDiagnoser;
16931 public:
16932 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
16933 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
16934 BaseDiagnoser.Suppress, true),
16935 BaseDiagnoser(BaseDiagnoser) {}
16936
16937 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
16938 QualType T) override {
16939 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
16940 }
16941
16942 SemaDiagnosticBuilder diagnoseIncomplete(
16943 Sema &S, SourceLocation Loc, QualType T) override {
16944 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
16945 }
16946
16947 SemaDiagnosticBuilder diagnoseExplicitConv(
16948 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16949 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
16950 }
16951
16952 SemaDiagnosticBuilder noteExplicitConv(
16953 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16954 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16955 << ConvTy->isEnumeralType() << ConvTy;
16956 }
16957
16958 SemaDiagnosticBuilder diagnoseAmbiguous(
16959 Sema &S, SourceLocation Loc, QualType T) override {
16960 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
16961 }
16962
16963 SemaDiagnosticBuilder noteAmbiguous(
16964 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
16965 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
16966 << ConvTy->isEnumeralType() << ConvTy;
16967 }
16968
16969 SemaDiagnosticBuilder diagnoseConversion(
16970 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
16971 llvm_unreachable("conversion functions are permitted");
16972 }
16973 } ConvertDiagnoser(Diagnoser);
16974
16975 Converted = PerformContextualImplicitConversion(DiagLoc, E,
16976 ConvertDiagnoser);
16977 if (Converted.isInvalid())
16978 return Converted;
16979 E = Converted.get();
16980 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
16981 // don't try to evaluate it later. We also don't want to return the
16982 // RecoveryExpr here, as it results in this call succeeding, thus callers of
16983 // this function will attempt to use 'Value'.
16984 if (isa<RecoveryExpr>(E))
16985 return ExprError();
16987 return ExprError();
16988 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
16989 // An ICE must be of integral or unscoped enumeration type.
16990 if (!Diagnoser.Suppress)
16991 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
16992 << E->getSourceRange();
16993 return ExprError();
16994 }
16995
16996 ExprResult RValueExpr = DefaultLvalueConversion(E);
16997 if (RValueExpr.isInvalid())
16998 return ExprError();
16999
17000 E = RValueExpr.get();
17001
17002 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17003 // in the non-ICE case.
17006 if (Result)
17008 if (!isa<ConstantExpr>(E))
17011
17012 if (Notes.empty())
17013 return E;
17014
17015 // If our only note is the usual "invalid subexpression" note, just point
17016 // the caret at its location rather than producing an essentially
17017 // redundant note.
17018 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17019 diag::note_invalid_subexpr_in_const_expr) {
17020 DiagLoc = Notes[0].first;
17021 Notes.clear();
17022 }
17023
17024 if (getLangOpts().CPlusPlus) {
17025 if (!Diagnoser.Suppress) {
17026 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17027 for (const PartialDiagnosticAt &Note : Notes)
17028 Diag(Note.first, Note.second);
17029 }
17030 return ExprError();
17031 }
17032
17033 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17034 for (const PartialDiagnosticAt &Note : Notes)
17035 Diag(Note.first, Note.second);
17036
17037 return E;
17038 }
17039
17040 Expr::EvalResult EvalResult;
17042 EvalResult.Diag = &Notes;
17043
17044 // Try to evaluate the expression, and produce diagnostics explaining why it's
17045 // not a constant expression as a side-effect.
17046 bool Folded =
17047 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17048 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17049 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17050
17051 if (!isa<ConstantExpr>(E))
17052 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17053
17054 // In C++11, we can rely on diagnostics being produced for any expression
17055 // which is not a constant expression. If no diagnostics were produced, then
17056 // this is a constant expression.
17057 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17058 if (Result)
17059 *Result = EvalResult.Val.getInt();
17060 return E;
17061 }
17062
17063 // If our only note is the usual "invalid subexpression" note, just point
17064 // the caret at its location rather than producing an essentially
17065 // redundant note.
17066 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17067 diag::note_invalid_subexpr_in_const_expr) {
17068 DiagLoc = Notes[0].first;
17069 Notes.clear();
17070 }
17071
17072 if (!Folded || !CanFold) {
17073 if (!Diagnoser.Suppress) {
17074 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17075 for (const PartialDiagnosticAt &Note : Notes)
17076 Diag(Note.first, Note.second);
17077 }
17078
17079 return ExprError();
17080 }
17081
17082 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17083 for (const PartialDiagnosticAt &Note : Notes)
17084 Diag(Note.first, Note.second);
17085
17086 if (Result)
17087 *Result = EvalResult.Val.getInt();
17088 return E;
17089}
17090
17091namespace {
17092 // Handle the case where we conclude a expression which we speculatively
17093 // considered to be unevaluated is actually evaluated.
17094 class TransformToPE : public TreeTransform<TransformToPE> {
17095 typedef TreeTransform<TransformToPE> BaseTransform;
17096
17097 public:
17098 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17099
17100 // Make sure we redo semantic analysis
17101 bool AlwaysRebuild() { return true; }
17102 bool ReplacingOriginal() { return true; }
17103
17104 // We need to special-case DeclRefExprs referring to FieldDecls which
17105 // are not part of a member pointer formation; normal TreeTransforming
17106 // doesn't catch this case because of the way we represent them in the AST.
17107 // FIXME: This is a bit ugly; is it really the best way to handle this
17108 // case?
17109 //
17110 // Error on DeclRefExprs referring to FieldDecls.
17111 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17112 if (isa<FieldDecl>(E->getDecl()) &&
17113 !SemaRef.isUnevaluatedContext())
17114 return SemaRef.Diag(E->getLocation(),
17115 diag::err_invalid_non_static_member_use)
17116 << E->getDecl() << E->getSourceRange();
17117
17118 return BaseTransform::TransformDeclRefExpr(E);
17119 }
17120
17121 // Exception: filter out member pointer formation
17122 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17123 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17124 return E;
17125
17126 return BaseTransform::TransformUnaryOperator(E);
17127 }
17128
17129 // The body of a lambda-expression is in a separate expression evaluation
17130 // context so never needs to be transformed.
17131 // FIXME: Ideally we wouldn't transform the closure type either, and would
17132 // just recreate the capture expressions and lambda expression.
17133 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17134 return SkipLambdaBody(E, Body);
17135 }
17136 };
17137}
17138
17140 assert(isUnevaluatedContext() &&
17141 "Should only transform unevaluated expressions");
17142 ExprEvalContexts.back().Context =
17143 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17145 return E;
17146 return TransformToPE(*this).TransformExpr(E);
17147}
17148
17150 assert(isUnevaluatedContext() &&
17151 "Should only transform unevaluated expressions");
17154 return TInfo;
17155 return TransformToPE(*this).TransformType(TInfo);
17156}
17157
17158void
17160 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17162 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17163 LambdaContextDecl, ExprContext);
17164
17165 // Discarded statements and immediate contexts nested in other
17166 // discarded statements or immediate context are themselves
17167 // a discarded statement or an immediate context, respectively.
17168 ExprEvalContexts.back().InDiscardedStatement =
17170
17171 // C++23 [expr.const]/p15
17172 // An expression or conversion is in an immediate function context if [...]
17173 // it is a subexpression of a manifestly constant-evaluated expression or
17174 // conversion.
17175 const auto &Prev = parentEvaluationContext();
17176 ExprEvalContexts.back().InImmediateFunctionContext =
17177 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17178
17179 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17180 Prev.InImmediateEscalatingFunctionContext;
17181
17182 Cleanup.reset();
17183 if (!MaybeODRUseExprs.empty())
17184 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17185}
17186
17187void
17191 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17192 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17193}
17194
17195namespace {
17196
17197const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17198 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17199 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17200 if (E->getOpcode() == UO_Deref)
17201 return CheckPossibleDeref(S, E->getSubExpr());
17202 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17203 return CheckPossibleDeref(S, E->getBase());
17204 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17205 return CheckPossibleDeref(S, E->getBase());
17206 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17207 QualType Inner;
17208 QualType Ty = E->getType();
17209 if (const auto *Ptr = Ty->getAs<PointerType>())
17210 Inner = Ptr->getPointeeType();
17211 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17212 Inner = Arr->getElementType();
17213 else
17214 return nullptr;
17215
17216 if (Inner->hasAttr(attr::NoDeref))
17217 return E;
17218 }
17219 return nullptr;
17220}
17221
17222} // namespace
17223
17225 for (const Expr *E : Rec.PossibleDerefs) {
17226 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17227 if (DeclRef) {
17228 const ValueDecl *Decl = DeclRef->getDecl();
17229 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17230 << Decl->getName() << E->getSourceRange();
17231 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17232 } else {
17233 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17234 << E->getSourceRange();
17235 }
17236 }
17237 Rec.PossibleDerefs.clear();
17238}
17239
17242 return;
17243
17244 // Note: ignoring parens here is not justified by the standard rules, but
17245 // ignoring parentheses seems like a more reasonable approach, and this only
17246 // drives a deprecation warning so doesn't affect conformance.
17247 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17248 if (BO->getOpcode() == BO_Assign) {
17249 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17250 llvm::erase(LHSs, BO->getLHS());
17251 }
17252 }
17253}
17254
17256 assert(getLangOpts().CPlusPlus20 &&
17257 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17258 "Cannot mark an immediate escalating expression outside of an "
17259 "immediate escalating context");
17260 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17261 Call && Call->getCallee()) {
17262 if (auto *DeclRef =
17263 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17264 DeclRef->setIsImmediateEscalating(true);
17265 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
17266 Ctr->setIsImmediateEscalating(true);
17267 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
17268 DeclRef->setIsImmediateEscalating(true);
17269 } else {
17270 assert(false && "expected an immediately escalating expression");
17271 }
17273 FI->FoundImmediateEscalatingExpression = true;
17274}
17275
17277 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17278 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17281 return E;
17282
17283 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17284 /// It's OK if this fails; we'll also remove this in
17285 /// HandleImmediateInvocations, but catching it here allows us to avoid
17286 /// walking the AST looking for it in simple cases.
17287 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17288 if (auto *DeclRef =
17289 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17290 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17291
17292 // C++23 [expr.const]/p16
17293 // An expression or conversion is immediate-escalating if it is not initially
17294 // in an immediate function context and it is [...] an immediate invocation
17295 // that is not a constant expression and is not a subexpression of an
17296 // immediate invocation.
17297 APValue Cached;
17298 auto CheckConstantExpressionAndKeepResult = [&]() {
17300 Expr::EvalResult Eval;
17301 Eval.Diag = &Notes;
17302 bool Res = E.get()->EvaluateAsConstantExpr(
17303 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
17304 if (Res && Notes.empty()) {
17305 Cached = std::move(Eval.Val);
17306 return true;
17307 }
17308 return false;
17309 };
17310
17311 if (!E.get()->isValueDependent() &&
17312 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17313 !CheckConstantExpressionAndKeepResult()) {
17315 return E;
17316 }
17317
17318 if (Cleanup.exprNeedsCleanups()) {
17319 // Since an immediate invocation is a full expression itself - it requires
17320 // an additional ExprWithCleanups node, but it can participate to a bigger
17321 // full expression which actually requires cleanups to be run after so
17322 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
17323 // may discard cleanups for outer expression too early.
17324
17325 // Note that ExprWithCleanups created here must always have empty cleanup
17326 // objects:
17327 // - compound literals do not create cleanup objects in C++ and immediate
17328 // invocations are C++-only.
17329 // - blocks are not allowed inside constant expressions and compiler will
17330 // issue an error if they appear there.
17331 //
17332 // Hence, in correct code any cleanup objects created inside current
17333 // evaluation context must be outside the immediate invocation.
17336 }
17337
17339 getASTContext(), E.get(),
17340 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17341 getASTContext()),
17342 /*IsImmediateInvocation*/ true);
17343 if (Cached.hasValue())
17344 Res->MoveIntoResult(Cached, getASTContext());
17345 /// Value-dependent constant expressions should not be immediately
17346 /// evaluated until they are instantiated.
17347 if (!Res->isValueDependent())
17348 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17349 return Res;
17350}
17351
17355 Expr::EvalResult Eval;
17356 Eval.Diag = &Notes;
17357 ConstantExpr *CE = Candidate.getPointer();
17358 bool Result = CE->EvaluateAsConstantExpr(
17359 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17360 if (!Result || !Notes.empty()) {
17362 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17363 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17364 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
17365 FunctionDecl *FD = nullptr;
17366 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17367 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17368 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17369 FD = Call->getConstructor();
17370 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
17371 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
17372
17373 assert(FD && FD->isImmediateFunction() &&
17374 "could not find an immediate function in this expression");
17375 if (FD->isInvalidDecl())
17376 return;
17377 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
17378 << FD << FD->isConsteval();
17379 if (auto Context =
17381 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17382 << Context->Decl;
17383 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17384 }
17385 if (!FD->isConsteval())
17387 for (auto &Note : Notes)
17388 SemaRef.Diag(Note.first, Note.second);
17389 return;
17390 }
17392}
17393
17397 struct ComplexRemove : TreeTransform<ComplexRemove> {
17399 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17402 CurrentII;
17403 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17406 4>::reverse_iterator Current)
17407 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17408 void RemoveImmediateInvocation(ConstantExpr* E) {
17409 auto It = std::find_if(CurrentII, IISet.rend(),
17411 return Elem.getPointer() == E;
17412 });
17413 // It is possible that some subexpression of the current immediate
17414 // invocation was handled from another expression evaluation context. Do
17415 // not handle the current immediate invocation if some of its
17416 // subexpressions failed before.
17417 if (It == IISet.rend()) {
17418 if (SemaRef.FailedImmediateInvocations.contains(E))
17419 CurrentII->setInt(1);
17420 } else {
17421 It->setInt(1); // Mark as deleted
17422 }
17423 }
17424 ExprResult TransformConstantExpr(ConstantExpr *E) {
17425 if (!E->isImmediateInvocation())
17426 return Base::TransformConstantExpr(E);
17427 RemoveImmediateInvocation(E);
17428 return Base::TransformExpr(E->getSubExpr());
17429 }
17430 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17431 /// we need to remove its DeclRefExpr from the DRSet.
17432 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17433 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17434 return Base::TransformCXXOperatorCallExpr(E);
17435 }
17436 /// Base::TransformUserDefinedLiteral doesn't preserve the
17437 /// UserDefinedLiteral node.
17438 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
17439 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
17440 /// here.
17441 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17442 if (!Init)
17443 return Init;
17444 /// ConstantExpr are the first layer of implicit node to be removed so if
17445 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17446 if (auto *CE = dyn_cast<ConstantExpr>(Init))
17447 if (CE->isImmediateInvocation())
17448 RemoveImmediateInvocation(CE);
17449 return Base::TransformInitializer(Init, NotCopyInit);
17450 }
17451 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17452 DRSet.erase(E);
17453 return E;
17454 }
17455 ExprResult TransformLambdaExpr(LambdaExpr *E) {
17456 // Do not rebuild lambdas to avoid creating a new type.
17457 // Lambdas have already been processed inside their eval context.
17458 return E;
17459 }
17460 bool AlwaysRebuild() { return false; }
17461 bool ReplacingOriginal() { return true; }
17462 bool AllowSkippingCXXConstructExpr() {
17463 bool Res = AllowSkippingFirstCXXConstructExpr;
17464 AllowSkippingFirstCXXConstructExpr = true;
17465 return Res;
17466 }
17467 bool AllowSkippingFirstCXXConstructExpr = true;
17468 } Transformer(SemaRef, Rec.ReferenceToConsteval,
17470
17471 /// CXXConstructExpr with a single argument are getting skipped by
17472 /// TreeTransform in some situtation because they could be implicit. This
17473 /// can only occur for the top-level CXXConstructExpr because it is used
17474 /// nowhere in the expression being transformed therefore will not be rebuilt.
17475 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17476 /// skipping the first CXXConstructExpr.
17477 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17478 Transformer.AllowSkippingFirstCXXConstructExpr = false;
17479
17480 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17481 // The result may not be usable in case of previous compilation errors.
17482 // In this case evaluation of the expression may result in crash so just
17483 // don't do anything further with the result.
17484 if (Res.isUsable()) {
17486 It->getPointer()->setSubExpr(Res.get());
17487 }
17488}
17489
17490static void
17493 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17494 Rec.ReferenceToConsteval.size() == 0) ||
17496 return;
17497
17498 /// When we have more than 1 ImmediateInvocationCandidates or previously
17499 /// failed immediate invocations, we need to check for nested
17500 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
17501 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
17502 /// invocation.
17503 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
17505
17506 /// Prevent sema calls during the tree transform from adding pointers that
17507 /// are already in the sets.
17508 llvm::SaveAndRestore DisableIITracking(
17510
17511 /// Prevent diagnostic during tree transfrom as they are duplicates
17513
17514 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17515 It != Rec.ImmediateInvocationCandidates.rend(); It++)
17516 if (!It->getInt())
17518 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17519 Rec.ReferenceToConsteval.size()) {
17520 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
17521 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17522 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17523 bool VisitDeclRefExpr(DeclRefExpr *E) {
17524 DRSet.erase(E);
17525 return DRSet.size();
17526 }
17527 } Visitor(Rec.ReferenceToConsteval);
17528 Visitor.TraverseStmt(
17529 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17530 }
17531 for (auto CE : Rec.ImmediateInvocationCandidates)
17532 if (!CE.getInt())
17534 for (auto *DR : Rec.ReferenceToConsteval) {
17535 // If the expression is immediate escalating, it is not an error;
17536 // The outer context itself becomes immediate and further errors,
17537 // if any, will be handled by DiagnoseImmediateEscalatingReason.
17538 if (DR->isImmediateEscalating())
17539 continue;
17540 auto *FD = cast<FunctionDecl>(DR->getDecl());
17541 const NamedDecl *ND = FD;
17542 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
17543 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
17544 ND = MD->getParent();
17545
17546 // C++23 [expr.const]/p16
17547 // An expression or conversion is immediate-escalating if it is not
17548 // initially in an immediate function context and it is [...] a
17549 // potentially-evaluated id-expression that denotes an immediate function
17550 // that is not a subexpression of an immediate invocation.
17551 bool ImmediateEscalating = false;
17552 bool IsPotentiallyEvaluated =
17553 Rec.Context ==
17555 Rec.Context ==
17557 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
17558 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
17559
17561 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
17562 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17563 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
17564 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
17565 if (auto Context =
17567 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17568 << Context->Decl;
17569 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17570 }
17571 if (FD->isImmediateEscalating() && !FD->isConsteval())
17573
17574 } else {
17576 }
17577 }
17578}
17579
17582 unsigned NumTypos = Rec.NumTypos;
17583
17584 if (!Rec.Lambdas.empty()) {
17586 if (!getLangOpts().CPlusPlus20 &&
17587 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17588 Rec.isUnevaluated() ||
17590 unsigned D;
17591 if (Rec.isUnevaluated()) {
17592 // C++11 [expr.prim.lambda]p2:
17593 // A lambda-expression shall not appear in an unevaluated operand
17594 // (Clause 5).
17595 D = diag::err_lambda_unevaluated_operand;
17596 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17597 // C++1y [expr.const]p2:
17598 // A conditional-expression e is a core constant expression unless the
17599 // evaluation of e, following the rules of the abstract machine, would
17600 // evaluate [...] a lambda-expression.
17601 D = diag::err_lambda_in_constant_expression;
17602 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17603 // C++17 [expr.prim.lamda]p2:
17604 // A lambda-expression shall not appear [...] in a template-argument.
17605 D = diag::err_lambda_in_invalid_context;
17606 } else
17607 llvm_unreachable("Couldn't infer lambda error message.");
17608
17609 for (const auto *L : Rec.Lambdas)
17610 Diag(L->getBeginLoc(), D);
17611 }
17612 }
17613
17614 // Append the collected materialized temporaries into previous context before
17615 // exit if the previous also is a lifetime extending context.
17616 auto &PrevRecord = parentEvaluationContext();
17618 PrevRecord.InLifetimeExtendingContext &&
17619 !Rec.ForRangeLifetimeExtendTemps.empty()) {
17620 PrevRecord.ForRangeLifetimeExtendTemps.append(
17622 }
17623
17625 HandleImmediateInvocations(*this, Rec);
17626
17627 // Warn on any volatile-qualified simple-assignments that are not discarded-
17628 // value expressions nor unevaluated operands (those cases get removed from
17629 // this list by CheckUnusedVolatileAssignment).
17630 for (auto *BO : Rec.VolatileAssignmentLHSs)
17631 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17632 << BO->getType();
17633
17634 // When are coming out of an unevaluated context, clear out any
17635 // temporaries that we may have created as part of the evaluation of
17636 // the expression in that context: they aren't relevant because they
17637 // will never be constructed.
17638 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17640 ExprCleanupObjects.end());
17641 Cleanup = Rec.ParentCleanup;
17644 // Otherwise, merge the contexts together.
17645 } else {
17647 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17648 Rec.SavedMaybeODRUseExprs.end());
17649 }
17650
17651 // Pop the current expression evaluation context off the stack.
17652 ExprEvalContexts.pop_back();
17653
17654 // The global expression evaluation context record is never popped.
17655 ExprEvalContexts.back().NumTypos += NumTypos;
17656}
17657
17659 ExprCleanupObjects.erase(
17660 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17661 ExprCleanupObjects.end());
17662 Cleanup.reset();
17663 MaybeODRUseExprs.clear();
17664}
17665
17668 if (Result.isInvalid())
17669 return ExprError();
17670 E = Result.get();
17671 if (!E->getType()->isVariablyModifiedType())
17672 return E;
17674}
17675
17676/// Are we in a context that is potentially constant evaluated per C++20
17677/// [expr.const]p12?
17679 /// C++2a [expr.const]p12:
17680 // An expression or conversion is potentially constant evaluated if it is
17681 switch (SemaRef.ExprEvalContexts.back().Context) {
17684
17685 // -- a manifestly constant-evaluated expression,
17689 // -- a potentially-evaluated expression,
17691 // -- an immediate subexpression of a braced-init-list,
17692
17693 // -- [FIXME] an expression of the form & cast-expression that occurs
17694 // within a templated entity
17695 // -- a subexpression of one of the above that is not a subexpression of
17696 // a nested unevaluated operand.
17697 return true;
17698
17701 // Expressions in this context are never evaluated.
17702 return false;
17703 }
17704 llvm_unreachable("Invalid context");
17705}
17706
17707/// Return true if this function has a calling convention that requires mangling
17708/// in the size of the parameter pack.
17710 // These manglings don't do anything on non-Windows or non-x86 platforms, so
17711 // we don't need parameter type sizes.
17712 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17713 if (!TT.isOSWindows() || !TT.isX86())
17714 return false;
17715
17716 // If this is C++ and this isn't an extern "C" function, parameters do not
17717 // need to be complete. In this case, C++ mangling will apply, which doesn't
17718 // use the size of the parameters.
17719 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17720 return false;
17721
17722 // Stdcall, fastcall, and vectorcall need this special treatment.
17723 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17724 switch (CC) {
17725 case CC_X86StdCall:
17726 case CC_X86FastCall:
17727 case CC_X86VectorCall:
17728 return true;
17729 default:
17730 break;
17731 }
17732 return false;
17733}
17734
17735/// Require that all of the parameter types of function be complete. Normally,
17736/// parameter types are only required to be complete when a function is called
17737/// or defined, but to mangle functions with certain calling conventions, the
17738/// mangler needs to know the size of the parameter list. In this situation,
17739/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17740/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17741/// result in a linker error. Clang doesn't implement this behavior, and instead
17742/// attempts to error at compile time.
17745 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17746 FunctionDecl *FD;
17747 ParmVarDecl *Param;
17748
17749 public:
17750 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17751 : FD(FD), Param(Param) {}
17752
17753 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17754 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17755 StringRef CCName;
17756 switch (CC) {
17757 case CC_X86StdCall:
17758 CCName = "stdcall";
17759 break;
17760 case CC_X86FastCall:
17761 CCName = "fastcall";
17762 break;
17763 case CC_X86VectorCall:
17764 CCName = "vectorcall";
17765 break;
17766 default:
17767 llvm_unreachable("CC does not need mangling");
17768 }
17769
17770 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
17771 << Param->getDeclName() << FD->getDeclName() << CCName;
17772 }
17773 };
17774
17775 for (ParmVarDecl *Param : FD->parameters()) {
17776 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
17777 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
17778 }
17779}
17780
17781namespace {
17782enum class OdrUseContext {
17783 /// Declarations in this context are not odr-used.
17784 None,
17785 /// Declarations in this context are formally odr-used, but this is a
17786 /// dependent context.
17787 Dependent,
17788 /// Declarations in this context are odr-used but not actually used (yet).
17789 FormallyOdrUsed,
17790 /// Declarations in this context are used.
17791 Used
17792};
17793}
17794
17795/// Are we within a context in which references to resolved functions or to
17796/// variables result in odr-use?
17797static OdrUseContext isOdrUseContext(Sema &SemaRef) {
17798 OdrUseContext Result;
17799
17800 switch (SemaRef.ExprEvalContexts.back().Context) {
17804 return OdrUseContext::None;
17805
17809 Result = OdrUseContext::Used;
17810 break;
17811
17813 Result = OdrUseContext::FormallyOdrUsed;
17814 break;
17815
17817 // A default argument formally results in odr-use, but doesn't actually
17818 // result in a use in any real sense until it itself is used.
17819 Result = OdrUseContext::FormallyOdrUsed;
17820 break;
17821 }
17822
17824 return OdrUseContext::Dependent;
17825
17826 return Result;
17827}
17828
17830 if (!Func->isConstexpr())
17831 return false;
17832
17833 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
17834 return true;
17835 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
17836 return CCD && CCD->getInheritedConstructor();
17837}
17838
17840 bool MightBeOdrUse) {
17841 assert(Func && "No function?");
17842
17843 Func->setReferenced();
17844
17845 // Recursive functions aren't really used until they're used from some other
17846 // context.
17847 bool IsRecursiveCall = CurContext == Func;
17848
17849 // C++11 [basic.def.odr]p3:
17850 // A function whose name appears as a potentially-evaluated expression is
17851 // odr-used if it is the unique lookup result or the selected member of a
17852 // set of overloaded functions [...].
17853 //
17854 // We (incorrectly) mark overload resolution as an unevaluated context, so we
17855 // can just check that here.
17856 OdrUseContext OdrUse =
17857 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
17858 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
17859 OdrUse = OdrUseContext::FormallyOdrUsed;
17860
17861 // Trivial default constructors and destructors are never actually used.
17862 // FIXME: What about other special members?
17863 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
17864 OdrUse == OdrUseContext::Used) {
17865 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
17866 if (Constructor->isDefaultConstructor())
17867 OdrUse = OdrUseContext::FormallyOdrUsed;
17868 if (isa<CXXDestructorDecl>(Func))
17869 OdrUse = OdrUseContext::FormallyOdrUsed;
17870 }
17871
17872 // C++20 [expr.const]p12:
17873 // A function [...] is needed for constant evaluation if it is [...] a
17874 // constexpr function that is named by an expression that is potentially
17875 // constant evaluated
17876 bool NeededForConstantEvaluation =
17879
17880 // Determine whether we require a function definition to exist, per
17881 // C++11 [temp.inst]p3:
17882 // Unless a function template specialization has been explicitly
17883 // instantiated or explicitly specialized, the function template
17884 // specialization is implicitly instantiated when the specialization is
17885 // referenced in a context that requires a function definition to exist.
17886 // C++20 [temp.inst]p7:
17887 // The existence of a definition of a [...] function is considered to
17888 // affect the semantics of the program if the [...] function is needed for
17889 // constant evaluation by an expression
17890 // C++20 [basic.def.odr]p10:
17891 // Every program shall contain exactly one definition of every non-inline
17892 // function or variable that is odr-used in that program outside of a
17893 // discarded statement
17894 // C++20 [special]p1:
17895 // The implementation will implicitly define [defaulted special members]
17896 // if they are odr-used or needed for constant evaluation.
17897 //
17898 // Note that we skip the implicit instantiation of templates that are only
17899 // used in unused default arguments or by recursive calls to themselves.
17900 // This is formally non-conforming, but seems reasonable in practice.
17901 bool NeedDefinition =
17902 !IsRecursiveCall &&
17903 (OdrUse == OdrUseContext::Used ||
17904 (NeededForConstantEvaluation && !Func->isPureVirtual()));
17905
17906 // C++14 [temp.expl.spec]p6:
17907 // If a template [...] is explicitly specialized then that specialization
17908 // shall be declared before the first use of that specialization that would
17909 // cause an implicit instantiation to take place, in every translation unit
17910 // in which such a use occurs
17911 if (NeedDefinition &&
17912 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
17913 Func->getMemberSpecializationInfo()))
17915
17916 if (getLangOpts().CUDA)
17917 CUDA().CheckCall(Loc, Func);
17918
17919 // If we need a definition, try to create one.
17920 if (NeedDefinition && !Func->getBody()) {
17922 if (CXXConstructorDecl *Constructor =
17923 dyn_cast<CXXConstructorDecl>(Func)) {
17924 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
17925 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
17926 if (Constructor->isDefaultConstructor()) {
17927 if (Constructor->isTrivial() &&
17928 !Constructor->hasAttr<DLLExportAttr>())
17929 return;
17931 } else if (Constructor->isCopyConstructor()) {
17932 DefineImplicitCopyConstructor(Loc, Constructor);
17933 } else if (Constructor->isMoveConstructor()) {
17934 DefineImplicitMoveConstructor(Loc, Constructor);
17935 }
17936 } else if (Constructor->getInheritedConstructor()) {
17937 DefineInheritingConstructor(Loc, Constructor);
17938 }
17939 } else if (CXXDestructorDecl *Destructor =
17940 dyn_cast<CXXDestructorDecl>(Func)) {
17941 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
17942 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
17943 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
17944 return;
17946 }
17947 if (Destructor->isVirtual() && getLangOpts().AppleKext)
17948 MarkVTableUsed(Loc, Destructor->getParent());
17949 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
17950 if (MethodDecl->isOverloadedOperator() &&
17951 MethodDecl->getOverloadedOperator() == OO_Equal) {
17952 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
17953 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
17954 if (MethodDecl->isCopyAssignmentOperator())
17955 DefineImplicitCopyAssignment(Loc, MethodDecl);
17956 else if (MethodDecl->isMoveAssignmentOperator())
17957 DefineImplicitMoveAssignment(Loc, MethodDecl);
17958 }
17959 } else if (isa<CXXConversionDecl>(MethodDecl) &&
17960 MethodDecl->getParent()->isLambda()) {
17961 CXXConversionDecl *Conversion =
17962 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
17963 if (Conversion->isLambdaToBlockPointerConversion())
17965 else
17967 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
17968 MarkVTableUsed(Loc, MethodDecl->getParent());
17969 }
17970
17971 if (Func->isDefaulted() && !Func->isDeleted()) {
17975 }
17976
17977 // Implicit instantiation of function templates and member functions of
17978 // class templates.
17979 if (Func->isImplicitlyInstantiable()) {
17981 Func->getTemplateSpecializationKindForInstantiation();
17982 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
17983 bool FirstInstantiation = PointOfInstantiation.isInvalid();
17984 if (FirstInstantiation) {
17985 PointOfInstantiation = Loc;
17986 if (auto *MSI = Func->getMemberSpecializationInfo())
17987 MSI->setPointOfInstantiation(Loc);
17988 // FIXME: Notify listener.
17989 else
17990 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
17991 } else if (TSK != TSK_ImplicitInstantiation) {
17992 // Use the point of use as the point of instantiation, instead of the
17993 // point of explicit instantiation (which we track as the actual point
17994 // of instantiation). This gives better backtraces in diagnostics.
17995 PointOfInstantiation = Loc;
17996 }
17997
17998 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
17999 Func->isConstexpr()) {
18000 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18001 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18002 CodeSynthesisContexts.size())
18004 std::make_pair(Func, PointOfInstantiation));
18005 else if (Func->isConstexpr())
18006 // Do not defer instantiations of constexpr functions, to avoid the
18007 // expression evaluator needing to call back into Sema if it sees a
18008 // call to such a function.
18009 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18010 else {
18011 Func->setInstantiationIsPending(true);
18012 PendingInstantiations.push_back(
18013 std::make_pair(Func, PointOfInstantiation));
18014 // Notify the consumer that a function was implicitly instantiated.
18016 }
18017 }
18018 } else {
18019 // Walk redefinitions, as some of them may be instantiable.
18020 for (auto *i : Func->redecls()) {
18021 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18022 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18023 }
18024 }
18025 });
18026 }
18027
18028 // If a constructor was defined in the context of a default parameter
18029 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18030 // context), its initializers may not be referenced yet.
18031 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18033 *this,
18034 Constructor->isImmediateFunction()
18037 Constructor);
18038 for (CXXCtorInitializer *Init : Constructor->inits()) {
18039 if (Init->isInClassMemberInitializer())
18040 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18041 MarkDeclarationsReferencedInExpr(Init->getInit());
18042 });
18043 }
18044 }
18045
18046 // C++14 [except.spec]p17:
18047 // An exception-specification is considered to be needed when:
18048 // - the function is odr-used or, if it appears in an unevaluated operand,
18049 // would be odr-used if the expression were potentially-evaluated;
18050 //
18051 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18052 // function is a pure virtual function we're calling, and in that case the
18053 // function was selected by overload resolution and we need to resolve its
18054 // exception specification for a different reason.
18055 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18058
18059 // A callee could be called by a host function then by a device function.
18060 // If we only try recording once, we will miss recording the use on device
18061 // side. Therefore keep trying until it is recorded.
18062 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18065
18066 // If this is the first "real" use, act on that.
18067 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18068 // Keep track of used but undefined functions.
18069 if (!Func->isDefined()) {
18070 if (mightHaveNonExternalLinkage(Func))
18071 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18072 else if (Func->getMostRecentDecl()->isInlined() &&
18073 !LangOpts.GNUInline &&
18074 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18075 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18077 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18078 }
18079
18080 // Some x86 Windows calling conventions mangle the size of the parameter
18081 // pack into the name. Computing the size of the parameters requires the
18082 // parameter types to be complete. Check that now.
18085
18086 // In the MS C++ ABI, the compiler emits destructor variants where they are
18087 // used. If the destructor is used here but defined elsewhere, mark the
18088 // virtual base destructors referenced. If those virtual base destructors
18089 // are inline, this will ensure they are defined when emitting the complete
18090 // destructor variant. This checking may be redundant if the destructor is
18091 // provided later in this TU.
18093 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18094 CXXRecordDecl *Parent = Dtor->getParent();
18095 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18097 }
18098 }
18099
18100 Func->markUsed(Context);
18101 }
18102}
18103
18104/// Directly mark a variable odr-used. Given a choice, prefer to use
18105/// MarkVariableReferenced since it does additional checks and then
18106/// calls MarkVarDeclODRUsed.
18107/// If the variable must be captured:
18108/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18109/// - else capture it in the DeclContext that maps to the
18110/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18111static void
18113 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18114 // Keep track of used but undefined variables.
18115 // FIXME: We shouldn't suppress this warning for static data members.
18116 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18117 assert(Var && "expected a capturable variable");
18118
18120 (!Var->isExternallyVisible() || Var->isInline() ||
18122 !(Var->isStaticDataMember() && Var->hasInit())) {
18124 if (old.isInvalid())
18125 old = Loc;
18126 }
18127 QualType CaptureType, DeclRefType;
18128 if (SemaRef.LangOpts.OpenMP)
18131 /*EllipsisLoc*/ SourceLocation(),
18132 /*BuildAndDiagnose*/ true, CaptureType,
18133 DeclRefType, FunctionScopeIndexToStopAt);
18134
18135 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18136 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18137 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18138 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18139 if (VarTarget == SemaCUDA::CVT_Host &&
18140 (UserTarget == CUDAFunctionTarget::Device ||
18141 UserTarget == CUDAFunctionTarget::HostDevice ||
18142 UserTarget == CUDAFunctionTarget::Global)) {
18143 // Diagnose ODR-use of host global variables in device functions.
18144 // Reference of device global variables in host functions is allowed
18145 // through shadow variables therefore it is not diagnosed.
18146 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18147 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18148 << /*host*/ 2 << /*variable*/ 1 << Var
18149 << llvm::to_underlying(UserTarget);
18151 Var->getType().isConstQualified()
18152 ? diag::note_cuda_const_var_unpromoted
18153 : diag::note_cuda_host_var);
18154 }
18155 } else if (VarTarget == SemaCUDA::CVT_Device &&
18156 !Var->hasAttr<CUDASharedAttr>() &&
18157 (UserTarget == CUDAFunctionTarget::Host ||
18158 UserTarget == CUDAFunctionTarget::HostDevice)) {
18159 // Record a CUDA/HIP device side variable if it is ODR-used
18160 // by host code. This is done conservatively, when the variable is
18161 // referenced in any of the following contexts:
18162 // - a non-function context
18163 // - a host function
18164 // - a host device function
18165 // This makes the ODR-use of the device side variable by host code to
18166 // be visible in the device compilation for the compiler to be able to
18167 // emit template variables instantiated by host code only and to
18168 // externalize the static device side variable ODR-used by host code.
18169 if (!Var->hasExternalStorage())
18171 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18172 (!FD || (!FD->getDescribedFunctionTemplate() &&
18176 }
18177 }
18178
18179 V->markUsed(SemaRef.Context);
18180}
18181
18184 unsigned CapturingScopeIndex) {
18185 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18186}
18187
18189 ValueDecl *var) {
18190 DeclContext *VarDC = var->getDeclContext();
18191
18192 // If the parameter still belongs to the translation unit, then
18193 // we're actually just using one parameter in the declaration of
18194 // the next.
18195 if (isa<ParmVarDecl>(var) &&
18196 isa<TranslationUnitDecl>(VarDC))
18197 return;
18198
18199 // For C code, don't diagnose about capture if we're not actually in code
18200 // right now; it's impossible to write a non-constant expression outside of
18201 // function context, so we'll get other (more useful) diagnostics later.
18202 //
18203 // For C++, things get a bit more nasty... it would be nice to suppress this
18204 // diagnostic for certain cases like using a local variable in an array bound
18205 // for a member of a local class, but the correct predicate is not obvious.
18206 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18207 return;
18208
18209 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18210 unsigned ContextKind = 3; // unknown
18211 if (isa<CXXMethodDecl>(VarDC) &&
18212 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18213 ContextKind = 2;
18214 } else if (isa<FunctionDecl>(VarDC)) {
18215 ContextKind = 0;
18216 } else if (isa<BlockDecl>(VarDC)) {
18217 ContextKind = 1;
18218 }
18219
18220 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18221 << var << ValueKind << ContextKind << VarDC;
18222 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18223 << var;
18224
18225 // FIXME: Add additional diagnostic info about class etc. which prevents
18226 // capture.
18227}
18228
18230 ValueDecl *Var,
18231 bool &SubCapturesAreNested,
18232 QualType &CaptureType,
18233 QualType &DeclRefType) {
18234 // Check whether we've already captured it.
18235 if (CSI->CaptureMap.count(Var)) {
18236 // If we found a capture, any subcaptures are nested.
18237 SubCapturesAreNested = true;
18238
18239 // Retrieve the capture type for this variable.
18240 CaptureType = CSI->getCapture(Var).getCaptureType();
18241
18242 // Compute the type of an expression that refers to this variable.
18243 DeclRefType = CaptureType.getNonReferenceType();
18244
18245 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18246 // are mutable in the sense that user can change their value - they are
18247 // private instances of the captured declarations.
18248 const Capture &Cap = CSI->getCapture(Var);
18249 if (Cap.isCopyCapture() &&
18250 !(isa<LambdaScopeInfo>(CSI) &&
18251 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
18252 !(isa<CapturedRegionScopeInfo>(CSI) &&
18253 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18254 DeclRefType.addConst();
18255 return true;
18256 }
18257 return false;
18258}
18259
18260// Only block literals, captured statements, and lambda expressions can
18261// capture; other scopes don't work.
18263 ValueDecl *Var,
18265 const bool Diagnose,
18266 Sema &S) {
18267 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18269
18270 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18271 if (Underlying) {
18272 if (Underlying->hasLocalStorage() && Diagnose)
18274 }
18275 return nullptr;
18276}
18277
18278// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18279// certain types of variables (unnamed, variably modified types etc.)
18280// so check for eligibility.
18282 SourceLocation Loc, const bool Diagnose,
18283 Sema &S) {
18284
18285 assert((isa<VarDecl, BindingDecl>(Var)) &&
18286 "Only variables and structured bindings can be captured");
18287
18288 bool IsBlock = isa<BlockScopeInfo>(CSI);
18289 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18290
18291 // Lambdas are not allowed to capture unnamed variables
18292 // (e.g. anonymous unions).
18293 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18294 // assuming that's the intent.
18295 if (IsLambda && !Var->getDeclName()) {
18296 if (Diagnose) {
18297 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18298 S.Diag(Var->getLocation(), diag::note_declared_at);
18299 }
18300 return false;
18301 }
18302
18303 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18304 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18305 if (Diagnose) {
18306 S.Diag(Loc, diag::err_ref_vm_type);
18307 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18308 }
18309 return false;
18310 }
18311 // Prohibit structs with flexible array members too.
18312 // We cannot capture what is in the tail end of the struct.
18313 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18314 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18315 if (Diagnose) {
18316 if (IsBlock)
18317 S.Diag(Loc, diag::err_ref_flexarray_type);
18318 else
18319 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18320 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18321 }
18322 return false;
18323 }
18324 }
18325 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18326 // Lambdas and captured statements are not allowed to capture __block
18327 // variables; they don't support the expected semantics.
18328 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18329 if (Diagnose) {
18330 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18331 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18332 }
18333 return false;
18334 }
18335 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18336 if (S.getLangOpts().OpenCL && IsBlock &&
18337 Var->getType()->isBlockPointerType()) {
18338 if (Diagnose)
18339 S.Diag(Loc, diag::err_opencl_block_ref_block);
18340 return false;
18341 }
18342
18343 if (isa<BindingDecl>(Var)) {
18344 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18345 if (Diagnose)
18347 return false;
18348 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18349 S.Diag(Loc, S.LangOpts.CPlusPlus20
18350 ? diag::warn_cxx17_compat_capture_binding
18351 : diag::ext_capture_binding)
18352 << Var;
18353 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18354 }
18355 }
18356
18357 return true;
18358}
18359
18360// Returns true if the capture by block was successful.
18362 SourceLocation Loc, const bool BuildAndDiagnose,
18363 QualType &CaptureType, QualType &DeclRefType,
18364 const bool Nested, Sema &S, bool Invalid) {
18365 bool ByRef = false;
18366
18367 // Blocks are not allowed to capture arrays, excepting OpenCL.
18368 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18369 // (decayed to pointers).
18370 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18371 if (BuildAndDiagnose) {
18372 S.Diag(Loc, diag::err_ref_array_type);
18373 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18374 Invalid = true;
18375 } else {
18376 return false;
18377 }
18378 }
18379
18380 // Forbid the block-capture of autoreleasing variables.
18381 if (!Invalid &&
18383 if (BuildAndDiagnose) {
18384 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18385 << /*block*/ 0;
18386 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18387 Invalid = true;
18388 } else {
18389 return false;
18390 }
18391 }
18392
18393 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18394 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18395 QualType PointeeTy = PT->getPointeeType();
18396
18397 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18399 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18400 if (BuildAndDiagnose) {
18401 SourceLocation VarLoc = Var->getLocation();
18402 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18403 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18404 }
18405 }
18406 }
18407
18408 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18409 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18410 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
18411 // Block capture by reference does not change the capture or
18412 // declaration reference types.
18413 ByRef = true;
18414 } else {
18415 // Block capture by copy introduces 'const'.
18416 CaptureType = CaptureType.getNonReferenceType().withConst();
18417 DeclRefType = CaptureType;
18418 }
18419
18420 // Actually capture the variable.
18421 if (BuildAndDiagnose)
18422 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18423 CaptureType, Invalid);
18424
18425 return !Invalid;
18426}
18427
18428/// Capture the given variable in the captured region.
18431 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18432 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18433 bool IsTopScope, Sema &S, bool Invalid) {
18434 // By default, capture variables by reference.
18435 bool ByRef = true;
18436 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18437 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18438 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18439 // Using an LValue reference type is consistent with Lambdas (see below).
18440 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
18441 bool HasConst = DeclRefType.isConstQualified();
18442 DeclRefType = DeclRefType.getUnqualifiedType();
18443 // Don't lose diagnostics about assignments to const.
18444 if (HasConst)
18445 DeclRefType.addConst();
18446 }
18447 // Do not capture firstprivates in tasks.
18448 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
18449 RSI->OpenMPCaptureLevel) != OMPC_unknown)
18450 return true;
18451 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18452 RSI->OpenMPCaptureLevel);
18453 }
18454
18455 if (ByRef)
18456 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18457 else
18458 CaptureType = DeclRefType;
18459
18460 // Actually capture the variable.
18461 if (BuildAndDiagnose)
18462 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18463 Loc, SourceLocation(), CaptureType, Invalid);
18464
18465 return !Invalid;
18466}
18467
18468/// Capture the given variable in the lambda.
18470 SourceLocation Loc, const bool BuildAndDiagnose,
18471 QualType &CaptureType, QualType &DeclRefType,
18472 const bool RefersToCapturedVariable,
18473 const Sema::TryCaptureKind Kind,
18474 SourceLocation EllipsisLoc, const bool IsTopScope,
18475 Sema &S, bool Invalid) {
18476 // Determine whether we are capturing by reference or by value.
18477 bool ByRef = false;
18478 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18479 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18480 } else {
18481 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18482 }
18483
18484 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
18486 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
18487 Invalid = true;
18488 }
18489
18490 // Compute the type of the field that will capture this variable.
18491 if (ByRef) {
18492 // C++11 [expr.prim.lambda]p15:
18493 // An entity is captured by reference if it is implicitly or
18494 // explicitly captured but not captured by copy. It is
18495 // unspecified whether additional unnamed non-static data
18496 // members are declared in the closure type for entities
18497 // captured by reference.
18498 //
18499 // FIXME: It is not clear whether we want to build an lvalue reference
18500 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18501 // to do the former, while EDG does the latter. Core issue 1249 will
18502 // clarify, but for now we follow GCC because it's a more permissive and
18503 // easily defensible position.
18504 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18505 } else {
18506 // C++11 [expr.prim.lambda]p14:
18507 // For each entity captured by copy, an unnamed non-static
18508 // data member is declared in the closure type. The
18509 // declaration order of these members is unspecified. The type
18510 // of such a data member is the type of the corresponding
18511 // captured entity if the entity is not a reference to an
18512 // object, or the referenced type otherwise. [Note: If the
18513 // captured entity is a reference to a function, the
18514 // corresponding data member is also a reference to a
18515 // function. - end note ]
18516 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18517 if (!RefType->getPointeeType()->isFunctionType())
18518 CaptureType = RefType->getPointeeType();
18519 }
18520
18521 // Forbid the lambda copy-capture of autoreleasing variables.
18522 if (!Invalid &&
18524 if (BuildAndDiagnose) {
18525 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18526 S.Diag(Var->getLocation(), diag::note_previous_decl)
18527 << Var->getDeclName();
18528 Invalid = true;
18529 } else {
18530 return false;
18531 }
18532 }
18533
18534 // Make sure that by-copy captures are of a complete and non-abstract type.
18535 if (!Invalid && BuildAndDiagnose) {
18536 if (!CaptureType->isDependentType() &&
18538 Loc, CaptureType,
18539 diag::err_capture_of_incomplete_or_sizeless_type,
18540 Var->getDeclName()))
18541 Invalid = true;
18542 else if (S.RequireNonAbstractType(Loc, CaptureType,
18543 diag::err_capture_of_abstract_type))
18544 Invalid = true;
18545 }
18546 }
18547
18548 // Compute the type of a reference to this captured variable.
18549 if (ByRef)
18550 DeclRefType = CaptureType.getNonReferenceType();
18551 else {
18552 // C++ [expr.prim.lambda]p5:
18553 // The closure type for a lambda-expression has a public inline
18554 // function call operator [...]. This function call operator is
18555 // declared const (9.3.1) if and only if the lambda-expression's
18556 // parameter-declaration-clause is not followed by mutable.
18557 DeclRefType = CaptureType.getNonReferenceType();
18558 bool Const = LSI->lambdaCaptureShouldBeConst();
18559 if (Const && !CaptureType->isReferenceType())
18560 DeclRefType.addConst();
18561 }
18562
18563 // Add the capture.
18564 if (BuildAndDiagnose)
18565 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18566 Loc, EllipsisLoc, CaptureType, Invalid);
18567
18568 return !Invalid;
18569}
18570
18572 const ASTContext &Context) {
18573 // Offer a Copy fix even if the type is dependent.
18574 if (Var->getType()->isDependentType())
18575 return true;
18577 if (T.isTriviallyCopyableType(Context))
18578 return true;
18579 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18580
18581 if (!(RD = RD->getDefinition()))
18582 return false;
18583 if (RD->hasSimpleCopyConstructor())
18584 return true;
18585 if (RD->hasUserDeclaredCopyConstructor())
18586 for (CXXConstructorDecl *Ctor : RD->ctors())
18587 if (Ctor->isCopyConstructor())
18588 return !Ctor->isDeleted();
18589 }
18590 return false;
18591}
18592
18593/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18594/// default capture. Fixes may be omitted if they aren't allowed by the
18595/// standard, for example we can't emit a default copy capture fix-it if we
18596/// already explicitly copy capture capture another variable.
18598 ValueDecl *Var) {
18600 // Don't offer Capture by copy of default capture by copy fixes if Var is
18601 // known not to be copy constructible.
18602 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18603
18604 SmallString<32> FixBuffer;
18605 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18606 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18607 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18608 if (ShouldOfferCopyFix) {
18609 // Offer fixes to insert an explicit capture for the variable.
18610 // [] -> [VarName]
18611 // [OtherCapture] -> [OtherCapture, VarName]
18612 FixBuffer.assign({Separator, Var->getName()});
18613 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18614 << Var << /*value*/ 0
18615 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18616 }
18617 // As above but capture by reference.
18618 FixBuffer.assign({Separator, "&", Var->getName()});
18619 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18620 << Var << /*reference*/ 1
18621 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18622 }
18623
18624 // Only try to offer default capture if there are no captures excluding this
18625 // and init captures.
18626 // [this]: OK.
18627 // [X = Y]: OK.
18628 // [&A, &B]: Don't offer.
18629 // [A, B]: Don't offer.
18630 if (llvm::any_of(LSI->Captures, [](Capture &C) {
18631 return !C.isThisCapture() && !C.isInitCapture();
18632 }))
18633 return;
18634
18635 // The default capture specifiers, '=' or '&', must appear first in the
18636 // capture body.
18637 SourceLocation DefaultInsertLoc =
18639
18640 if (ShouldOfferCopyFix) {
18641 bool CanDefaultCopyCapture = true;
18642 // [=, *this] OK since c++17
18643 // [=, this] OK since c++20
18644 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18645 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18647 : false;
18648 // We can't use default capture by copy if any captures already specified
18649 // capture by copy.
18650 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18651 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18652 })) {
18653 FixBuffer.assign({"=", Separator});
18654 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18655 << /*value*/ 0
18656 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18657 }
18658 }
18659
18660 // We can't use default capture by reference if any captures already specified
18661 // capture by reference.
18662 if (llvm::none_of(LSI->Captures, [](Capture &C) {
18663 return !C.isInitCapture() && C.isReferenceCapture() &&
18664 !C.isThisCapture();
18665 })) {
18666 FixBuffer.assign({"&", Separator});
18667 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18668 << /*reference*/ 1
18669 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18670 }
18671}
18672
18674 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18675 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18676 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18677 // An init-capture is notionally from the context surrounding its
18678 // declaration, but its parent DC is the lambda class.
18679 DeclContext *VarDC = Var->getDeclContext();
18680 DeclContext *DC = CurContext;
18681
18682 // Skip past RequiresExprBodys because they don't constitute function scopes.
18683 while (DC->isRequiresExprBody())
18684 DC = DC->getParent();
18685
18686 // tryCaptureVariable is called every time a DeclRef is formed,
18687 // it can therefore have non-negigible impact on performances.
18688 // For local variables and when there is no capturing scope,
18689 // we can bailout early.
18690 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
18691 return true;
18692
18693 // Exception: Function parameters are not tied to the function's DeclContext
18694 // until we enter the function definition. Capturing them anyway would result
18695 // in an out-of-bounds error while traversing DC and its parents.
18696 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
18697 return true;
18698
18699 const auto *VD = dyn_cast<VarDecl>(Var);
18700 if (VD) {
18701 if (VD->isInitCapture())
18702 VarDC = VarDC->getParent();
18703 } else {
18705 }
18706 assert(VD && "Cannot capture a null variable");
18707
18708 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18709 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18710 // We need to sync up the Declaration Context with the
18711 // FunctionScopeIndexToStopAt
18712 if (FunctionScopeIndexToStopAt) {
18713 unsigned FSIndex = FunctionScopes.size() - 1;
18714 while (FSIndex != MaxFunctionScopesIndex) {
18716 --FSIndex;
18717 }
18718 }
18719
18720 // Capture global variables if it is required to use private copy of this
18721 // variable.
18722 bool IsGlobal = !VD->hasLocalStorage();
18723 if (IsGlobal && !(LangOpts.OpenMP &&
18724 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18725 MaxFunctionScopesIndex)))
18726 return true;
18727
18728 if (isa<VarDecl>(Var))
18729 Var = cast<VarDecl>(Var->getCanonicalDecl());
18730
18731 // Walk up the stack to determine whether we can capture the variable,
18732 // performing the "simple" checks that don't depend on type. We stop when
18733 // we've either hit the declared scope of the variable or find an existing
18734 // capture of that variable. We start from the innermost capturing-entity
18735 // (the DC) and ensure that all intervening capturing-entities
18736 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
18737 // declcontext can either capture the variable or have already captured
18738 // the variable.
18739 CaptureType = Var->getType();
18740 DeclRefType = CaptureType.getNonReferenceType();
18741 bool Nested = false;
18742 bool Explicit = (Kind != TryCapture_Implicit);
18743 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
18744 do {
18745
18746 LambdaScopeInfo *LSI = nullptr;
18747 if (!FunctionScopes.empty())
18748 LSI = dyn_cast_or_null<LambdaScopeInfo>(
18749 FunctionScopes[FunctionScopesIndex]);
18750
18751 bool IsInScopeDeclarationContext =
18752 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
18753
18754 if (LSI && !LSI->AfterParameterList) {
18755 // This allows capturing parameters from a default value which does not
18756 // seems correct
18757 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
18758 return true;
18759 }
18760 // If the variable is declared in the current context, there is no need to
18761 // capture it.
18762 if (IsInScopeDeclarationContext &&
18763 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
18764 return true;
18765
18766 // Only block literals, captured statements, and lambda expressions can
18767 // capture; other scopes don't work.
18768 DeclContext *ParentDC =
18769 !IsInScopeDeclarationContext
18770 ? DC->getParent()
18771 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
18772 BuildAndDiagnose, *this);
18773 // We need to check for the parent *first* because, if we *have*
18774 // private-captured a global variable, we need to recursively capture it in
18775 // intermediate blocks, lambdas, etc.
18776 if (!ParentDC) {
18777 if (IsGlobal) {
18778 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
18779 break;
18780 }
18781 return true;
18782 }
18783
18784 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
18785 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
18786
18787 // Check whether we've already captured it.
18788 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
18789 DeclRefType)) {
18790 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
18791 break;
18792 }
18793
18794 // When evaluating some attributes (like enable_if) we might refer to a
18795 // function parameter appertaining to the same declaration as that
18796 // attribute.
18797 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
18798 Parm && Parm->getDeclContext() == DC)
18799 return true;
18800
18801 // If we are instantiating a generic lambda call operator body,
18802 // we do not want to capture new variables. What was captured
18803 // during either a lambdas transformation or initial parsing
18804 // should be used.
18806 if (BuildAndDiagnose) {
18807 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18809 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18810 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18811 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18812 buildLambdaCaptureFixit(*this, LSI, Var);
18813 } else
18815 }
18816 return true;
18817 }
18818
18819 // Try to capture variable-length arrays types.
18820 if (Var->getType()->isVariablyModifiedType()) {
18821 // We're going to walk down into the type and look for VLA
18822 // expressions.
18823 QualType QTy = Var->getType();
18824 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18825 QTy = PVD->getOriginalType();
18827 }
18828
18829 if (getLangOpts().OpenMP) {
18830 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18831 // OpenMP private variables should not be captured in outer scope, so
18832 // just break here. Similarly, global variables that are captured in a
18833 // target region should not be captured outside the scope of the region.
18834 if (RSI->CapRegionKind == CR_OpenMP) {
18835 // FIXME: We should support capturing structured bindings in OpenMP.
18836 if (isa<BindingDecl>(Var)) {
18837 if (BuildAndDiagnose) {
18838 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
18839 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18840 }
18841 return true;
18842 }
18843 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
18844 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18845 // If the variable is private (i.e. not captured) and has variably
18846 // modified type, we still need to capture the type for correct
18847 // codegen in all regions, associated with the construct. Currently,
18848 // it is captured in the innermost captured region only.
18849 if (IsOpenMPPrivateDecl != OMPC_unknown &&
18850 Var->getType()->isVariablyModifiedType()) {
18851 QualType QTy = Var->getType();
18852 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
18853 QTy = PVD->getOriginalType();
18854 for (int I = 1,
18855 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
18856 I < E; ++I) {
18857 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
18858 FunctionScopes[FunctionScopesIndex - I]);
18859 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
18860 "Wrong number of captured regions associated with the "
18861 "OpenMP construct.");
18862 captureVariablyModifiedType(Context, QTy, OuterRSI);
18863 }
18864 }
18865 bool IsTargetCap =
18866 IsOpenMPPrivateDecl != OMPC_private &&
18867 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
18868 RSI->OpenMPCaptureLevel);
18869 // Do not capture global if it is not privatized in outer regions.
18870 bool IsGlobalCap =
18871 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
18872 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
18873
18874 // When we detect target captures we are looking from inside the
18875 // target region, therefore we need to propagate the capture from the
18876 // enclosing region. Therefore, the capture is not initially nested.
18877 if (IsTargetCap)
18878 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
18879 RSI->OpenMPLevel);
18880
18881 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
18882 (IsGlobal && !IsGlobalCap)) {
18883 Nested = !IsTargetCap;
18884 bool HasConst = DeclRefType.isConstQualified();
18885 DeclRefType = DeclRefType.getUnqualifiedType();
18886 // Don't lose diagnostics about assignments to const.
18887 if (HasConst)
18888 DeclRefType.addConst();
18889 CaptureType = Context.getLValueReferenceType(DeclRefType);
18890 break;
18891 }
18892 }
18893 }
18894 }
18895 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
18896 // No capture-default, and this is not an explicit capture
18897 // so cannot capture this variable.
18898 if (BuildAndDiagnose) {
18899 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
18900 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18901 auto *LSI = cast<LambdaScopeInfo>(CSI);
18902 if (LSI->Lambda) {
18903 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
18904 buildLambdaCaptureFixit(*this, LSI, Var);
18905 }
18906 // FIXME: If we error out because an outer lambda can not implicitly
18907 // capture a variable that an inner lambda explicitly captures, we
18908 // should have the inner lambda do the explicit capture - because
18909 // it makes for cleaner diagnostics later. This would purely be done
18910 // so that the diagnostic does not misleadingly claim that a variable
18911 // can not be captured by a lambda implicitly even though it is captured
18912 // explicitly. Suggestion:
18913 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
18914 // at the function head
18915 // - cache the StartingDeclContext - this must be a lambda
18916 // - captureInLambda in the innermost lambda the variable.
18917 }
18918 return true;
18919 }
18920 Explicit = false;
18921 FunctionScopesIndex--;
18922 if (IsInScopeDeclarationContext)
18923 DC = ParentDC;
18924 } while (!VarDC->Equals(DC));
18925
18926 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
18927 // computing the type of the capture at each step, checking type-specific
18928 // requirements, and adding captures if requested.
18929 // If the variable had already been captured previously, we start capturing
18930 // at the lambda nested within that one.
18931 bool Invalid = false;
18932 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
18933 ++I) {
18934 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
18935
18936 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18937 // certain types of variables (unnamed, variably modified types etc.)
18938 // so check for eligibility.
18939 if (!Invalid)
18940 Invalid =
18941 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
18942
18943 // After encountering an error, if we're actually supposed to capture, keep
18944 // capturing in nested contexts to suppress any follow-on diagnostics.
18945 if (Invalid && !BuildAndDiagnose)
18946 return true;
18947
18948 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
18949 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18950 DeclRefType, Nested, *this, Invalid);
18951 Nested = true;
18952 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
18954 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
18955 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
18956 Nested = true;
18957 } else {
18958 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
18959 Invalid =
18960 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
18961 DeclRefType, Nested, Kind, EllipsisLoc,
18962 /*IsTopScope*/ I == N - 1, *this, Invalid);
18963 Nested = true;
18964 }
18965
18966 if (Invalid && !BuildAndDiagnose)
18967 return true;
18968 }
18969 return Invalid;
18970}
18971
18973 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
18974 QualType CaptureType;
18975 QualType DeclRefType;
18976 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
18977 /*BuildAndDiagnose=*/true, CaptureType,
18978 DeclRefType, nullptr);
18979}
18980
18982 QualType CaptureType;
18983 QualType DeclRefType;
18985 /*BuildAndDiagnose=*/false, CaptureType,
18986 DeclRefType, nullptr);
18987}
18988
18990 QualType CaptureType;
18991 QualType DeclRefType;
18992
18993 // Determine whether we can capture this variable.
18995 /*BuildAndDiagnose=*/false, CaptureType,
18996 DeclRefType, nullptr))
18997 return QualType();
18998
18999 return DeclRefType;
19000}
19001
19002namespace {
19003// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19004// The produced TemplateArgumentListInfo* points to data stored within this
19005// object, so should only be used in contexts where the pointer will not be
19006// used after the CopiedTemplateArgs object is destroyed.
19007class CopiedTemplateArgs {
19008 bool HasArgs;
19009 TemplateArgumentListInfo TemplateArgStorage;
19010public:
19011 template<typename RefExpr>
19012 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19013 if (HasArgs)
19014 E->copyTemplateArgumentsInto(TemplateArgStorage);
19015 }
19016 operator TemplateArgumentListInfo*()
19017#ifdef __has_cpp_attribute
19018#if __has_cpp_attribute(clang::lifetimebound)
19019 [[clang::lifetimebound]]
19020#endif
19021#endif
19022 {
19023 return HasArgs ? &TemplateArgStorage : nullptr;
19024 }
19025};
19026}
19027
19028/// Walk the set of potential results of an expression and mark them all as
19029/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19030///
19031/// \return A new expression if we found any potential results, ExprEmpty() if
19032/// not, and ExprError() if we diagnosed an error.
19034 NonOdrUseReason NOUR) {
19035 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19036 // an object that satisfies the requirements for appearing in a
19037 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19038 // is immediately applied." This function handles the lvalue-to-rvalue
19039 // conversion part.
19040 //
19041 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19042 // transform it into the relevant kind of non-odr-use node and rebuild the
19043 // tree of nodes leading to it.
19044 //
19045 // This is a mini-TreeTransform that only transforms a restricted subset of
19046 // nodes (and only certain operands of them).
19047
19048 // Rebuild a subexpression.
19049 auto Rebuild = [&](Expr *Sub) {
19050 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19051 };
19052
19053 // Check whether a potential result satisfies the requirements of NOUR.
19054 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19055 // Any entity other than a VarDecl is always odr-used whenever it's named
19056 // in a potentially-evaluated expression.
19057 auto *VD = dyn_cast<VarDecl>(D);
19058 if (!VD)
19059 return true;
19060
19061 // C++2a [basic.def.odr]p4:
19062 // A variable x whose name appears as a potentially-evalauted expression
19063 // e is odr-used by e unless
19064 // -- x is a reference that is usable in constant expressions, or
19065 // -- x is a variable of non-reference type that is usable in constant
19066 // expressions and has no mutable subobjects, and e is an element of
19067 // the set of potential results of an expression of
19068 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19069 // conversion is applied, or
19070 // -- x is a variable of non-reference type, and e is an element of the
19071 // set of potential results of a discarded-value expression to which
19072 // the lvalue-to-rvalue conversion is not applied
19073 //
19074 // We check the first bullet and the "potentially-evaluated" condition in
19075 // BuildDeclRefExpr. We check the type requirements in the second bullet
19076 // in CheckLValueToRValueConversionOperand below.
19077 switch (NOUR) {
19078 case NOUR_None:
19079 case NOUR_Unevaluated:
19080 llvm_unreachable("unexpected non-odr-use-reason");
19081
19082 case NOUR_Constant:
19083 // Constant references were handled when they were built.
19084 if (VD->getType()->isReferenceType())
19085 return true;
19086 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19087 if (RD->hasMutableFields())
19088 return true;
19089 if (!VD->isUsableInConstantExpressions(S.Context))
19090 return true;
19091 break;
19092
19093 case NOUR_Discarded:
19094 if (VD->getType()->isReferenceType())
19095 return true;
19096 break;
19097 }
19098 return false;
19099 };
19100
19101 // Mark that this expression does not constitute an odr-use.
19102 auto MarkNotOdrUsed = [&] {
19103 S.MaybeODRUseExprs.remove(E);
19104 if (LambdaScopeInfo *LSI = S.getCurLambda())
19105 LSI->markVariableExprAsNonODRUsed(E);
19106 };
19107
19108 // C++2a [basic.def.odr]p2:
19109 // The set of potential results of an expression e is defined as follows:
19110 switch (E->getStmtClass()) {
19111 // -- If e is an id-expression, ...
19112 case Expr::DeclRefExprClass: {
19113 auto *DRE = cast<DeclRefExpr>(E);
19114 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19115 break;
19116
19117 // Rebuild as a non-odr-use DeclRefExpr.
19118 MarkNotOdrUsed();
19119 return DeclRefExpr::Create(
19120 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19121 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19122 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19123 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19124 }
19125
19126 case Expr::FunctionParmPackExprClass: {
19127 auto *FPPE = cast<FunctionParmPackExpr>(E);
19128 // If any of the declarations in the pack is odr-used, then the expression
19129 // as a whole constitutes an odr-use.
19130 for (VarDecl *D : *FPPE)
19131 if (IsPotentialResultOdrUsed(D))
19132 return ExprEmpty();
19133
19134 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19135 // nothing cares about whether we marked this as an odr-use, but it might
19136 // be useful for non-compiler tools.
19137 MarkNotOdrUsed();
19138 break;
19139 }
19140
19141 // -- If e is a subscripting operation with an array operand...
19142 case Expr::ArraySubscriptExprClass: {
19143 auto *ASE = cast<ArraySubscriptExpr>(E);
19144 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19145 if (!OldBase->getType()->isArrayType())
19146 break;
19147 ExprResult Base = Rebuild(OldBase);
19148 if (!Base.isUsable())
19149 return Base;
19150 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19151 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19152 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19153 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19154 ASE->getRBracketLoc());
19155 }
19156
19157 case Expr::MemberExprClass: {
19158 auto *ME = cast<MemberExpr>(E);
19159 // -- If e is a class member access expression [...] naming a non-static
19160 // data member...
19161 if (isa<FieldDecl>(ME->getMemberDecl())) {
19162 ExprResult Base = Rebuild(ME->getBase());
19163 if (!Base.isUsable())
19164 return Base;
19165 return MemberExpr::Create(
19166 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19167 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19168 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19169 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19170 ME->getObjectKind(), ME->isNonOdrUse());
19171 }
19172
19173 if (ME->getMemberDecl()->isCXXInstanceMember())
19174 break;
19175
19176 // -- If e is a class member access expression naming a static data member,
19177 // ...
19178 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19179 break;
19180
19181 // Rebuild as a non-odr-use MemberExpr.
19182 MarkNotOdrUsed();
19183 return MemberExpr::Create(
19184 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19185 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19186 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19187 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19188 }
19189
19190 case Expr::BinaryOperatorClass: {
19191 auto *BO = cast<BinaryOperator>(E);
19192 Expr *LHS = BO->getLHS();
19193 Expr *RHS = BO->getRHS();
19194 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19195 if (BO->getOpcode() == BO_PtrMemD) {
19196 ExprResult Sub = Rebuild(LHS);
19197 if (!Sub.isUsable())
19198 return Sub;
19199 BO->setLHS(Sub.get());
19200 // -- If e is a comma expression, ...
19201 } else if (BO->getOpcode() == BO_Comma) {
19202 ExprResult Sub = Rebuild(RHS);
19203 if (!Sub.isUsable())
19204 return Sub;
19205 BO->setRHS(Sub.get());
19206 } else {
19207 break;
19208 }
19209 return ExprResult(BO);
19210 }
19211
19212 // -- If e has the form (e1)...
19213 case Expr::ParenExprClass: {
19214 auto *PE = cast<ParenExpr>(E);
19215 ExprResult Sub = Rebuild(PE->getSubExpr());
19216 if (!Sub.isUsable())
19217 return Sub;
19218 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19219 }
19220
19221 // -- If e is a glvalue conditional expression, ...
19222 // We don't apply this to a binary conditional operator. FIXME: Should we?
19223 case Expr::ConditionalOperatorClass: {
19224 auto *CO = cast<ConditionalOperator>(E);
19225 ExprResult LHS = Rebuild(CO->getLHS());
19226 if (LHS.isInvalid())
19227 return ExprError();
19228 ExprResult RHS = Rebuild(CO->getRHS());
19229 if (RHS.isInvalid())
19230 return ExprError();
19231 if (!LHS.isUsable() && !RHS.isUsable())
19232 return ExprEmpty();
19233 if (!LHS.isUsable())
19234 LHS = CO->getLHS();
19235 if (!RHS.isUsable())
19236 RHS = CO->getRHS();
19237 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19238 CO->getCond(), LHS.get(), RHS.get());
19239 }
19240
19241 // [Clang extension]
19242 // -- If e has the form __extension__ e1...
19243 case Expr::UnaryOperatorClass: {
19244 auto *UO = cast<UnaryOperator>(E);
19245 if (UO->getOpcode() != UO_Extension)
19246 break;
19247 ExprResult Sub = Rebuild(UO->getSubExpr());
19248 if (!Sub.isUsable())
19249 return Sub;
19250 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19251 Sub.get());
19252 }
19253
19254 // [Clang extension]
19255 // -- If e has the form _Generic(...), the set of potential results is the
19256 // union of the sets of potential results of the associated expressions.
19257 case Expr::GenericSelectionExprClass: {
19258 auto *GSE = cast<GenericSelectionExpr>(E);
19259
19260 SmallVector<Expr *, 4> AssocExprs;
19261 bool AnyChanged = false;
19262 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19263 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19264 if (AssocExpr.isInvalid())
19265 return ExprError();
19266 if (AssocExpr.isUsable()) {
19267 AssocExprs.push_back(AssocExpr.get());
19268 AnyChanged = true;
19269 } else {
19270 AssocExprs.push_back(OrigAssocExpr);
19271 }
19272 }
19273
19274 void *ExOrTy = nullptr;
19275 bool IsExpr = GSE->isExprPredicate();
19276 if (IsExpr)
19277 ExOrTy = GSE->getControllingExpr();
19278 else
19279 ExOrTy = GSE->getControllingType();
19280 return AnyChanged ? S.CreateGenericSelectionExpr(
19281 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19282 GSE->getRParenLoc(), IsExpr, ExOrTy,
19283 GSE->getAssocTypeSourceInfos(), AssocExprs)
19284 : ExprEmpty();
19285 }
19286
19287 // [Clang extension]
19288 // -- If e has the form __builtin_choose_expr(...), the set of potential
19289 // results is the union of the sets of potential results of the
19290 // second and third subexpressions.
19291 case Expr::ChooseExprClass: {
19292 auto *CE = cast<ChooseExpr>(E);
19293
19294 ExprResult LHS = Rebuild(CE->getLHS());
19295 if (LHS.isInvalid())
19296 return ExprError();
19297
19298 ExprResult RHS = Rebuild(CE->getLHS());
19299 if (RHS.isInvalid())
19300 return ExprError();
19301
19302 if (!LHS.get() && !RHS.get())
19303 return ExprEmpty();
19304 if (!LHS.isUsable())
19305 LHS = CE->getLHS();
19306 if (!RHS.isUsable())
19307 RHS = CE->getRHS();
19308
19309 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19310 RHS.get(), CE->getRParenLoc());
19311 }
19312
19313 // Step through non-syntactic nodes.
19314 case Expr::ConstantExprClass: {
19315 auto *CE = cast<ConstantExpr>(E);
19316 ExprResult Sub = Rebuild(CE->getSubExpr());
19317 if (!Sub.isUsable())
19318 return Sub;
19319 return ConstantExpr::Create(S.Context, Sub.get());
19320 }
19321
19322 // We could mostly rely on the recursive rebuilding to rebuild implicit
19323 // casts, but not at the top level, so rebuild them here.
19324 case Expr::ImplicitCastExprClass: {
19325 auto *ICE = cast<ImplicitCastExpr>(E);
19326 // Only step through the narrow set of cast kinds we expect to encounter.
19327 // Anything else suggests we've left the region in which potential results
19328 // can be found.
19329 switch (ICE->getCastKind()) {
19330 case CK_NoOp:
19331 case CK_DerivedToBase:
19332 case CK_UncheckedDerivedToBase: {
19333 ExprResult Sub = Rebuild(ICE->getSubExpr());
19334 if (!Sub.isUsable())
19335 return Sub;
19336 CXXCastPath Path(ICE->path());
19337 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19338 ICE->getValueKind(), &Path);
19339 }
19340
19341 default:
19342 break;
19343 }
19344 break;
19345 }
19346
19347 default:
19348 break;
19349 }
19350
19351 // Can't traverse through this node. Nothing to do.
19352 return ExprEmpty();
19353}
19354
19356 // Check whether the operand is or contains an object of non-trivial C union
19357 // type.
19358 if (E->getType().isVolatileQualified() &&
19364
19365 // C++2a [basic.def.odr]p4:
19366 // [...] an expression of non-volatile-qualified non-class type to which
19367 // the lvalue-to-rvalue conversion is applied [...]
19369 return E;
19370
19373 if (Result.isInvalid())
19374 return ExprError();
19375 return Result.get() ? Result : E;
19376}
19377
19379 Res = CorrectDelayedTyposInExpr(Res);
19380
19381 if (!Res.isUsable())
19382 return Res;
19383
19384 // If a constant-expression is a reference to a variable where we delay
19385 // deciding whether it is an odr-use, just assume we will apply the
19386 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19387 // (a non-type template argument), we have special handling anyway.
19389}
19390
19392 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19393 // call.
19394 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19395 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19396
19397 for (Expr *E : LocalMaybeODRUseExprs) {
19398 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19399 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19400 DRE->getLocation(), *this);
19401 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19402 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19403 *this);
19404 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19405 for (VarDecl *VD : *FP)
19406 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19407 } else {
19408 llvm_unreachable("Unexpected expression");
19409 }
19410 }
19411
19412 assert(MaybeODRUseExprs.empty() &&
19413 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19414}
19415
19417 ValueDecl *Var, Expr *E) {
19419 if (!VD)
19420 return;
19421
19422 const bool RefersToEnclosingScope =
19423 (SemaRef.CurContext != VD->getDeclContext() &&
19425 if (RefersToEnclosingScope) {
19426 LambdaScopeInfo *const LSI =
19427 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19428 if (LSI && (!LSI->CallOperator ||
19429 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19430 // If a variable could potentially be odr-used, defer marking it so
19431 // until we finish analyzing the full expression for any
19432 // lvalue-to-rvalue
19433 // or discarded value conversions that would obviate odr-use.
19434 // Add it to the list of potential captures that will be analyzed
19435 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19436 // unless the variable is a reference that was initialized by a constant
19437 // expression (this will never need to be captured or odr-used).
19438 //
19439 // FIXME: We can simplify this a lot after implementing P0588R1.
19440 assert(E && "Capture variable should be used in an expression.");
19441 if (!Var->getType()->isReferenceType() ||
19444 }
19445 }
19446}
19447
19450 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19451 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19452 isa<FunctionParmPackExpr>(E)) &&
19453 "Invalid Expr argument to DoMarkVarDeclReferenced");
19454 Var->setReferenced();
19455
19456 if (Var->isInvalidDecl())
19457 return;
19458
19459 auto *MSI = Var->getMemberSpecializationInfo();
19462
19463 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19464 bool UsableInConstantExpr =
19466
19467 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19468 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19469 }
19470
19471 // C++20 [expr.const]p12:
19472 // A variable [...] is needed for constant evaluation if it is [...] a
19473 // variable whose name appears as a potentially constant evaluated
19474 // expression that is either a contexpr variable or is of non-volatile
19475 // const-qualified integral type or of reference type
19476 bool NeededForConstantEvaluation =
19477 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19478
19479 bool NeedDefinition =
19480 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19481
19482 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19483 "Can't instantiate a partial template specialization.");
19484
19485 // If this might be a member specialization of a static data member, check
19486 // the specialization is visible. We already did the checks for variable
19487 // template specializations when we created them.
19488 if (NeedDefinition && TSK != TSK_Undeclared &&
19489 !isa<VarTemplateSpecializationDecl>(Var))
19491
19492 // Perform implicit instantiation of static data members, static data member
19493 // templates of class templates, and variable template specializations. Delay
19494 // instantiations of variable templates, except for those that could be used
19495 // in a constant expression.
19496 if (NeedDefinition && isTemplateInstantiation(TSK)) {
19497 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19498 // instantiation declaration if a variable is usable in a constant
19499 // expression (among other cases).
19500 bool TryInstantiating =
19502 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19503
19504 if (TryInstantiating) {
19505 SourceLocation PointOfInstantiation =
19506 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19507 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19508 if (FirstInstantiation) {
19509 PointOfInstantiation = Loc;
19510 if (MSI)
19511 MSI->setPointOfInstantiation(PointOfInstantiation);
19512 // FIXME: Notify listener.
19513 else
19514 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19515 }
19516
19517 if (UsableInConstantExpr) {
19518 // Do not defer instantiations of variables that could be used in a
19519 // constant expression.
19520 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19521 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19522 });
19523
19524 // Re-set the member to trigger a recomputation of the dependence bits
19525 // for the expression.
19526 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19527 DRE->setDecl(DRE->getDecl());
19528 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19529 ME->setMemberDecl(ME->getMemberDecl());
19530 } else if (FirstInstantiation) {
19532 .push_back(std::make_pair(Var, PointOfInstantiation));
19533 } else {
19534 bool Inserted = false;
19535 for (auto &I : SemaRef.SavedPendingInstantiations) {
19536 auto Iter = llvm::find_if(
19537 I, [Var](const Sema::PendingImplicitInstantiation &P) {
19538 return P.first == Var;
19539 });
19540 if (Iter != I.end()) {
19542 I.erase(Iter);
19543 Inserted = true;
19544 break;
19545 }
19546 }
19547
19548 // FIXME: For a specialization of a variable template, we don't
19549 // distinguish between "declaration and type implicitly instantiated"
19550 // and "implicit instantiation of definition requested", so we have
19551 // no direct way to avoid enqueueing the pending instantiation
19552 // multiple times.
19553 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
19555 .push_back(std::make_pair(Var, PointOfInstantiation));
19556 }
19557 }
19558 }
19559
19560 // C++2a [basic.def.odr]p4:
19561 // A variable x whose name appears as a potentially-evaluated expression e
19562 // is odr-used by e unless
19563 // -- x is a reference that is usable in constant expressions
19564 // -- x is a variable of non-reference type that is usable in constant
19565 // expressions and has no mutable subobjects [FIXME], and e is an
19566 // element of the set of potential results of an expression of
19567 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19568 // conversion is applied
19569 // -- x is a variable of non-reference type, and e is an element of the set
19570 // of potential results of a discarded-value expression to which the
19571 // lvalue-to-rvalue conversion is not applied [FIXME]
19572 //
19573 // We check the first part of the second bullet here, and
19574 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19575 // FIXME: To get the third bullet right, we need to delay this even for
19576 // variables that are not usable in constant expressions.
19577
19578 // If we already know this isn't an odr-use, there's nothing more to do.
19579 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19580 if (DRE->isNonOdrUse())
19581 return;
19582 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19583 if (ME->isNonOdrUse())
19584 return;
19585
19586 switch (OdrUse) {
19587 case OdrUseContext::None:
19588 // In some cases, a variable may not have been marked unevaluated, if it
19589 // appears in a defaukt initializer.
19590 assert((!E || isa<FunctionParmPackExpr>(E) ||
19592 "missing non-odr-use marking for unevaluated decl ref");
19593 break;
19594
19595 case OdrUseContext::FormallyOdrUsed:
19596 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19597 // behavior.
19598 break;
19599
19600 case OdrUseContext::Used:
19601 // If we might later find that this expression isn't actually an odr-use,
19602 // delay the marking.
19604 SemaRef.MaybeODRUseExprs.insert(E);
19605 else
19607 break;
19608
19609 case OdrUseContext::Dependent:
19610 // If this is a dependent context, we don't need to mark variables as
19611 // odr-used, but we may still need to track them for lambda capture.
19612 // FIXME: Do we also need to do this inside dependent typeid expressions
19613 // (which are modeled as unevaluated at this point)?
19615 break;
19616 }
19617}
19618
19620 BindingDecl *BD, Expr *E) {
19621 BD->setReferenced();
19622
19623 if (BD->isInvalidDecl())
19624 return;
19625
19626 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19627 if (OdrUse == OdrUseContext::Used) {
19628 QualType CaptureType, DeclRefType;
19630 /*EllipsisLoc*/ SourceLocation(),
19631 /*BuildAndDiagnose*/ true, CaptureType,
19632 DeclRefType,
19633 /*FunctionScopeIndexToStopAt*/ nullptr);
19634 } else if (OdrUse == OdrUseContext::Dependent) {
19636 }
19637}
19638
19640 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19641}
19642
19643// C++ [temp.dep.expr]p3:
19644// An id-expression is type-dependent if it contains:
19645// - an identifier associated by name lookup with an entity captured by copy
19646// in a lambda-expression that has an explicit object parameter whose type
19647// is dependent ([dcl.fct]),
19649 Sema &SemaRef, ValueDecl *D, Expr *E) {
19650 auto *ID = dyn_cast<DeclRefExpr>(E);
19651 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
19652 return;
19653
19654 // If any enclosing lambda with a dependent explicit object parameter either
19655 // explicitly captures the variable by value, or has a capture default of '='
19656 // and does not capture the variable by reference, then the type of the DRE
19657 // is dependent on the type of that lambda's explicit object parameter.
19658 auto IsDependent = [&]() {
19659 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
19660 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
19661 if (!LSI)
19662 continue;
19663
19664 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
19665 LSI->AfterParameterList)
19666 return false;
19667
19668 const auto *MD = LSI->CallOperator;
19669 if (MD->getType().isNull())
19670 continue;
19671
19672 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
19673 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
19674 !Ty->getParamType(0)->isDependentType())
19675 continue;
19676
19677 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
19678 if (C->isCopyCapture())
19679 return true;
19680 continue;
19681 }
19682
19683 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
19684 return true;
19685 }
19686 return false;
19687 }();
19688
19689 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
19690 IsDependent, SemaRef.getASTContext());
19691}
19692
19693static void
19695 bool MightBeOdrUse,
19696 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19699
19700 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19702 if (SemaRef.getLangOpts().CPlusPlus)
19704 Var, E);
19705 return;
19706 }
19707
19708 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
19710 if (SemaRef.getLangOpts().CPlusPlus)
19712 Decl, E);
19713 return;
19714 }
19715 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19716
19717 // If this is a call to a method via a cast, also mark the method in the
19718 // derived class used in case codegen can devirtualize the call.
19719 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19720 if (!ME)
19721 return;
19722 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19723 if (!MD)
19724 return;
19725 // Only attempt to devirtualize if this is truly a virtual call.
19726 bool IsVirtualCall = MD->isVirtual() &&
19728 if (!IsVirtualCall)
19729 return;
19730
19731 // If it's possible to devirtualize the call, mark the called function
19732 // referenced.
19734 ME->getBase(), SemaRef.getLangOpts().AppleKext);
19735 if (DM)
19736 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
19737}
19738
19740 // TODO: update this with DR# once a defect report is filed.
19741 // C++11 defect. The address of a pure member should not be an ODR use, even
19742 // if it's a qualified reference.
19743 bool OdrUse = true;
19744 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
19745 if (Method->isVirtual() &&
19746 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
19747 OdrUse = false;
19748
19749 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
19753 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
19754 !FD->isDependentContext())
19755 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
19756 }
19757 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
19759}
19760
19762 // C++11 [basic.def.odr]p2:
19763 // A non-overloaded function whose name appears as a potentially-evaluated
19764 // expression or a member of a set of candidate functions, if selected by
19765 // overload resolution when referred to from a potentially-evaluated
19766 // expression, is odr-used, unless it is a pure virtual function and its
19767 // name is not explicitly qualified.
19768 bool MightBeOdrUse = true;
19769 if (E->performsVirtualDispatch(getLangOpts())) {
19770 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
19771 if (Method->isPureVirtual())
19772 MightBeOdrUse = false;
19773 }
19775 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
19776 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
19778}
19779
19781 for (VarDecl *VD : *E)
19782 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
19784}
19785
19786/// Perform marking for a reference to an arbitrary declaration. It
19787/// marks the declaration referenced, and performs odr-use checking for
19788/// functions and variables. This method should not be used when building a
19789/// normal expression which refers to a variable.
19791 bool MightBeOdrUse) {
19792 if (MightBeOdrUse) {
19793 if (auto *VD = dyn_cast<VarDecl>(D)) {
19795 return;
19796 }
19797 }
19798 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
19799 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
19800 return;
19801 }
19802 D->setReferenced();
19803}
19804
19805namespace {
19806 // Mark all of the declarations used by a type as referenced.
19807 // FIXME: Not fully implemented yet! We need to have a better understanding
19808 // of when we're entering a context we should not recurse into.
19809 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
19810 // TreeTransforms rebuilding the type in a new context. Rather than
19811 // duplicating the TreeTransform logic, we should consider reusing it here.
19812 // Currently that causes problems when rebuilding LambdaExprs.
19813 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
19814 Sema &S;
19816
19817 public:
19819
19820 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
19821
19822 bool TraverseTemplateArgument(const TemplateArgument &Arg);
19823 };
19824}
19825
19826bool MarkReferencedDecls::TraverseTemplateArgument(
19827 const TemplateArgument &Arg) {
19828 {
19829 // A non-type template argument is a constant-evaluated context.
19833 if (Decl *D = Arg.getAsDecl())
19834 S.MarkAnyDeclReferenced(Loc, D, true);
19835 } else if (Arg.getKind() == TemplateArgument::Expression) {
19837 }
19838 }
19839
19840 return Inherited::TraverseTemplateArgument(Arg);
19841}
19842
19844 MarkReferencedDecls Marker(*this, Loc);
19845 Marker.TraverseType(T);
19846}
19847
19848namespace {
19849/// Helper class that marks all of the declarations referenced by
19850/// potentially-evaluated subexpressions as "referenced".
19851class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
19852public:
19853 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
19854 bool SkipLocalVariables;
19856
19857 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
19859 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
19860
19861 void visitUsedDecl(SourceLocation Loc, Decl *D) {
19862 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
19863 }
19864
19865 void Visit(Expr *E) {
19866 if (llvm::is_contained(StopAt, E))
19867 return;
19868 Inherited::Visit(E);
19869 }
19870
19871 void VisitConstantExpr(ConstantExpr *E) {
19872 // Don't mark declarations within a ConstantExpression, as this expression
19873 // will be evaluated and folded to a value.
19874 }
19875
19876 void VisitDeclRefExpr(DeclRefExpr *E) {
19877 // If we were asked not to visit local variables, don't.
19878 if (SkipLocalVariables) {
19879 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
19880 if (VD->hasLocalStorage())
19881 return;
19882 }
19883
19884 // FIXME: This can trigger the instantiation of the initializer of a
19885 // variable, which can cause the expression to become value-dependent
19886 // or error-dependent. Do we need to propagate the new dependence bits?
19888 }
19889
19890 void VisitMemberExpr(MemberExpr *E) {
19892 Visit(E->getBase());
19893 }
19894};
19895} // namespace
19896
19898 bool SkipLocalVariables,
19899 ArrayRef<const Expr*> StopAt) {
19900 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
19901}
19902
19903/// Emit a diagnostic when statements are reachable.
19904/// FIXME: check for reachability even in expressions for which we don't build a
19905/// CFG (eg, in the initializer of a global or in a constant expression).
19906/// For example,
19907/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
19909 const PartialDiagnostic &PD) {
19910 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
19911 if (!FunctionScopes.empty())
19912 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
19914 return true;
19915 }
19916
19917 // The initializer of a constexpr variable or of the first declaration of a
19918 // static data member is not syntactically a constant evaluated constant,
19919 // but nonetheless is always required to be a constant expression, so we
19920 // can skip diagnosing.
19921 // FIXME: Using the mangling context here is a hack.
19922 if (auto *VD = dyn_cast_or_null<VarDecl>(
19923 ExprEvalContexts.back().ManglingContextDecl)) {
19924 if (VD->isConstexpr() ||
19925 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
19926 return false;
19927 // FIXME: For any other kind of variable, we should build a CFG for its
19928 // initializer and check whether the context in question is reachable.
19929 }
19930
19931 Diag(Loc, PD);
19932 return true;
19933}
19934
19935/// Emit a diagnostic that describes an effect on the run-time behavior
19936/// of the program being compiled.
19937///
19938/// This routine emits the given diagnostic when the code currently being
19939/// type-checked is "potentially evaluated", meaning that there is a
19940/// possibility that the code will actually be executable. Code in sizeof()
19941/// expressions, code used only during overload resolution, etc., are not
19942/// potentially evaluated. This routine will suppress such diagnostics or,
19943/// in the absolutely nutty case of potentially potentially evaluated
19944/// expressions (C++ typeid), queue the diagnostic to potentially emit it
19945/// later.
19946///
19947/// This routine should be used for all diagnostics that describe the run-time
19948/// behavior of a program, such as passing a non-POD value through an ellipsis.
19949/// Failure to do so will likely result in spurious diagnostics or failures
19950/// during overload resolution or within sizeof/alignof/typeof/typeid.
19952 const PartialDiagnostic &PD) {
19953
19954 if (ExprEvalContexts.back().isDiscardedStatementContext())
19955 return false;
19956
19957 switch (ExprEvalContexts.back().Context) {
19962 // The argument will never be evaluated, so don't complain.
19963 break;
19964
19967 // Relevant diagnostics should be produced by constant evaluation.
19968 break;
19969
19972 return DiagIfReachable(Loc, Stmts, PD);
19973 }
19974
19975 return false;
19976}
19977
19979 const PartialDiagnostic &PD) {
19980 return DiagRuntimeBehavior(
19981 Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
19982}
19983
19985 CallExpr *CE, FunctionDecl *FD) {
19986 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
19987 return false;
19988
19989 // If we're inside a decltype's expression, don't check for a valid return
19990 // type or construct temporaries until we know whether this is the last call.
19991 if (ExprEvalContexts.back().ExprContext ==
19993 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
19994 return false;
19995 }
19996
19997 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
19998 FunctionDecl *FD;
19999 CallExpr *CE;
20000
20001 public:
20002 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20003 : FD(FD), CE(CE) { }
20004
20005 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20006 if (!FD) {
20007 S.Diag(Loc, diag::err_call_incomplete_return)
20008 << T << CE->getSourceRange();
20009 return;
20010 }
20011
20012 S.Diag(Loc, diag::err_call_function_incomplete_return)
20013 << CE->getSourceRange() << FD << T;
20014 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20015 << FD->getDeclName();
20016 }
20017 } Diagnoser(FD, CE);
20018
20019 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20020 return true;
20021
20022 return false;
20023}
20024
20025// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20026// will prevent this condition from triggering, which is what we want.
20029
20030 unsigned diagnostic = diag::warn_condition_is_assignment;
20031 bool IsOrAssign = false;
20032
20033 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20034 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20035 return;
20036
20037 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20038
20039 // Greylist some idioms by putting them into a warning subcategory.
20040 if (ObjCMessageExpr *ME
20041 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20042 Selector Sel = ME->getSelector();
20043
20044 // self = [<foo> init...]
20045 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20046 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20047
20048 // <foo> = [<bar> nextObject]
20049 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20050 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20051 }
20052
20053 Loc = Op->getOperatorLoc();
20054 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20055 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20056 return;
20057
20058 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20059 Loc = Op->getOperatorLoc();
20060 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20061 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20062 else {
20063 // Not an assignment.
20064 return;
20065 }
20066
20067 Diag(Loc, diagnostic) << E->getSourceRange();
20068
20071 Diag(Loc, diag::note_condition_assign_silence)
20073 << FixItHint::CreateInsertion(Close, ")");
20074
20075 if (IsOrAssign)
20076 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20078 else
20079 Diag(Loc, diag::note_condition_assign_to_comparison)
20081}
20082
20084 // Don't warn if the parens came from a macro.
20085 SourceLocation parenLoc = ParenE->getBeginLoc();
20086 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20087 return;
20088 // Don't warn for dependent expressions.
20089 if (ParenE->isTypeDependent())
20090 return;
20091
20092 Expr *E = ParenE->IgnoreParens();
20093
20094 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20095 if (opE->getOpcode() == BO_EQ &&
20096 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20097 == Expr::MLV_Valid) {
20098 SourceLocation Loc = opE->getOperatorLoc();
20099
20100 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20101 SourceRange ParenERange = ParenE->getSourceRange();
20102 Diag(Loc, diag::note_equality_comparison_silence)
20103 << FixItHint::CreateRemoval(ParenERange.getBegin())
20104 << FixItHint::CreateRemoval(ParenERange.getEnd());
20105 Diag(Loc, diag::note_equality_comparison_to_assign)
20107 }
20108}
20109
20111 bool IsConstexpr) {
20113 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20115
20117 if (result.isInvalid()) return ExprError();
20118 E = result.get();
20119
20120 if (!E->isTypeDependent()) {
20121 if (getLangOpts().CPlusPlus)
20122 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20123
20125 if (ERes.isInvalid())
20126 return ExprError();
20127 E = ERes.get();
20128
20129 QualType T = E->getType();
20130 if (!T->isScalarType()) { // C99 6.8.4.1p1
20131 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20132 << T << E->getSourceRange();
20133 return ExprError();
20134 }
20135 CheckBoolLikeConversion(E, Loc);
20136 }
20137
20138 return E;
20139}
20140
20142 Expr *SubExpr, ConditionKind CK,
20143 bool MissingOK) {
20144 // MissingOK indicates whether having no condition expression is valid
20145 // (for loop) or invalid (e.g. while loop).
20146 if (!SubExpr)
20147 return MissingOK ? ConditionResult() : ConditionError();
20148
20149 ExprResult Cond;
20150 switch (CK) {
20152 Cond = CheckBooleanCondition(Loc, SubExpr);
20153 break;
20154
20156 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20157 break;
20158
20160 Cond = CheckSwitchCondition(Loc, SubExpr);
20161 break;
20162 }
20163 if (Cond.isInvalid()) {
20164 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20165 {SubExpr}, PreferredConditionType(CK));
20166 if (!Cond.get())
20167 return ConditionError();
20168 }
20169 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20171 if (!FullExpr.get())
20172 return ConditionError();
20173
20174 return ConditionResult(*this, nullptr, FullExpr,
20176}
20177
20178namespace {
20179 /// A visitor for rebuilding a call to an __unknown_any expression
20180 /// to have an appropriate type.
20181 struct RebuildUnknownAnyFunction
20182 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20183
20184 Sema &S;
20185
20186 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20187
20188 ExprResult VisitStmt(Stmt *S) {
20189 llvm_unreachable("unexpected statement!");
20190 }
20191
20192 ExprResult VisitExpr(Expr *E) {
20193 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20194 << E->getSourceRange();
20195 return ExprError();
20196 }
20197
20198 /// Rebuild an expression which simply semantically wraps another
20199 /// expression which it shares the type and value kind of.
20200 template <class T> ExprResult rebuildSugarExpr(T *E) {
20201 ExprResult SubResult = Visit(E->getSubExpr());
20202 if (SubResult.isInvalid()) return ExprError();
20203
20204 Expr *SubExpr = SubResult.get();
20205 E->setSubExpr(SubExpr);
20206 E->setType(SubExpr->getType());
20207 E->setValueKind(SubExpr->getValueKind());
20208 assert(E->getObjectKind() == OK_Ordinary);
20209 return E;
20210 }
20211
20212 ExprResult VisitParenExpr(ParenExpr *E) {
20213 return rebuildSugarExpr(E);
20214 }
20215
20216 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20217 return rebuildSugarExpr(E);
20218 }
20219
20220 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20221 ExprResult SubResult = Visit(E->getSubExpr());
20222 if (SubResult.isInvalid()) return ExprError();
20223
20224 Expr *SubExpr = SubResult.get();
20225 E->setSubExpr(SubExpr);
20226 E->setType(S.Context.getPointerType(SubExpr->getType()));
20227 assert(E->isPRValue());
20228 assert(E->getObjectKind() == OK_Ordinary);
20229 return E;
20230 }
20231
20232 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20233 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20234
20235 E->setType(VD->getType());
20236
20237 assert(E->isPRValue());
20238 if (S.getLangOpts().CPlusPlus &&
20239 !(isa<CXXMethodDecl>(VD) &&
20240 cast<CXXMethodDecl>(VD)->isInstance()))
20242
20243 return E;
20244 }
20245
20246 ExprResult VisitMemberExpr(MemberExpr *E) {
20247 return resolveDecl(E, E->getMemberDecl());
20248 }
20249
20250 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20251 return resolveDecl(E, E->getDecl());
20252 }
20253 };
20254}
20255
20256/// Given a function expression of unknown-any type, try to rebuild it
20257/// to have a function type.
20259 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20260 if (Result.isInvalid()) return ExprError();
20261 return S.DefaultFunctionArrayConversion(Result.get());
20262}
20263
20264namespace {
20265 /// A visitor for rebuilding an expression of type __unknown_anytype
20266 /// into one which resolves the type directly on the referring
20267 /// expression. Strict preservation of the original source
20268 /// structure is not a goal.
20269 struct RebuildUnknownAnyExpr
20270 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20271
20272 Sema &S;
20273
20274 /// The current destination type.
20275 QualType DestType;
20276
20277 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20278 : S(S), DestType(CastType) {}
20279
20280 ExprResult VisitStmt(Stmt *S) {
20281 llvm_unreachable("unexpected statement!");
20282 }
20283
20284 ExprResult VisitExpr(Expr *E) {
20285 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20286 << E->getSourceRange();
20287 return ExprError();
20288 }
20289
20290 ExprResult VisitCallExpr(CallExpr *E);
20291 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20292
20293 /// Rebuild an expression which simply semantically wraps another
20294 /// expression which it shares the type and value kind of.
20295 template <class T> ExprResult rebuildSugarExpr(T *E) {
20296 ExprResult SubResult = Visit(E->getSubExpr());
20297 if (SubResult.isInvalid()) return ExprError();
20298 Expr *SubExpr = SubResult.get();
20299 E->setSubExpr(SubExpr);
20300 E->setType(SubExpr->getType());
20301 E->setValueKind(SubExpr->getValueKind());
20302 assert(E->getObjectKind() == OK_Ordinary);
20303 return E;
20304 }
20305
20306 ExprResult VisitParenExpr(ParenExpr *E) {
20307 return rebuildSugarExpr(E);
20308 }
20309
20310 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20311 return rebuildSugarExpr(E);
20312 }
20313
20314 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20315 const PointerType *Ptr = DestType->getAs<PointerType>();
20316 if (!Ptr) {
20317 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20318 << E->getSourceRange();
20319 return ExprError();
20320 }
20321
20322 if (isa<CallExpr>(E->getSubExpr())) {
20323 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20324 << E->getSourceRange();
20325 return ExprError();
20326 }
20327
20328 assert(E->isPRValue());
20329 assert(E->getObjectKind() == OK_Ordinary);
20330 E->setType(DestType);
20331
20332 // Build the sub-expression as if it were an object of the pointee type.
20333 DestType = Ptr->getPointeeType();
20334 ExprResult SubResult = Visit(E->getSubExpr());
20335 if (SubResult.isInvalid()) return ExprError();
20336 E->setSubExpr(SubResult.get());
20337 return E;
20338 }
20339
20340 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20341
20342 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20343
20344 ExprResult VisitMemberExpr(MemberExpr *E) {
20345 return resolveDecl(E, E->getMemberDecl());
20346 }
20347
20348 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20349 return resolveDecl(E, E->getDecl());
20350 }
20351 };
20352}
20353
20354/// Rebuilds a call expression which yielded __unknown_anytype.
20355ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20356 Expr *CalleeExpr = E->getCallee();
20357
20358 enum FnKind {
20359 FK_MemberFunction,
20360 FK_FunctionPointer,
20361 FK_BlockPointer
20362 };
20363
20364 FnKind Kind;
20365 QualType CalleeType = CalleeExpr->getType();
20366 if (CalleeType == S.Context.BoundMemberTy) {
20367 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20368 Kind = FK_MemberFunction;
20369 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20370 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20371 CalleeType = Ptr->getPointeeType();
20372 Kind = FK_FunctionPointer;
20373 } else {
20374 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20375 Kind = FK_BlockPointer;
20376 }
20377 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20378
20379 // Verify that this is a legal result type of a function.
20380 if (DestType->isArrayType() || DestType->isFunctionType()) {
20381 unsigned diagID = diag::err_func_returning_array_function;
20382 if (Kind == FK_BlockPointer)
20383 diagID = diag::err_block_returning_array_function;
20384
20385 S.Diag(E->getExprLoc(), diagID)
20386 << DestType->isFunctionType() << DestType;
20387 return ExprError();
20388 }
20389
20390 // Otherwise, go ahead and set DestType as the call's result.
20391 E->setType(DestType.getNonLValueExprType(S.Context));
20393 assert(E->getObjectKind() == OK_Ordinary);
20394
20395 // Rebuild the function type, replacing the result type with DestType.
20396 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20397 if (Proto) {
20398 // __unknown_anytype(...) is a special case used by the debugger when
20399 // it has no idea what a function's signature is.
20400 //
20401 // We want to build this call essentially under the K&R
20402 // unprototyped rules, but making a FunctionNoProtoType in C++
20403 // would foul up all sorts of assumptions. However, we cannot
20404 // simply pass all arguments as variadic arguments, nor can we
20405 // portably just call the function under a non-variadic type; see
20406 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20407 // However, it turns out that in practice it is generally safe to
20408 // call a function declared as "A foo(B,C,D);" under the prototype
20409 // "A foo(B,C,D,...);". The only known exception is with the
20410 // Windows ABI, where any variadic function is implicitly cdecl
20411 // regardless of its normal CC. Therefore we change the parameter
20412 // types to match the types of the arguments.
20413 //
20414 // This is a hack, but it is far superior to moving the
20415 // corresponding target-specific code from IR-gen to Sema/AST.
20416
20417 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20418 SmallVector<QualType, 8> ArgTypes;
20419 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20420 ArgTypes.reserve(E->getNumArgs());
20421 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20422 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20423 }
20424 ParamTypes = ArgTypes;
20425 }
20426 DestType = S.Context.getFunctionType(DestType, ParamTypes,
20427 Proto->getExtProtoInfo());
20428 } else {
20429 DestType = S.Context.getFunctionNoProtoType(DestType,
20430 FnType->getExtInfo());
20431 }
20432
20433 // Rebuild the appropriate pointer-to-function type.
20434 switch (Kind) {
20435 case FK_MemberFunction:
20436 // Nothing to do.
20437 break;
20438
20439 case FK_FunctionPointer:
20440 DestType = S.Context.getPointerType(DestType);
20441 break;
20442
20443 case FK_BlockPointer:
20444 DestType = S.Context.getBlockPointerType(DestType);
20445 break;
20446 }
20447
20448 // Finally, we can recurse.
20449 ExprResult CalleeResult = Visit(CalleeExpr);
20450 if (!CalleeResult.isUsable()) return ExprError();
20451 E->setCallee(CalleeResult.get());
20452
20453 // Bind a temporary if necessary.
20454 return S.MaybeBindToTemporary(E);
20455}
20456
20457ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20458 // Verify that this is a legal result type of a call.
20459 if (DestType->isArrayType() || DestType->isFunctionType()) {
20460 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20461 << DestType->isFunctionType() << DestType;
20462 return ExprError();
20463 }
20464
20465 // Rewrite the method result type if available.
20466 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20467 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20468 Method->setReturnType(DestType);
20469 }
20470
20471 // Change the type of the message.
20472 E->setType(DestType.getNonReferenceType());
20474
20475 return S.MaybeBindToTemporary(E);
20476}
20477
20478ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20479 // The only case we should ever see here is a function-to-pointer decay.
20480 if (E->getCastKind() == CK_FunctionToPointerDecay) {
20481 assert(E->isPRValue());
20482 assert(E->getObjectKind() == OK_Ordinary);
20483
20484 E->setType(DestType);
20485
20486 // Rebuild the sub-expression as the pointee (function) type.
20487 DestType = DestType->castAs<PointerType>()->getPointeeType();
20488
20489 ExprResult Result = Visit(E->getSubExpr());
20490 if (!Result.isUsable()) return ExprError();
20491
20492 E->setSubExpr(Result.get());
20493 return E;
20494 } else if (E->getCastKind() == CK_LValueToRValue) {
20495 assert(E->isPRValue());
20496 assert(E->getObjectKind() == OK_Ordinary);
20497
20498 assert(isa<BlockPointerType>(E->getType()));
20499
20500 E->setType(DestType);
20501
20502 // The sub-expression has to be a lvalue reference, so rebuild it as such.
20503 DestType = S.Context.getLValueReferenceType(DestType);
20504
20505 ExprResult Result = Visit(E->getSubExpr());
20506 if (!Result.isUsable()) return ExprError();
20507
20508 E->setSubExpr(Result.get());
20509 return E;
20510 } else {
20511 llvm_unreachable("Unhandled cast type!");
20512 }
20513}
20514
20515ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20516 ExprValueKind ValueKind = VK_LValue;
20517 QualType Type = DestType;
20518
20519 // We know how to make this work for certain kinds of decls:
20520
20521 // - functions
20522 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20523 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20524 DestType = Ptr->getPointeeType();
20525 ExprResult Result = resolveDecl(E, VD);
20526 if (Result.isInvalid()) return ExprError();
20527 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20528 VK_PRValue);
20529 }
20530
20531 if (!Type->isFunctionType()) {
20532 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20533 << VD << E->getSourceRange();
20534 return ExprError();
20535 }
20536 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20537 // We must match the FunctionDecl's type to the hack introduced in
20538 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20539 // type. See the lengthy commentary in that routine.
20540 QualType FDT = FD->getType();
20541 const FunctionType *FnType = FDT->castAs<FunctionType>();
20542 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20543 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20544 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20545 SourceLocation Loc = FD->getLocation();
20547 S.Context, FD->getDeclContext(), Loc, Loc,
20548 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20550 false /*isInlineSpecified*/, FD->hasPrototype(),
20551 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20552
20553 if (FD->getQualifier())
20554 NewFD->setQualifierInfo(FD->getQualifierLoc());
20555
20557 for (const auto &AI : FT->param_types()) {
20558 ParmVarDecl *Param =
20560 Param->setScopeInfo(0, Params.size());
20561 Params.push_back(Param);
20562 }
20563 NewFD->setParams(Params);
20564 DRE->setDecl(NewFD);
20565 VD = DRE->getDecl();
20566 }
20567 }
20568
20569 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20570 if (MD->isInstance()) {
20571 ValueKind = VK_PRValue;
20573 }
20574
20575 // Function references aren't l-values in C.
20576 if (!S.getLangOpts().CPlusPlus)
20577 ValueKind = VK_PRValue;
20578
20579 // - variables
20580 } else if (isa<VarDecl>(VD)) {
20581 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20582 Type = RefTy->getPointeeType();
20583 } else if (Type->isFunctionType()) {
20584 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20585 << VD << E->getSourceRange();
20586 return ExprError();
20587 }
20588
20589 // - nothing else
20590 } else {
20591 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20592 << VD << E->getSourceRange();
20593 return ExprError();
20594 }
20595
20596 // Modifying the declaration like this is friendly to IR-gen but
20597 // also really dangerous.
20598 VD->setType(DestType);
20599 E->setType(Type);
20600 E->setValueKind(ValueKind);
20601 return E;
20602}
20603
20607 // The type we're casting to must be either void or complete.
20608 if (!CastType->isVoidType() &&
20610 diag::err_typecheck_cast_to_incomplete))
20611 return ExprError();
20612
20613 // Rewrite the casted expression from scratch.
20614 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20615 if (!result.isUsable()) return ExprError();
20616
20617 CastExpr = result.get();
20618 VK = CastExpr->getValueKind();
20619 CastKind = CK_NoOp;
20620
20621 return CastExpr;
20622}
20623
20625 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20626}
20627
20629 Expr *arg, QualType &paramType) {
20630 // If the syntactic form of the argument is not an explicit cast of
20631 // any sort, just do default argument promotion.
20632 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20633 if (!castArg) {
20635 if (result.isInvalid()) return ExprError();
20636 paramType = result.get()->getType();
20637 return result;
20638 }
20639
20640 // Otherwise, use the type that was written in the explicit cast.
20641 assert(!arg->hasPlaceholderType());
20642 paramType = castArg->getTypeAsWritten();
20643
20644 // Copy-initialize a parameter of that type.
20645 InitializedEntity entity =
20647 /*consumed*/ false);
20648 return PerformCopyInitialization(entity, callLoc, arg);
20649}
20650
20652 Expr *orig = E;
20653 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20654 while (true) {
20655 E = E->IgnoreParenImpCasts();
20656 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20657 E = call->getCallee();
20658 diagID = diag::err_uncasted_call_of_unknown_any;
20659 } else {
20660 break;
20661 }
20662 }
20663
20664 SourceLocation loc;
20665 NamedDecl *d;
20666 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20667 loc = ref->getLocation();
20668 d = ref->getDecl();
20669 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20670 loc = mem->getMemberLoc();
20671 d = mem->getMemberDecl();
20672 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20673 diagID = diag::err_uncasted_call_of_unknown_any;
20674 loc = msg->getSelectorStartLoc();
20675 d = msg->getMethodDecl();
20676 if (!d) {
20677 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20678 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20679 << orig->getSourceRange();
20680 return ExprError();
20681 }
20682 } else {
20683 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20684 << E->getSourceRange();
20685 return ExprError();
20686 }
20687
20688 S.Diag(loc, diagID) << d << orig->getSourceRange();
20689
20690 // Never recoverable.
20691 return ExprError();
20692}
20693
20696 // C cannot handle TypoExpr nodes on either side of a binop because it
20697 // doesn't handle dependent types properly, so make sure any TypoExprs have
20698 // been dealt with before checking the operands.
20700 if (!Result.isUsable()) return ExprError();
20701 E = Result.get();
20702 }
20703
20704 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20705 if (!placeholderType) return E;
20706
20707 switch (placeholderType->getKind()) {
20708 case BuiltinType::UnresolvedTemplate: {
20709 auto *ULE = cast<UnresolvedLookupExpr>(E);
20710 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
20711 // There's only one FoundDecl for UnresolvedTemplate type. See
20712 // BuildTemplateIdExpr.
20713 NamedDecl *Temp = *ULE->decls_begin();
20714 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
20715
20716 if (NestedNameSpecifierLoc Loc = ULE->getQualifierLoc(); Loc.hasQualifier())
20717 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
20718 << Loc.getNestedNameSpecifier() << NameInfo.getName().getAsString()
20719 << Loc.getSourceRange() << IsTypeAliasTemplateDecl;
20720 else
20721 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
20722 << "" << NameInfo.getName().getAsString() << ULE->getSourceRange()
20723 << IsTypeAliasTemplateDecl;
20724 Diag(Temp->getLocation(), diag::note_referenced_type_template)
20725 << IsTypeAliasTemplateDecl;
20726
20727 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
20728 }
20729
20730 // Overloaded expressions.
20731 case BuiltinType::Overload: {
20732 // Try to resolve a single function template specialization.
20733 // This is obligatory.
20736 return Result;
20737
20738 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20739 // leaves Result unchanged on failure.
20740 Result = E;
20742 return Result;
20743
20744 // If that failed, try to recover with a call.
20745 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
20746 /*complain*/ true);
20747 return Result;
20748 }
20749
20750 // Bound member functions.
20751 case BuiltinType::BoundMember: {
20752 ExprResult result = E;
20753 const Expr *BME = E->IgnoreParens();
20754 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
20755 // Try to give a nicer diagnostic if it is a bound member that we recognize.
20756 if (isa<CXXPseudoDestructorExpr>(BME)) {
20757 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
20758 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
20759 if (ME->getMemberNameInfo().getName().getNameKind() ==
20761 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
20762 }
20763 tryToRecoverWithCall(result, PD,
20764 /*complain*/ true);
20765 return result;
20766 }
20767
20768 // ARC unbridged casts.
20769 case BuiltinType::ARCUnbridgedCast: {
20770 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
20771 ObjC().diagnoseARCUnbridgedCast(realCast);
20772 return realCast;
20773 }
20774
20775 // Expressions of unknown type.
20776 case BuiltinType::UnknownAny:
20777 return diagnoseUnknownAnyExpr(*this, E);
20778
20779 // Pseudo-objects.
20780 case BuiltinType::PseudoObject:
20781 return PseudoObject().checkRValue(E);
20782
20783 case BuiltinType::BuiltinFn: {
20784 // Accept __noop without parens by implicitly converting it to a call expr.
20785 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
20786 if (DRE) {
20787 auto *FD = cast<FunctionDecl>(DRE->getDecl());
20788 unsigned BuiltinID = FD->getBuiltinID();
20789 if (BuiltinID == Builtin::BI__noop) {
20790 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
20791 CK_BuiltinFnToFnPtr)
20792 .get();
20793 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
20796 }
20797
20798 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
20799 // Any use of these other than a direct call is ill-formed as of C++20,
20800 // because they are not addressable functions. In earlier language
20801 // modes, warn and force an instantiation of the real body.
20802 Diag(E->getBeginLoc(),
20804 ? diag::err_use_of_unaddressable_function
20805 : diag::warn_cxx20_compat_use_of_unaddressable_function);
20806 if (FD->isImplicitlyInstantiable()) {
20807 // Require a definition here because a normal attempt at
20808 // instantiation for a builtin will be ignored, and we won't try
20809 // again later. We assume that the definition of the template
20810 // precedes this use.
20812 /*Recursive=*/false,
20813 /*DefinitionRequired=*/true,
20814 /*AtEndOfTU=*/false);
20815 }
20816 // Produce a properly-typed reference to the function.
20817 CXXScopeSpec SS;
20818 SS.Adopt(DRE->getQualifierLoc());
20819 TemplateArgumentListInfo TemplateArgs;
20820 DRE->copyTemplateArgumentsInto(TemplateArgs);
20821 return BuildDeclRefExpr(
20822 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
20823 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
20824 DRE->getTemplateKeywordLoc(),
20825 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
20826 }
20827 }
20828
20829 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
20830 return ExprError();
20831 }
20832
20833 case BuiltinType::IncompleteMatrixIdx:
20834 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
20835 ->getRowIdx()
20836 ->getBeginLoc(),
20837 diag::err_matrix_incomplete_index);
20838 return ExprError();
20839
20840 // Expressions of unknown type.
20841 case BuiltinType::ArraySection:
20842 Diag(E->getBeginLoc(), diag::err_array_section_use)
20843 << cast<ArraySectionExpr>(E)->isOMPArraySection();
20844 return ExprError();
20845
20846 // Expressions of unknown type.
20847 case BuiltinType::OMPArrayShaping:
20848 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
20849
20850 case BuiltinType::OMPIterator:
20851 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
20852
20853 // Everything else should be impossible.
20854#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
20855 case BuiltinType::Id:
20856#include "clang/Basic/OpenCLImageTypes.def"
20857#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
20858 case BuiltinType::Id:
20859#include "clang/Basic/OpenCLExtensionTypes.def"
20860#define SVE_TYPE(Name, Id, SingletonId) \
20861 case BuiltinType::Id:
20862#include "clang/Basic/AArch64SVEACLETypes.def"
20863#define PPC_VECTOR_TYPE(Name, Id, Size) \
20864 case BuiltinType::Id:
20865#include "clang/Basic/PPCTypes.def"
20866#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20867#include "clang/Basic/RISCVVTypes.def"
20868#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20869#include "clang/Basic/WebAssemblyReferenceTypes.def"
20870#define AMDGPU_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
20871#include "clang/Basic/AMDGPUTypes.def"
20872#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
20873#define PLACEHOLDER_TYPE(Id, SingletonId)
20874#include "clang/AST/BuiltinTypes.def"
20875 break;
20876 }
20877
20878 llvm_unreachable("invalid placeholder type!");
20879}
20880
20882 if (E->isTypeDependent())
20883 return true;
20886 return false;
20887}
20888
20890 ArrayRef<Expr *> SubExprs, QualType T) {
20891 if (!Context.getLangOpts().RecoveryAST)
20892 return ExprError();
20893
20894 if (isSFINAEContext())
20895 return ExprError();
20896
20897 if (T.isNull() || T->isUndeducedType() ||
20898 !Context.getLangOpts().RecoveryASTType)
20899 // We don't know the concrete type, fallback to dependent type.
20901
20902 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
20903}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3338
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:1143
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:9035
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
Definition: SemaExpr.cpp:17491
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:1922
@ ConstMethod
Definition: SemaExpr.cpp:13156
@ ConstUnknown
Definition: SemaExpr.cpp:13158
@ ConstVariable
Definition: SemaExpr.cpp:13154
@ NestedConstMember
Definition: SemaExpr.cpp:13157
@ ConstMember
Definition: SemaExpr.cpp:13155
@ ConstFunction
Definition: SemaExpr.cpp:13153
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:15076
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:9914
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:18429
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:10656
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:14867
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
Definition: SemaExpr.cpp:6053
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:10575
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:8605
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:3131
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
Definition: SemaExpr.cpp:8059
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:8265
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:11621
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:10620
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:11571
static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn)
Definition: SemaExpr.cpp:5723
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
Definition: SemaExpr.cpp:2207
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:14343
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:17829
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:13106
@ NCCK_Block
Definition: SemaExpr.cpp:13106
@ NCCK_None
Definition: SemaExpr.cpp:13106
@ NCCK_Lambda
Definition: SemaExpr.cpp:13106
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:9808
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:9084
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:5985
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:2609
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
Definition: SemaExpr.cpp:19648
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18281
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:16565
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:8509
static Decl * getPredefinedExprDecl(DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
Definition: SemaExpr.cpp:1906
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:16448
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
Definition: SemaExpr.cpp:13668
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4690
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:11973
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
Definition: SemaExpr.cpp:14243
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
Definition: SemaExpr.cpp:4306
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
Definition: SemaExpr.cpp:8584
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
Definition: SemaExpr.cpp:17678
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:14399
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:10741
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:7902
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19448
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:3156
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:7868
static bool checkForArray(const Expr *E)
Definition: SemaExpr.cpp:11663
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
Definition: SemaExpr.cpp:6326
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:13290
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19694
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:9855
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
Definition: SemaExpr.cpp:19416
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:14225
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
Definition: SemaExpr.cpp:17352
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:11848
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:8539
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:14497
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1292
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:6216
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:9472
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:8183
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:7889
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
Definition: SemaExpr.cpp:10587
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:14482
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:4747
static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8811
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
Definition: SemaExpr.cpp:17394
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:14958
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:2342
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:13773
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:8128
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:8237
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10414
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:11677
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:4183
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:10462
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3454
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
Definition: SemaExpr.cpp:5682
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition: SemaExpr.cpp:144
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
Definition: SemaExpr.cpp:11110
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4090
static Sema::AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
Definition: SemaExpr.cpp:8984
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:1249
static void MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
Definition: SemaExpr.cpp:18112
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:10771
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:13354
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:13875
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:160
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:17709
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:11472
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:15015
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:13935
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:1342
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:4761
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:9958
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:18469
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
Definition: SemaExpr.cpp:14922
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:553
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
Definition: SemaExpr.cpp:8639
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:17797
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:13165
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3584
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:13143
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:18229
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:10634
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4135
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:11305
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:11891
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:20651
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:1914
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:8303
OriginalExprKind
Definition: SemaExpr.cpp:13284
@ OEK_Variable
Definition: SemaExpr.cpp:13285
@ OEK_LValue
Definition: SemaExpr.cpp:13287
@ OEK_Member
Definition: SemaExpr.cpp:13286
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:18361
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:1199
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:10562
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:11211
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
Definition: SemaExpr.cpp:18188
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1274
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:10378
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:13093
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:18597
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:6285
static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4120
static Sema::AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, SourceLocation Loc)
Definition: SemaExpr.cpp:8832
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4108
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
Definition: SemaExpr.cpp:14943
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
Definition: SemaExpr.cpp:4780
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:1474
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:10822
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:6243
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
Definition: SemaExpr.cpp:1388
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4165
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:10604
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:8098
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:11809
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
Definition: SemaExpr.cpp:12672
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:8217
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:8524
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:1093
static std::pair< ExprResult, ExprResult > CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:14530
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:14441
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition: SemaExpr.cpp:578
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:20258
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:1168
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:11524
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
Definition: SemaExpr.cpp:1121
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:6143
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
Definition: SemaExpr.cpp:19619
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind)
Definition: SemaExpr.cpp:1882
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition: SemaExpr.cpp:106
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:1435
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
Definition: SemaExpr.cpp:1144
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:13737
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
Definition: SemaExpr.cpp:18571
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:10552
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:11461
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:14553
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:11511
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:13107
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:8033
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:14987
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:14973
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:11501
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
Definition: SemaExpr.cpp:14910
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
Definition: SemaExpr.cpp:4372
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:9876
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18262
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:15255
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:13482
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12902
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:19033
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
Definition: SemaExpr.cpp:17743
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:11104
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:10688
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:7413
SourceRange Range
Definition: SemaObjC.cpp:757
SourceLocation Loc
Definition: SemaObjC.cpp:758
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:186
CanQualType AccumTy
Definition: ASTContext.h:1131
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:1100
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2822
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:1149
CanQualType LongTy
Definition: ASTContext.h:1127
unsigned getIntWidth(QualType T) const
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
CanQualType Int128Ty
Definition: ASTContext.h:1127
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:2169
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:663
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:2183
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1131
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
Definition: ASTContext.h:1130
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2625
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2641
CanQualType DoubleTy
Definition: ASTContext.h:1130
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:1130
CanQualType Char16Ty
Definition: ASTContext.h:1125
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1145
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:1146
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:1634
CanQualType WideCharTy
Definition: ASTContext.h:1122
IdentifierTable & Idents
Definition: ASTContext.h:659
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:661
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:796
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>.
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:1119
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:1130
CanQualType UnsignedLongTy
Definition: ASTContext.h:1128
llvm::DenseSet< const FunctionDecl * > CUDAImplicitHostDeviceFunUsedByDevice
Keep track of CUDA/HIP implicit host device functions used on device side in device compilation.
Definition: ASTContext.h:1200
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:1134
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:1146
CanQualType CharTy
Definition: ASTContext.h:1120
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:1127
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1192
CanQualType PseudoObjectTy
Definition: ASTContext.h:1149
CanQualType Float16Ty
Definition: ASTContext.h:1144
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2207
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1146
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:2371
llvm::DenseSet< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
Definition: ASTContext.h:1196
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2672
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:2391
CanQualType BuiltinFnTy
Definition: ASTContext.h:1148
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1118
CanQualType UnsignedCharTy
Definition: ASTContext.h:1128
CanQualType UnsignedIntTy
Definition: ASTContext.h:1128
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:1928
CanQualType UnknownAnyTy
Definition: ASTContext.h:1147
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1129
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:1612
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:1127
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:1134
CanQualType LongAccumTy
Definition: ASTContext.h:1132
CanQualType Char32Ty
Definition: ASTContext.h:1126
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:778
CanQualType LongFractTy
Definition: ASTContext.h:1134
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1157
std::optional< CharUnits > getTypeSizeInCharsIfKnown(QualType Ty) const
Definition: ASTContext.h:2410
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:1127
QualType getCorrespondingSignedType(QualType T) const
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1844
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:2050
unsigned char getFixedPointScale(QualType Ty) const
QualType adjustStringLiteralBaseType(QualType StrLTy) const
CanQualType Char8Ty
Definition: ASTContext.h:1124
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
CanQualType HalfTy
Definition: ASTContext.h:1142
bool isDependenceAllowed() const
Definition: ASTContext.h:802
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:2395
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:4362
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:3540
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3554
QualType getElementType() const
Definition: Type.h:3552
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition: Expr.h:6416
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:6046
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6368
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4265
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
Expr * getLHS() const
Definition: Expr.h:3909
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:3959
bool isComparisonOp() const
Definition: Expr.h:3960
StringRef getOpcodeStr() const
Definition: Expr.h:3925
bool isRelationalOp() const
Definition: Expr.h:3954
SourceLocation getOperatorLoc() const
Definition: Expr.h:3901
bool isCompoundAssignmentOp() const
Definition: Expr.h:4003
bool isMultiplicativeOp() const
Definition: Expr.h:3944
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:3948
Expr * getRHS() const
Definition: Expr.h:3911
bool isEqualityOp() const
Definition: Expr.h:3957
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:4804
bool isBitwiseOp() const
Definition: Expr.h:3951
bool isAdditiveOp() const
Definition: Expr.h:3946
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:3904
bool isAssignmentOp() const
Definition: Expr.h:3998
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:3950
A binding in a decomposition declaration.
Definition: DeclCXX.h:4107
A class which contains all the information about a particular captured value.
Definition: Decl.h:4473
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4467
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.cpp:5217
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition: Decl.h:4549
void setBlockMissingReturnType(bool val=true)
Definition: Decl.h:4606
void setIsVariadic(bool value)
Definition: Decl.h:4543
SourceLocation getCaretLocation() const
Definition: Decl.h:4540
void setBody(CompoundStmt *B)
Definition: Decl.h:4547
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:4553
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition: Decl.cpp:5228
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5404
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6355
Pointer to a block type.
Definition: Type.h:3371
This class is used for builtin types like 'int'.
Definition: Type.h:3000
bool isSVEBool() const
Definition: Type.h:3074
Kind getKind() const
Definition: Type.h:3045
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:1904
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:2535
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition: DeclCXX.cpp:2906
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2300
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:1016
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:1070
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:1531
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isVirtual() const
Definition: DeclCXX.h:2115
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
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:2295
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:1226
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:569
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:613
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1933
bool hasDefinition() const
Definition: DeclCXX.h:571
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
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:4582
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:3108
QualType getElementType() const
Definition: Type.h:3118
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:4826
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3428
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
bool body_empty() const
Definition: Stmt.h:1650
Stmt * getStmtExprResult()
Definition: Stmt.h:1728
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4203
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3578
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3634
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3654
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:4189
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4210
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4207
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:4523
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:1358
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1425
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2079
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2208
bool isRequiresExprBody() const
Definition: DeclBase.h:2164
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1309
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1828
bool isRecord() const
Definition: DeclBase.h:2159
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1964
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1742
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1611
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1990
bool isFunctionOrMethod() const
Definition: DeclBase.h:2131
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1260
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1379
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:579
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
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:594
SourceLocation getLocation() const
Definition: DeclBase.h:445
void setReferenced(bool R=true)
Definition: DeclBase.h:629
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1028
DeclContext * getDeclContext()
Definition: DeclBase.h:454
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:897
bool hasAttr() const
Definition: DeclBase.h:583
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:957
Kind getKind() const
Definition: DeclBase.h:448
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:1900
DeclaratorContext getContext() const
Definition: DeclSpec.h:2072
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2083
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2330
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:529
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:4857
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:5962
EnumDecl * getDecl() const
Definition: Type.h:5969
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:1444
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:6295
ExtVectorType - Extended vector type.
Definition: Type.h:4083
Represents difference between two FPOptions values.
Definition: LangOptions.h:919
bool isFPConstrained() const
Definition: LangOptions.h:847
RoundingMode getRoundingMode() const
Definition: LangOptions.h:853
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:3243
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:3701
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:3861
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3620
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3719
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:3480
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:3967
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:3877
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:4646
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4973
QualType desugar() const
Definition: Type.h:5517
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5439
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5253
bool isParamConsumed(unsigned I) const
Definition: Type.h:5453
unsigned getNumParams() const
Definition: Type.h:5226
QualType getParamType(unsigned i) const
Definition: Type.h:5228
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5350
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5237
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5233
ArrayRef< QualType > param_types() const
Definition: Type.h:5382
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:4389
bool getCmseNSCall() const
Definition: Type.h:4439
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4463
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4278
ExtInfo getExtInfo() const
Definition: Type.h:4612
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4608
QualType getReturnType() const
Definition: Type.h:4600
bool getCmseNSCallAttr() const
Definition: Type.h:4610
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4624
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4657
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:3314
Describes an C or C++ initializer list.
Definition: Expr.h:5029
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:7482
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:461
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:496
bool isSubscriptPointerArithmetic() const
Definition: LangOptions.h:624
bool isSignedOverflowDefined() const
Definition: LangOptions.h:620
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:4289
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:4153
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4167
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:7336
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:1950
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:7392
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:7511
Represents a class type in Objective C.
Definition: Type.h:7138
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:2082
bool allowsSizeofAlignof() const
Does this runtime allow sizeof or alignof on object types?
Definition: ObjCRuntime.h:332
bool allowsPointerArithmetic() const
Does this runtime allow pointer arithmetic on objects?
Definition: ObjCRuntime.h:340
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr * > exprs, SourceLocation RParenLoc)
Definition: Expr.cpp:1657
Helper class for OffsetOfExpr.
Definition: Expr.h:2369
void * getAsOpaquePtr() const
Definition: Ownership.h:90
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:91
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1008
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition: ExprCXX.h:2982
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3043
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2135
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2154
const Expr * getSubExpr() const
Definition: Expr.h:2150
Expr * getExpr(unsigned Init)
Definition: Expr.h:5837
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:5835
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:3161
QualType getPointeeType() const
Definition: Type.h:3171
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.
SourceManager & getSourceManager() const
bool isMacroDefined(StringRef Id)
const TargetInfo & getTargetInfo() const
char getSpellingOfSingleCharacterNumericConstant(const Token &Tok, bool *Invalid=nullptr) const
Given a Token Tok that is a numeric constant with length 1, return the character.
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:6487
A (possibly-)qualified type.
Definition: Type.h:941
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7827
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7832
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:7890
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3469
@ DK_nontrivial_c_struct
Definition: Type.h:1535
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2819
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:7925
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:7743
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7869
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:7884
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7783
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:2601
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:7944
QualType getCanonicalType() const
Definition: Type.h:7795
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7837
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2837
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:7951
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7816
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7864
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:7800
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:2593
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7775
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:7878
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:4141
field_range fields() const
Definition: Decl.h:4347
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5936
RecordDecl * getDecl() const
Definition: Type.h:5946
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition: Expr.cpp:5127
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:216
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3402
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:110
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:862
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:1259
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
Definition: SemaObjC.cpp:1160
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:599
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:370
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:8057
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:12119
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7233
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T)
Definition: SemaExpr.cpp:16906
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:16912
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:535
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:14364
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:6321
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition: Sema.h:7802
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:13120
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:803
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:2434
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:15588
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:7864
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3578
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15265
bool isAlwaysConstantEvaluatedContext() const
Definition: Sema.h:7772
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:863
bool isAttrContext() const
Definition: Sema.h:6460
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:15001
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:7857
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8999
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition: Sema.h:9038
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9007
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:407
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19378
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12980
VariadicCallType
Definition: Sema.h:2333
@ VariadicDoesNotApply
Definition: Sema.h:2338
@ VariadicFunction
Definition: Sema.h:2334
@ VariadicMethod
Definition: Sema.h:2336
@ VariadicConstructor
Definition: Sema.h:2337
@ VariadicBlock
Definition: Sema.h:2335
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:6954
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:3636
@ NTCUC_Assignment
Definition: Sema.h:3634
@ NTCUC_FunctionReturn
Definition: Sema.h:3626
@ NTCUC_LValueToRValueVolatile
Definition: Sema.h:3640
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:7458
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:2320
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition: Sema.h:1219
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:15607
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:17224
void ActOnStmtExprError()
Definition: SemaExpr.cpp:15613
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:1539
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
Definition: SemaExpr.cpp:12000
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:16221
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition: Sema.h:947
SemaCUDA & CUDA()
Definition: Sema.h:1164
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17159
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:20110
ConditionKind
Definition: Sema.h:7355
@ 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:2650
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:940
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:2276
Preprocessor & getPreprocessor() const
Definition: Sema.h:599
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition: Sema.h:6438
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2145
QualType GetSignedSizelessVectorType(QualType V)
Definition: SemaExpr.cpp:12558
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:7933
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3518
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition: Sema.h:7845
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:18182
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:16917
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
Definition: SemaExpr.cpp:6595
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:10050
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:1731
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types? I.e.
Definition: SemaExpr.cpp:7432
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:19897
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth)
Definition: SemaExpr.cpp:15626
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.
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16274
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition: Sema.h:6450
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:1547
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:779
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
ExprResult CheckUnevaluatedOperand(Expr *E)
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
Definition: SemaExpr.cpp:1024
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:13688
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:4967
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
Definition: SemaExpr.cpp:1981
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
Definition: SemaExpr.cpp:7542
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:13968
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:14988
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1057
ASTContext & Context
Definition: Sema.h:1002
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:7759
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:9748
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:19908
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:11397
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:597
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:7807
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:20881
SemaObjC & ObjC()
Definition: Sema.h:1204
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
Definition: SemaExpr.cpp:12819
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:2653
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:7247
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1495
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19391
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:747
bool isImmediateFunctionContext() const
Definition: Sema.h:7784
ASTContext & getASTContext() const
Definition: Sema.h:600
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition: SemaExpr.cpp:757
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:15544
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:18673
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:19639
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
Definition: SemaExpr.cpp:15062
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:17580
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9491
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:694
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition: SemaExpr.cpp:862
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
Definition: SemaExpr.cpp:3466
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
Definition: SemaExpr.cpp:6118
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3075
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:6968
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:15594
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:5601
@ None
This is not a defaultable comparison operator.
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:7823
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:12865
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1552
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2186
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:15882
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:1653
AssumedTemplateKind
Definition: Sema.h:11113
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
Definition: SemaExpr.cpp:1951
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:502
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:743
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:7817
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:595
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition: Sema.h:7927
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20141
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:83
@ UPPC_Block
Block expression.
Definition: Sema.h:13931
const LangOptions & getLangOpts() const
Definition: Sema.h:593
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:12027
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:7206
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12794
SemaOpenACC & OpenACC()
Definition: Sema.h:1209
ReuseLambdaContextDecl_t
Definition: Sema.h:6535
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:6557
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void MarkExpressionAsImmediateEscalating(Expr *E)
Definition: SemaExpr.cpp:17255
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
Definition: SemaExpr.cpp:2234
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:19780
Preprocessor & PP
Definition: Sema.h:1001
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:10832
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5638
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:6394
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
Definition: SemaExpr.cpp:13940
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
Definition: SemaExpr.cpp:16548
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
Definition: SemaExpr.cpp:4682
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:1964
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
Definition: SemaExpr.cpp:7447
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:1000
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
Definition: SemaExpr.cpp:15696
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2389
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:6645
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17276
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7445
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:6030
SemaHLSL & HLSL()
Definition: Sema.h:1169
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:17240
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:204
@ 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:72
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:19790
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:9772
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:6471
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:6056
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1559
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:9348
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:13508
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:924
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
Definition: SemaExpr.cpp:15507
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:777
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:1033
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:3617
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
Definition: SemaExpr.cpp:10300
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:9543
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:1663
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6468
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:2128
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:635
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3163
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:7788
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
Definition: SemaExpr.cpp:7193
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:1621
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:16068
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7583
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2345
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1137
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:7426
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:20604
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition: Sema.h:12143
@ VAK_Invalid
Definition: Sema.h:7543
@ VAK_Valid
Definition: Sema.h:7539
@ VAK_ValidInCXX11
Definition: Sema.h:7540
@ VAK_MSVCUndefined
Definition: Sema.h:7542
@ VAK_Undefined
Definition: Sema.h:7541
SemaOpenCL & OpenCL()
Definition: Sema.h:1214
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5771
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:13517
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:16430
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:7829
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:19843
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:7780
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1527
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:7583
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition: Sema.h:7627
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition: Sema.h:7593
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition: Sema.h:7651
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition: Sema.h:7656
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition: Sema.h:7643
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:7622
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:7601
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition: Sema.h:7660
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:7585
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition: Sema.h:7612
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:7664
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition: Sema.h:7597
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition: Sema.h:7606
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:7618
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition: Sema.h:7639
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition: Sema.h:7633
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition: Sema.h:7589
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition: Sema.h:7647
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:8327
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition: Sema.h:7402
@ ACK_Arithmetic
An arithmetic operation.
Definition: Sema.h:7404
@ ACK_CompAssign
A compound assignment expression.
Definition: Sema.h:7412
@ ACK_BitwiseOp
A bitwise operation.
Definition: Sema.h:7406
@ ACK_Conditional
A conditional (?:) operator.
Definition: Sema.h:7410
@ ACK_Comparison
A comparison.
Definition: Sema.h:7408
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:19739
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:2870
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4081
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16515
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition: Sema.h:6283
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20694
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17139
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:13471
SourceManager & getSourceManager() const
Definition: Sema.h:598
TryCaptureKind
Definition: Sema.h:6597
@ TryCapture_Implicit
Definition: Sema.h:6598
@ TryCapture_ExplicitByRef
Definition: Sema.h:6600
AssignmentAction
Definition: Sema.h:6479
@ AA_Returning
Definition: Sema.h:6482
@ AA_Passing_CFAudited
Definition: Sema.h:6487
@ AA_Initializing
Definition: Sema.h:6484
@ AA_Converting
Definition: Sema.h:6483
@ AA_Assigning
Definition: Sema.h:6480
@ AA_Passing
Definition: Sema.h:6481
@ AA_Casting
Definition: Sema.h:6486
@ AA_Sending
Definition: Sema.h:6485
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
Definition: SemaExpr.cpp:6623
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:4362
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:8691
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:12570
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:10475
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
Definition: SemaExpr.cpp:19355
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13527
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:3652
@ NTCUK_Copy
Definition: Sema.h:3653
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:19978
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5441
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:7477
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:7514
void keepInLifetimeExtendingContext()
keepInLifetimeExtendingContext - Pull down InLifetimeExtendingContext flag from previous context.
Definition: Sema.h:7835
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:2176
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:6281
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:215
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:8170
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:2030
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14915
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:15049
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:7616
@ CTK_ErrorRecovery
Definition: Sema.h:9393
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2330
bool isConstantEvaluatedContext() const
Definition: Sema.h:2170
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:3077
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12405
ASTConsumer & Consumer
Definition: Sema.h:1003
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:4224
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:6475
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:120
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:1038
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:13500
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5090
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3514
ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, StringLiteral *BinaryData)
Definition: SemaExpr.cpp:16556
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
Definition: SemaExpr.cpp:12515
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:8317
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition: Sema.h:6225
@ 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:6616
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
Definition: SemaExpr.cpp:4588
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5645
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:19984
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
Definition: SemaExpr.cpp:4199
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16267
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
Definition: SemaType.cpp:5758
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8885
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:963
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20624
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:18989
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:7651
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:7770
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr)
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17658
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:18981
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7930
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1306
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
Definition: SemaExpr.cpp:7563
SourceManager & SourceMgr
Definition: Sema.h:1005
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
Definition: SemaExpr.cpp:4674
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:7724
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:2375
DiagnosticsEngine & Diags
Definition: Sema.h:1004
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:594
FPOptions CurFPFeatures
Definition: Sema.h:998
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:511
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:690
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:7500
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9616
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5515
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
Definition: SemaExpr.cpp:20027
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:1313
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12916
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:6060
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:15621
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:979
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
Definition: SemaExpr.cpp:5995
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12631
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8794
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:12951
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:16078
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:566
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
Definition: SemaExpr.cpp:19761
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:16584
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:17839
ExprResult ActOnStmtExprResult(ExprResult E)
Definition: SemaExpr.cpp:15665
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4727
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:5881
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:281
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
Definition: SemaExpr.cpp:20083
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1947
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:20889
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15112
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3651
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Definition: SemaExpr.cpp:2943
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7168
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:15920
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
Definition: SemaExpr.cpp:4800
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:14577
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9069
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:6356
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:4657
QualType PreferredConditionType(ConditionKind K) const
Definition: Sema.h:7500
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:9052
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition: Sema.h:9058
@ LOLR_Error
The lookup resulted in an error.
Definition: Sema.h:9050
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition: Sema.h:9055
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition: Sema.h:9066
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition: Sema.h:9062
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:15949
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:10514
@ 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:13496
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:2723
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:15629
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:13203
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:10955
static ConditionResult ConditionError()
Definition: Sema.h:7342
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ActOnConvertVectorExpr - create a new convert-vector expression from the provided arguments.
Definition: SemaExpr.cpp:6637
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:20628
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:5741
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:15863
SemaPseudoObject & PseudoObject()
Definition: Sema.h:1229
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2321
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:7298
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy)
Definition: SemaCast.cpp:2704
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:17666
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7100
bool isCheckingDefaultArgumentOrInitializer() const
Definition: Sema.h:7794
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:5302
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:8277
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:4975
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4751
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:4407
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:1358
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:3660
bool isUnion() const
Definition: Decl.h:3763
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3781
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:3363
const Type * getTypeForDecl() const
Definition: Decl.h:3387
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3390
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:7714
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:7725
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:2416
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:8356
bool isBlockPointerType() const
Definition: Type.h:8006
bool isVoidType() const
Definition: Type.h:8295
bool isBooleanType() const
Definition: Type.h:8423
bool isFunctionReferenceType() const
Definition: Type.h:8039
bool isObjCBuiltinType() const
Definition: Type.h:8185
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:8473
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:740
bool isIncompleteArrayType() const
Definition: Type.h:8072
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:8271
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:8453
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:8064
bool isCharType() const
Definition: Type.cpp:2089
bool isFunctionPointerType() const
Definition: Type.h:8032
bool isArithmeticType() const
Definition: Type.cpp:2281
bool isConstantMatrixType() const
Definition: Type.h:8126
bool isPointerType() const
Definition: Type.h:7996
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8335
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2480
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8583
bool isReferenceType() const
Definition: Type.h:8010
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:8376
bool isEnumeralType() const
Definition: Type.h:8096
bool isScalarType() const
Definition: Type.h:8394
bool isVariableArrayType() const
Definition: Type.h:8076
bool isSizelessBuiltinType() const
Definition: Type.cpp:2441
bool isClkEventT() const
Definition: Type.h:8207
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2507
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2058
bool isObjCQualifiedIdType() const
Definition: Type.h:8155
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:8410
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:8108
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:8112
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2545
bool isImageType() const
Definition: Type.h:8219
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:8289
bool isPipeType() const
Definition: Type.h:8226
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2680
bool isBitIntType() const
Definition: Type.h:8230
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8264
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8088
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2672
bool isAnyComplexType() const
Definition: Type.h:8100
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8348
bool isHalfType() const
Definition: Type.h:8299
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8364
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2336
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:2296
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:8277
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:2464
bool isQueueT() const
Definition: Type.h:8211
bool isMemberPointerType() const
Definition: Type.h:8046
bool isAtomicType() const
Definition: Type.h:8147
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:8436
bool isObjCIdType() const
Definition: Type.h:8167
bool isMatrixType() const
Definition: Type.h:8122
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2690
bool isComplexIntegerType() const
Definition: Type.cpp:683
bool isUnscopedEnumerationType() const
Definition: Type.cpp:2082
bool isObjCObjectType() const
Definition: Type.h:8138
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:4871
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8569
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4961
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8429
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:7992
bool isObjCObjectPointerType() const
Definition: Type.h:8134
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:8050
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:8390
bool isVectorType() const
Definition: Type.h:8104
bool isObjCQualifiedClassType() const
Definition: Type.h:8161
bool isObjCClassType() const
Definition: Type.h:8173
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2266
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2494
ScalarTypeKind
Definition: Type.h:2645
@ STK_FloatingComplex
Definition: Type.h:2654
@ STK_Floating
Definition: Type.h:2652
@ STK_BlockPointer
Definition: Type.h:2647
@ STK_Bool
Definition: Type.h:2650
@ STK_ObjCObjectPointer
Definition: Type.h:2648
@ STK_FixedPoint
Definition: Type.h:2655
@ STK_IntegralComplex
Definition: Type.h:2653
@ STK_CPointer
Definition: Type.h:2646
@ STK_Integral
Definition: Type.h:2651
@ STK_MemberPointer
Definition: Type.h:2649
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:8000
bool isRealType() const
Definition: Type.cpp:2272
TypeClass getTypeClass() const
Definition: Type.h:2316
bool isSubscriptableVectorType() const
Definition: Type.h:8118
bool isSamplerT() const
Definition: Type.h:8199
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8516
bool isNullPtrType() const
Definition: Type.h:8328
bool isRecordType() const
Definition: Type.h:8092
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4686
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2476
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:6767
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:4861
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:4346
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1025
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3202
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:419
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3941
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition: ExprCXX.cpp:1664
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:1626
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:4691
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:3303
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:3769
Expr * getSizeExpr() const
Definition: Type.h:3788
Represents a GCC generic vector type.
Definition: Type.h:3991
unsigned getNumElements() const
Definition: Type.h:4006
VectorKind getVectorKind() const
Definition: Type.h:4011
QualType getElementType() const
Definition: Type.h:4005
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:209
@ 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:333
@ 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:146
@ OK_VectorComponent
A vector component is an element or range of elements on a vector.
Definition: Specifiers.h:154
@ 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:158
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:151
@ OK_MatrixComponent
A matrix component is a single element of a matrix.
Definition: Specifiers.h:166
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:248
@ SC_Register
Definition: Specifiers.h:254
@ SC_None
Definition: Specifiers.h:247
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:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
const 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:185
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_X86VectorCall
Definition: Specifiers.h:280
@ CC_X86StdCall
Definition: Specifiers.h:277
@ CC_X86FastCall
Definition: Specifiers.h:278
@ 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:4738
@ 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:124
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition: Specifiers.h:170
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition: Specifiers.h:180
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:174
@ NOUR_None
This is an odr-use.
Definition: Specifiers.h:172
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition: Specifiers.h:177
#define false
Definition: stdbool.h:26
#define bool
Definition: stdbool.h:24
ExprResult TransformSourceLocExpr(SourceLocExpr *E)
Definition: SemaExpr.cpp:5432
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
Definition: SemaExpr.cpp:5429
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
Definition: SemaExpr.cpp:5416
ExprResult TransformBlockExpr(BlockExpr *E)
Definition: SemaExpr.cpp:5424
ExprResult TransformLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5423
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E)
Definition: SemaExpr.cpp:5409
bool VisitCallExpr(CallExpr *E)
Definition: SemaExpr.cpp:5374
bool VisitCXXConstructExpr(CXXConstructExpr *E)
Definition: SemaExpr.cpp:5380
const ASTContext & Context
Definition: SemaExpr.cpp:5368
bool VisitLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5401
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E)
Definition: SemaExpr.cpp:5405
bool VisitSourceLocExpr(SourceLocExpr *E)
Definition: SemaExpr.cpp:5390
bool shouldVisitImplicitCode() const
Definition: SemaExpr.cpp:5372
ImmediateCallVisitor(const ASTContext &Ctx)
Definition: SemaExpr.cpp:5369
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:4827
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:5058
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5059
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:12671
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:6287
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition: Sema.h:6321
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition: Sema.h:6367
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition: Sema.h:6326
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:6334
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition: Sema.h:6330
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition: Sema.h:6340
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:6306
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:6344
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:6292
unsigned NumTypos
The number of typos encountered during this expression evaluation context (i.e.
Definition: Sema.h:6300
ExpressionEvaluationContext Context
The expression evaluation context.
Definition: Sema.h:6289
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:6296
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7871
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
uint64_t Width
Definition: ASTContext.h:157
Describes an entity that is being assigned.