clang 24.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"
19#include "clang/AST/ASTLambda.h"
21#include "clang/AST/Attr.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclObjC.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/ExprCXX.h"
30#include "clang/AST/ExprObjC.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
46#include "clang/Sema/DeclSpec.h"
51#include "clang/Sema/Lookup.h"
52#include "clang/Sema/Overload.h"
54#include "clang/Sema/Scope.h"
57#include "clang/Sema/SemaARM.h"
58#include "clang/Sema/SemaCUDA.h"
60#include "clang/Sema/SemaHLSL.h"
61#include "clang/Sema/SemaObjC.h"
65#include "clang/Sema/Template.h"
66#include "llvm/ADT/STLExtras.h"
67#include "llvm/ADT/StringExtras.h"
68#include "llvm/Support/ConvertUTF.h"
69#include "llvm/Support/SaveAndRestore.h"
70#include "llvm/Support/TimeProfiler.h"
71#include "llvm/Support/TypeSize.h"
72#include <limits>
73#include <optional>
74
75using namespace clang;
76using namespace sema;
77
78bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
79 // See if this is an auto-typed variable whose initializer we are parsing.
80 if (ParsingInitForAutoVars.count(D))
81 return false;
82
83 // See if this is a deleted function.
84 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
85 if (FD->isDeleted())
86 return false;
87
88 // If the function has a deduced return type, and we can't deduce it,
89 // then we can't use it either.
90 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
91 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
92 return false;
93
94 // See if this is an aligned allocation/deallocation function that is
95 // unavailable.
96 if (TreatUnavailableAsInvalid &&
98 return false;
99 }
100
101 // See if this function is unavailable.
102 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
103 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
104 return false;
105
107 return false;
108
109 return true;
110}
111
113 // Warn if this is used but marked unused.
114 if (const auto *A = D->getAttr<UnusedAttr>()) {
115 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
116 // should diagnose them.
117 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
118 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
119 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
120 if (DC && !DC->hasAttr<UnusedAttr>())
121 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
122 }
123 }
124}
125
127 assert(Decl && Decl->isDeleted());
128
129 if (Decl->isDefaulted()) {
130 // If the method was explicitly defaulted, point at that declaration.
131 if (!Decl->isImplicit())
132 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
133
134 // Try to diagnose why this special member function was implicitly
135 // deleted. This might fail, if that reason no longer applies.
137 return;
138 }
139
140 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
141 if (Ctor && Ctor->isInheritingConstructor())
143
144 Diag(Decl->getLocation(), diag::note_availability_specified_here)
145 << Decl << 1;
146}
147
148/// Determine whether a FunctionDecl was ever declared with an
149/// explicit storage class.
151 for (auto *I : D->redecls()) {
152 if (I->getStorageClass() != SC_None)
153 return true;
154 }
155 return false;
156}
157
158/// Check whether we're in an extern inline function and referring to a
159/// variable or function with internal linkage (C11 6.7.4p3).
160///
161/// This is only a warning because we used to silently accept this code, but
162/// in many cases it will not behave correctly. This is not enabled in C++ mode
163/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
164/// and so while there may still be user mistakes, most of the time we can't
165/// prove that there are errors.
167 const NamedDecl *D,
168 SourceLocation Loc) {
169 // This is disabled under C++; there are too many ways for this to fire in
170 // contexts where the warning is a false positive, or where it is technically
171 // correct but benign.
172 //
173 // WG14 N3622 which removed the constraint entirely in C2y. It is left
174 // enabled in earlier language modes because this is a constraint in those
175 // language modes. But in C2y mode, we still want to issue the "incompatible
176 // with previous standards" diagnostic, too.
177 if (S.getLangOpts().CPlusPlus)
178 return;
179
180 // Check if this is an inlined function or method.
181 FunctionDecl *Current = S.getCurFunctionDecl();
182 if (!Current)
183 return;
184 if (!Current->isInlined())
185 return;
186 if (!Current->isExternallyVisible())
187 return;
188
189 // Check if the decl has internal linkage.
191 return;
192
193 // Downgrade from ExtWarn to Extension if
194 // (1) the supposedly external inline function is in the main file,
195 // and probably won't be included anywhere else.
196 // (2) the thing we're referencing is a pure function.
197 // (3) the thing we're referencing is another inline function.
198 // This last can give us false negatives, but it's better than warning on
199 // wrappers for simple C library functions.
200 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
201 unsigned DiagID;
202 if (S.getLangOpts().C2y)
203 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
204 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
206 DiagID = diag::ext_internal_in_extern_inline_quiet;
207 else
208 DiagID = diag::ext_internal_in_extern_inline;
209
210 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
212 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
213 << D;
214}
215
217 const FunctionDecl *First = Cur->getFirstDecl();
218
219 // Suggest "static" on the function, if possible.
221 SourceLocation DeclBegin = First->getSourceRange().getBegin();
222 Diag(DeclBegin, diag::note_convert_inline_to_static)
223 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
224 }
225}
226
228 const ObjCInterfaceDecl *UnknownObjCClass,
229 bool ObjCPropertyAccess,
230 bool AvoidPartialAvailabilityChecks,
231 ObjCInterfaceDecl *ClassReceiver,
232 bool SkipTrailingRequiresClause) {
233 SourceLocation Loc = Locs.front();
235 // If there were any diagnostics suppressed by template argument deduction,
236 // emit them now.
237 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
238 if (Pos != SuppressedDiagnostics.end()) {
239 for (const auto &[DiagLoc, PD] : Pos->second) {
240 DiagnosticBuilder Builder(Diags.Report(DiagLoc, PD.getDiagID()));
241 PD.Emit(Builder);
242 }
243 // Clear out the list of suppressed diagnostics, so that we don't emit
244 // them again for this specialization. However, we don't obsolete this
245 // entry from the table, because we want to avoid ever emitting these
246 // diagnostics again.
247 Pos->second.clear();
248 }
249
250 // C++ [basic.start.main]p3:
251 // The function 'main' shall not be used within a program.
252 if (cast<FunctionDecl>(D)->isMain())
253 Diag(Loc, diag::ext_main_used);
254
256 }
257
258 // See if this is an auto-typed variable whose initializer we are parsing.
259 if (ParsingInitForAutoVars.count(D)) {
260 if (isa<BindingDecl>(D)) {
261 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
262 << D->getDeclName();
263 } else {
264 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
265 << diag::ParsingInitFor::Var << D->getDeclName()
266 << cast<VarDecl>(D)->getType();
267 }
268 return true;
269 }
270
271 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
272 // See if this is a deleted function.
273 if (FD->isDeleted()) {
274 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
275 if (Ctor && Ctor->isInheritingConstructor())
276 Diag(Loc, diag::err_deleted_inherited_ctor_use)
277 << Ctor->getParent()
278 << Ctor->getInheritedConstructor().getConstructor()->getParent();
279 else {
280 StringLiteral *Msg = FD->getDeletedMessage();
281 Diag(Loc, diag::err_deleted_function_use)
282 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
283 }
285 return true;
286 }
287
288 // [expr.prim.id]p4
289 // A program that refers explicitly or implicitly to a function with a
290 // trailing requires-clause whose constraint-expression is not satisfied,
291 // other than to declare it, is ill-formed. [...]
292 //
293 // See if this is a function with constraints that need to be satisfied.
294 // Check this before deducing the return type, as it might instantiate the
295 // definition.
296 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
297 ConstraintSatisfaction Satisfaction;
298 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
299 /*ForOverloadResolution*/ true))
300 // A diagnostic will have already been generated (non-constant
301 // constraint expression, for example)
302 return true;
303 if (!Satisfaction.IsSatisfied) {
304 Diag(Loc,
305 diag::err_reference_to_function_with_unsatisfied_constraints)
306 << D;
307 DiagnoseUnsatisfiedConstraint(Satisfaction);
308 return true;
309 }
310 }
311
312 // If the function has a deduced return type, and we can't deduce it,
313 // then we can't use it either.
314 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
315 DeduceReturnType(FD, Loc))
316 return true;
317
318 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
319 return true;
320
321 }
322
323 if (auto *Concept = dyn_cast<ConceptDecl>(D);
325 return true;
326
327 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
328 // Lambdas are only default-constructible or assignable in C++2a onwards.
329 if (MD->getParent()->isLambda() &&
331 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
332 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
333 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
335 }
336 }
337
338 auto getReferencedObjCProp = [](const NamedDecl *D) ->
339 const ObjCPropertyDecl * {
340 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
341 return MD->findPropertyDecl();
342 return nullptr;
343 };
344 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
345 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
346 return true;
347 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
348 return true;
349 }
350
351 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
352 // Only the variables omp_in and omp_out are allowed in the combiner.
353 // Only the variables omp_priv and omp_orig are allowed in the
354 // initializer-clause.
355 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
356 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
357 isa<VarDecl>(D)) {
358 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
360 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
361 return true;
362 }
363
364 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
365 // List-items in map clauses on this construct may only refer to the declared
366 // variable var and entities that could be referenced by a procedure defined
367 // at the same location.
368 // [OpenMP 5.2] Also allow iterator declared variables.
369 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
370 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
371 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
373 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
374 return true;
375 }
376
377 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
378 Diag(Loc, diag::err_use_of_empty_using_if_exists);
379 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
380 return true;
381 }
382
383 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
384 AvoidPartialAvailabilityChecks, ClassReceiver);
385
386 DiagnoseUnusedOfDecl(*this, D, Loc);
387
389
390 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
391 if (getLangOpts().getFPEvalMethod() !=
393 PP.getLastFPEvalPragmaLocation().isValid() &&
394 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
395 Diag(D->getLocation(),
396 diag::err_type_available_only_in_default_eval_method)
397 << D->getName();
398 }
399
400 if (auto *VD = dyn_cast<ValueDecl>(D))
401 checkTypeSupport(VD->getType(), Loc, VD);
402
403 if (LangOpts.SYCLIsDevice ||
404 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
405 if (!Context.getTargetInfo().isTLSSupported())
406 if (const auto *VD = dyn_cast<VarDecl>(D))
407 if (VD->getTLSKind() != VarDecl::TLS_None)
408 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
409 }
410
411 if (LangOpts.SYCLIsDevice && isa<FunctionDecl>(D))
412 SYCL().CheckDeviceUseOfDecl(D, Loc);
413
414 return false;
415}
416
418 ArrayRef<Expr *> Args) {
419 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
420 if (!Attr)
421 return;
422
423 // The number of formal parameters of the declaration.
424 unsigned NumFormalParams;
425
426 // The kind of declaration. This is also an index into a %select in
427 // the diagnostic.
428 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
429
430 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
431 NumFormalParams = MD->param_size();
432 CalleeKind = CK_Method;
433 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
434 NumFormalParams = FD->param_size();
435 CalleeKind = CK_Function;
436 if (FD->hasCXXExplicitFunctionObjectParameter())
437 NumFormalParams++;
438 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
439 QualType Ty = VD->getType();
440 const FunctionType *Fn = nullptr;
441 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
442 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
443 if (!Fn)
444 return;
445 CalleeKind = CK_Function;
446 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
447 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
448 CalleeKind = CK_Block;
449 } else {
450 return;
451 }
452
453 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
454 NumFormalParams = proto->getNumParams();
455 else
456 NumFormalParams = 0;
457 } else {
458 return;
459 }
460
461 // "NullPos" is the number of formal parameters at the end which
462 // effectively count as part of the variadic arguments. This is
463 // useful if you would prefer to not have *any* formal parameters,
464 // but the language forces you to have at least one.
465 unsigned NullPos = Attr->getNullPos();
466 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
467 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
468
469 // The number of arguments which should follow the sentinel.
470 unsigned NumArgsAfterSentinel = Attr->getSentinel();
471
472 // If there aren't enough arguments for all the formal parameters,
473 // the sentinel, and the args after the sentinel, complain.
474 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
475 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
476 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
477 return;
478 }
479
480 // Otherwise, find the sentinel expression.
481 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
482 if (!SentinelExpr)
483 return;
484 if (SentinelExpr->isValueDependent())
485 return;
486 if (Context.isSentinelNullExpr(SentinelExpr))
487 return;
488
489 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
490 // or 'NULL' if those are actually defined in the context. Only use
491 // 'nil' for ObjC methods, where it's much more likely that the
492 // variadic arguments form a list of object pointers.
493 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
494 std::string NullValue;
495 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
496 NullValue = "nil";
497 else if (getLangOpts().CPlusPlus11)
498 NullValue = "nullptr";
499 else if (PP.isMacroDefined("NULL"))
500 NullValue = "NULL";
501 else
502 NullValue = "(void*) 0";
503
504 if (MissingNilLoc.isInvalid())
505 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
506 else
507 Diag(MissingNilLoc, diag::warn_missing_sentinel)
508 << int(CalleeKind)
509 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
510 Diag(D->getLocation(), diag::note_sentinel_here)
511 << int(CalleeKind) << Attr->getRange();
512}
513
515 return E ? E->getSourceRange() : SourceRange();
516}
517
518//===----------------------------------------------------------------------===//
519// Standard Promotions and Conversions
520//===----------------------------------------------------------------------===//
521
522/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
524 // Handle any placeholder expressions which made it here.
525 if (E->hasPlaceholderType()) {
527 if (result.isInvalid()) return ExprError();
528 E = result.get();
529 }
530
531 QualType Ty = E->getType();
532 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
533
534 if (Ty->isFunctionType()) {
535 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
536 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
538 return ExprError();
539
540 E = ImpCastExprToType(E, Context.getPointerType(Ty),
541 CK_FunctionToPointerDecay).get();
542 } else if (Ty->isArrayType()) {
543 // In C90 mode, arrays only promote to pointers if the array expression is
544 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
545 // type 'array of type' is converted to an expression that has type 'pointer
546 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
547 // that has type 'array of type' ...". The relevant change is "an lvalue"
548 // (C90) to "an expression" (C99).
549 //
550 // C++ 4.2p1:
551 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
552 // T" can be converted to an rvalue of type "pointer to T".
553 //
554 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
555 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
556 CK_ArrayToPointerDecay);
557 if (Res.isInvalid())
558 return ExprError();
559 E = Res.get();
560 }
561 }
562 return E;
563}
564
566 // Check to see if we are dereferencing a null pointer. If so,
567 // and if not volatile-qualified, this is undefined behavior that the
568 // optimizer will delete, so warn about it. People sometimes try to use this
569 // to get a deterministic trap and are surprised by clang's behavior. This
570 // only handles the pattern "*null", which is a very syntactic check.
571 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
572 if (UO && UO->getOpcode() == UO_Deref &&
573 UO->getSubExpr()->getType()->isPointerType()) {
574 const LangAS AS =
575 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
576 if ((!isTargetAddressSpace(AS) ||
577 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
578 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
580 !UO->getType().isVolatileQualified()) {
581 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
582 S.PDiag(diag::warn_indirection_through_null)
583 << UO->getSubExpr()->getSourceRange());
584 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
585 S.PDiag(diag::note_indirection_through_null));
586 }
587 }
588}
589
590static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
591 SourceLocation AssignLoc,
592 const Expr* RHS) {
593 const ObjCIvarDecl *IV = OIRE->getDecl();
594 if (!IV)
595 return;
596
597 DeclarationName MemberName = IV->getDeclName();
599 if (!Member || !Member->isStr("isa"))
600 return;
601
602 const Expr *Base = OIRE->getBase();
603 QualType BaseType = Base->getType();
604 if (OIRE->isArrow())
605 BaseType = BaseType->getPointeeType();
606 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
607 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
608 ObjCInterfaceDecl *ClassDeclared = nullptr;
609 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
610 if (!ClassDeclared->getSuperClass()
611 && (*ClassDeclared->ivar_begin()) == IV) {
612 if (RHS) {
613 NamedDecl *ObjectSetClass =
615 &S.Context.Idents.get("object_setClass"),
617 if (ObjectSetClass) {
618 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
619 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
621 "object_setClass(")
623 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
624 << FixItHint::CreateInsertion(RHSLocEnd, ")");
625 }
626 else
627 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
628 } else {
629 NamedDecl *ObjectGetClass =
631 &S.Context.Idents.get("object_getClass"),
633 if (ObjectGetClass)
634 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
636 "object_getClass(")
638 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
639 else
640 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
641 }
642 S.Diag(IV->getLocation(), diag::note_ivar_decl);
643 }
644 }
645}
646
648 // Handle any placeholder expressions which made it here.
649 if (E->hasPlaceholderType()) {
651 if (result.isInvalid()) return ExprError();
652 E = result.get();
653 }
654
655 // C++ [conv.lval]p1:
656 // A glvalue of a non-function, non-array type T can be
657 // converted to a prvalue.
658 if (!E->isGLValue()) return E;
659
660 QualType T = E->getType();
661 assert(!T.isNull() && "r-value conversion on typeless expression?");
662
663 // lvalue-to-rvalue conversion cannot be applied to types that decay to
664 // pointers (i.e. function or array types).
665 if (T->canDecayToPointerType())
666 return E;
667
668 // We don't want to throw lvalue-to-rvalue casts on top of
669 // expressions of certain types in C++.
670 // In HLSL LvaluetoRvalue conversion is allowed on records.
671 if (getLangOpts().CPlusPlus) {
672 if (T == Context.OverloadTy || (T->isRecordType() && !getLangOpts().HLSL) ||
673 (T->isDependentType() && !T->isAnyPointerType() &&
674 !T->isMemberPointerType()))
675 return E;
676 }
677
678 // The C standard is actually really unclear on this point, and
679 // DR106 tells us what the result should be but not why. It's
680 // generally best to say that void types just doesn't undergo
681 // lvalue-to-rvalue at all. Note that expressions of unqualified
682 // 'void' type are never l-values, but qualified void can be.
683 if (T->isVoidType())
684 return E;
685
686 // OpenCL usually rejects direct accesses to values of 'half' type.
687 if (getLangOpts().OpenCL &&
688 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
689 T->isHalfType()) {
690 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
691 << 0 << T;
692 return ExprError();
693 }
694
696 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
697 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
698 &Context.Idents.get("object_getClass"),
700 if (ObjectGetClass)
701 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
702 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
704 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
705 else
706 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
707 }
708 else if (const ObjCIvarRefExpr *OIRE =
709 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
710 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
711
712 // C++ [conv.lval]p1:
713 // [...] If T is a non-class type, the type of the prvalue is the
714 // cv-unqualified version of T. Otherwise, the type of the
715 // rvalue is T.
716 //
717 // C99 6.3.2.1p2:
718 // If the lvalue has qualified type, the value has the unqualified
719 // version of the type of the lvalue; otherwise, the value has the
720 // type of the lvalue.
721 if (T.hasQualifiers())
722 T = T.getUnqualifiedType();
723
724 // Under the MS ABI, lock down the inheritance model now.
725 if (T->isMemberPointerType() &&
726 Context.getTargetInfo().getCXXABI().isMicrosoft())
727 (void)isCompleteType(E->getExprLoc(), T);
728
730 if (Res.isInvalid())
731 return Res;
732 E = Res.get();
733
734 // Loading a __weak object implicitly retains the value, so we need a cleanup to
735 // balance that.
737 Cleanup.setExprNeedsCleanups(true);
738
740 Cleanup.setExprNeedsCleanups(true);
741
743 return ExprError();
744
745 // C++ [conv.lval]p3:
746 // If T is cv std::nullptr_t, the result is a null pointer constant.
747 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
748 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
750
751 // C11 6.3.2.1p2:
752 // ... if the lvalue has atomic type, the value has the non-atomic version
753 // of the type of the lvalue ...
754 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
755 T = Atomic->getValueType().getUnqualifiedType();
756 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
757 nullptr, VK_PRValue, FPOptionsOverride());
758 }
759
760 return Res;
761}
762
765 if (Res.isInvalid())
766 return ExprError();
767 Res = DefaultLvalueConversion(Res.get());
768 if (Res.isInvalid())
769 return ExprError();
770 return Res;
771}
772
774 QualType Ty = E->getType();
775 ExprResult Res = E;
776 // Only do implicit cast for a function type, but not for a pointer
777 // to function type.
778 if (Ty->isFunctionType()) {
779 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
780 CK_FunctionToPointerDecay);
781 if (Res.isInvalid())
782 return ExprError();
783 }
784 Res = DefaultLvalueConversion(Res.get());
785 if (Res.isInvalid())
786 return ExprError();
787 return Res.get();
788}
789
790/// UsualUnaryFPConversions - Promotes floating-point types according to the
791/// current language semantics.
793 QualType Ty = E->getType();
794 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
795
796 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
797 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
798 (getLangOpts().getFPEvalMethod() !=
800 PP.getLastFPEvalPragmaLocation().isValid())) {
801 switch (EvalMethod) {
802 default:
803 llvm_unreachable("Unrecognized float evaluation method");
804 break;
806 llvm_unreachable("Float evaluation method should be set by now");
807 break;
809 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
810 // Widen the expression to double.
811 return Ty->isComplexType()
813 Context.getComplexType(Context.DoubleTy),
814 CK_FloatingComplexCast)
815 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
816 break;
818 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
819 // Widen the expression to long double.
820 return Ty->isComplexType()
822 E, Context.getComplexType(Context.LongDoubleTy),
823 CK_FloatingComplexCast)
824 : ImpCastExprToType(E, Context.LongDoubleTy,
825 CK_FloatingCast);
826 break;
827 }
828 }
829
830 // Half FP have to be promoted to float unless it is natively supported
831 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
832 return ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast);
833
834 return E;
835}
836
837/// UsualUnaryConversions - Performs various conversions that are common to most
838/// operators (C99 6.3). The conversions of array and function types are
839/// sometimes suppressed. For example, the array->pointer conversion doesn't
840/// apply if the array is an argument to the sizeof or address (&) operators.
841/// In these instances, this routine should *not* be called.
843 // First, convert to an r-value.
845 if (Res.isInvalid())
846 return ExprError();
847
848 // Promote floating-point types.
849 Res = UsualUnaryFPConversions(Res.get());
850 if (Res.isInvalid())
851 return ExprError();
852 E = Res.get();
853
854 QualType Ty = E->getType();
855 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
856
857 // Try to perform integral promotions if the object has a theoretically
858 // promotable type.
860 // C99 6.3.1.1p2:
861 //
862 // The following may be used in an expression wherever an int or
863 // unsigned int may be used:
864 // - an object or expression with an integer type whose integer
865 // conversion rank is less than or equal to the rank of int
866 // and unsigned int.
867 // - A bit-field of type _Bool, int, signed int, or unsigned int.
868 //
869 // If an int can represent all values of the original type, the
870 // value is converted to an int; otherwise, it is converted to an
871 // unsigned int. These are called the integer promotions. All
872 // other types are unchanged by the integer promotions.
873
874 QualType PTy = Context.isPromotableBitField(E);
875 if (!PTy.isNull()) {
876 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
877 return E;
878 }
879 if (Context.isPromotableIntegerType(Ty)) {
880 QualType PT = Context.getPromotedIntegerType(Ty);
881 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
882 return E;
883 }
884 }
885 return E;
886}
887
888/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
889/// do not have a prototype. Arguments that have type float or __fp16
890/// are promoted to double. All other argument types are converted by
891/// UsualUnaryConversions().
893 QualType Ty = E->getType();
894 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
895
897 if (Res.isInvalid())
898 return ExprError();
899 E = Res.get();
900
901 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
902 // promote to double.
903 // Note that default argument promotion applies only to float (and
904 // half/fp16); it does not apply to _Float16.
905 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
906 if (BTy && (BTy->getKind() == BuiltinType::Half ||
907 BTy->getKind() == BuiltinType::Float)) {
908 if (getLangOpts().OpenCL &&
909 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
910 if (BTy->getKind() == BuiltinType::Half) {
911 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
912 }
913 } else {
914 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
915 }
916 }
917 if (BTy &&
918 getLangOpts().getExtendIntArgs() ==
920 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
921 Context.getTypeSizeInChars(BTy) <
922 Context.getTypeSizeInChars(Context.LongLongTy)) {
923 E = (Ty->isUnsignedIntegerType())
924 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
925 .get()
926 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
927 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
928 "Unexpected typesize for LongLongTy");
929 }
930
931 // C++ performs lvalue-to-rvalue conversion as a default argument
932 // promotion, even on class types, but note:
933 // C++11 [conv.lval]p2:
934 // When an lvalue-to-rvalue conversion occurs in an unevaluated
935 // operand or a subexpression thereof the value contained in the
936 // referenced object is not accessed. Otherwise, if the glvalue
937 // has a class type, the conversion copy-initializes a temporary
938 // of type T from the glvalue and the result of the conversion
939 // is a prvalue for the temporary.
940 // FIXME: add some way to gate this entire thing for correctness in
941 // potentially potentially evaluated contexts.
945 E->getExprLoc(), E);
946 if (Temp.isInvalid())
947 return ExprError();
948 E = Temp.get();
949 }
950
951 // C++ [expr.call]p7, per CWG722:
952 // An argument that has (possibly cv-qualified) type std::nullptr_t is
953 // converted to void* ([conv.ptr]).
954 // (This does not apply to C23 nullptr)
956 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
957
958 return E;
959}
960
962 if (Ty->isIncompleteType()) {
963 // C++11 [expr.call]p7:
964 // After these conversions, if the argument does not have arithmetic,
965 // enumeration, pointer, pointer to member, or class type, the program
966 // is ill-formed.
967 //
968 // Since we've already performed null pointer conversion, array-to-pointer
969 // decay and function-to-pointer decay, the only such type in C++ is cv
970 // void. This also handles initializer lists as variadic arguments.
971 if (Ty->isVoidType())
972 return VarArgKind::Invalid;
973
974 if (Ty->isObjCObjectType())
975 return VarArgKind::Invalid;
976 return VarArgKind::Valid;
977 }
978
980 return VarArgKind::Invalid;
981
982 if (Context.getTargetInfo().getTriple().isWasm() &&
984 return VarArgKind::Invalid;
985 }
986
987 if (Ty.isCXX98PODType(Context))
988 return VarArgKind::Valid;
989
990 // C++11 [expr.call]p7:
991 // Passing a potentially-evaluated argument of class type (Clause 9)
992 // having a non-trivial copy constructor, a non-trivial move constructor,
993 // or a non-trivial destructor, with no corresponding parameter,
994 // is conditionally-supported with implementation-defined semantics.
997 if (!Record->hasNonTrivialCopyConstructor() &&
998 !Record->hasNonTrivialMoveConstructor() &&
999 !Record->hasNonTrivialDestructor())
1001
1002 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
1003 return VarArgKind::Valid;
1004
1005 if (Ty->isObjCObjectType())
1006 return VarArgKind::Invalid;
1007
1008 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1009 return VarArgKind::Valid;
1010
1011 if (getLangOpts().MSVCCompat)
1013
1014 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1015 return VarArgKind::Valid;
1016
1017 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1018 // permitted to reject them. We should consider doing so.
1019 return VarArgKind::Undefined;
1020}
1021
1023 // Don't allow one to pass an Objective-C interface to a vararg.
1024 const QualType &Ty = E->getType();
1025 VarArgKind VAK = isValidVarArgType(Ty);
1026
1027 // Complain about passing non-POD types through varargs.
1028 switch (VAK) {
1031 E->getBeginLoc(), nullptr,
1032 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1033 [[fallthrough]];
1034 case VarArgKind::Valid:
1035 if (Ty->isRecordType()) {
1036 // This is unlikely to be what the user intended. If the class has a
1037 // 'c_str' member function, the user probably meant to call that.
1038 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1039 PDiag(diag::warn_pass_class_arg_to_vararg)
1040 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1041 }
1042 break;
1043
1046 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1047 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1048 << getLangOpts().CPlusPlus11 << Ty << CT);
1049 break;
1050
1053 Diag(E->getBeginLoc(),
1054 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1055 << Ty << CT;
1056 else if (Ty->isObjCObjectType())
1057 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1058 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1059 << Ty << CT);
1060 else
1061 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1062 << isa<InitListExpr>(E) << Ty << CT;
1063 break;
1064 }
1065}
1066
1068 FunctionDecl *FDecl) {
1069 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1070 // Strip the unbridged-cast placeholder expression off, if applicable.
1071 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1072 (CT == VariadicCallType::Method ||
1073 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1074 E = ObjC().stripARCUnbridgedCast(E);
1075
1076 // Otherwise, do normal placeholder checking.
1077 } else {
1078 ExprResult ExprRes = CheckPlaceholderExpr(E);
1079 if (ExprRes.isInvalid())
1080 return ExprError();
1081 E = ExprRes.get();
1082 }
1083 }
1084
1086 if (ExprRes.isInvalid())
1087 return ExprError();
1088
1089 // Copy blocks to the heap.
1090 if (ExprRes.get()->getType()->isBlockPointerType())
1091 maybeExtendBlockObject(ExprRes);
1092
1093 E = ExprRes.get();
1094
1095 // Diagnostics regarding non-POD argument types are
1096 // emitted along with format string checking in Sema::CheckFunctionCall().
1098 // Turn this into a trap.
1099 CXXScopeSpec SS;
1100 SourceLocation TemplateKWLoc;
1101 UnqualifiedId Name;
1102 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1103 E->getBeginLoc());
1104 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1105 /*HasTrailingLParen=*/true,
1106 /*IsAddressOfOperand=*/false);
1107 if (TrapFn.isInvalid())
1108 return ExprError();
1109
1110 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1111 E->getEndLoc());
1112 if (Call.isInvalid())
1113 return ExprError();
1114
1115 ExprResult Comma =
1116 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1117 if (Comma.isInvalid())
1118 return ExprError();
1119 return Comma.get();
1120 }
1121
1122 if (!getLangOpts().CPlusPlus &&
1124 diag::err_call_incomplete_argument))
1125 return ExprError();
1126
1127 return E;
1128}
1129
1130/// Convert complex integers to complex floats and real integers to
1131/// real floats as required for complex arithmetic. Helper function of
1132/// UsualArithmeticConversions()
1133///
1134/// \return false if the integer expression is an integer type and is
1135/// successfully converted to the (complex) float type.
1137 ExprResult &ComplexExpr,
1138 QualType IntTy,
1139 QualType ComplexTy,
1140 bool SkipCast) {
1141 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1142 if (SkipCast) return false;
1143 if (IntTy->isIntegerType()) {
1144 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1145 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1146 } else {
1147 assert(IntTy->isComplexIntegerType());
1148 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1149 CK_IntegralComplexToFloatingComplex);
1150 }
1151 return false;
1152}
1153
1154// This handles complex/complex, complex/float, or float/complex.
1155// When both operands are complex, the shorter operand is converted to the
1156// type of the longer, and that is the type of the result. This corresponds
1157// to what is done when combining two real floating-point operands.
1158// The fun begins when size promotion occur across type domains.
1159// From H&S 6.3.4: When one operand is complex and the other is a real
1160// floating-point type, the less precise type is converted, within it's
1161// real or complex domain, to the precision of the other type. For example,
1162// when combining a "long double" with a "double _Complex", the
1163// "double _Complex" is promoted to "long double _Complex".
1165 QualType ShorterType,
1166 QualType LongerType,
1167 bool PromotePrecision) {
1168 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1170 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1171
1172 if (PromotePrecision) {
1173 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1174 Shorter =
1175 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1176 } else {
1177 if (LongerIsComplex)
1178 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1179 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1180 }
1181 }
1182 return Result;
1183}
1184
1185/// Handle arithmetic conversion with complex types. Helper function of
1186/// UsualArithmeticConversions()
1188 ExprResult &RHS, QualType LHSType,
1189 QualType RHSType, bool IsCompAssign) {
1190 // Handle (complex) integer types.
1191 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1192 /*SkipCast=*/false))
1193 return LHSType;
1194 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1195 /*SkipCast=*/IsCompAssign))
1196 return RHSType;
1197
1198 // Compute the rank of the two types, regardless of whether they are complex.
1199 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1200 if (Order < 0)
1201 // Promote the precision of the LHS if not an assignment.
1202 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1203 /*PromotePrecision=*/!IsCompAssign);
1204 // Promote the precision of the RHS unless it is already the same as the LHS.
1205 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1206 /*PromotePrecision=*/Order > 0);
1207}
1208
1209/// Handle arithmetic conversion from integer to float. Helper function
1210/// of UsualArithmeticConversions()
1212 ExprResult &IntExpr,
1213 QualType FloatTy, QualType IntTy,
1214 bool ConvertFloat, bool ConvertInt) {
1215 if (IntTy->isIntegerType()) {
1216 if (ConvertInt)
1217 // Convert intExpr to the lhs floating point type.
1218 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1219 CK_IntegralToFloating);
1220 return FloatTy;
1221 }
1222
1223 // Convert both sides to the appropriate complex float.
1224 assert(IntTy->isComplexIntegerType());
1225 QualType result = S.Context.getComplexType(FloatTy);
1226
1227 // _Complex int -> _Complex float
1228 if (ConvertInt)
1229 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1230 CK_IntegralComplexToFloatingComplex);
1231
1232 // float -> _Complex float
1233 if (ConvertFloat)
1234 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1235 CK_FloatingRealToComplex);
1236
1237 return result;
1238}
1239
1240/// Handle arithmethic conversion with floating point types. Helper
1241/// function of UsualArithmeticConversions()
1243 ExprResult &RHS, QualType LHSType,
1244 QualType RHSType, bool IsCompAssign) {
1245 bool LHSFloat = LHSType->isRealFloatingType();
1246 bool RHSFloat = RHSType->isRealFloatingType();
1247
1248 // N1169 4.1.4: If one of the operands has a floating type and the other
1249 // operand has a fixed-point type, the fixed-point operand
1250 // is converted to the floating type [...]
1251 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1252 if (LHSFloat)
1253 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1254 else if (!IsCompAssign)
1255 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1256 return LHSFloat ? LHSType : RHSType;
1257 }
1258
1259 // If we have two real floating types, convert the smaller operand
1260 // to the bigger result.
1261 if (LHSFloat && RHSFloat) {
1262 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1263 if (order > 0) {
1264 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1265 return LHSType;
1266 }
1267
1268 assert(order < 0 && "illegal float comparison");
1269 if (!IsCompAssign)
1270 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1271 return RHSType;
1272 }
1273
1274 if (LHSFloat) {
1275 // Half FP has to be promoted to float unless it is natively supported
1276 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1277 LHSType = S.Context.FloatTy;
1278
1279 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1280 /*ConvertFloat=*/!IsCompAssign,
1281 /*ConvertInt=*/ true);
1282 }
1283 assert(RHSFloat);
1284 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1285 /*ConvertFloat=*/ true,
1286 /*ConvertInt=*/!IsCompAssign);
1287}
1288
1289/// Diagnose attempts to convert between __float128, __ibm128 and
1290/// long double if there is no support for such conversion.
1291/// Helper function of UsualArithmeticConversions().
1292static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1293 QualType RHSType) {
1294 // No issue if either is not a floating point type.
1295 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1296 return false;
1297
1298 // No issue if both have the same 128-bit float semantics.
1299 auto *LHSComplex = LHSType->getAs<ComplexType>();
1300 auto *RHSComplex = RHSType->getAs<ComplexType>();
1301
1302 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1303 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1304
1305 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1306 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1307
1308 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1309 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1310 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1311 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1312 return false;
1313
1314 return true;
1315}
1316
1317typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1318
1319namespace {
1320/// These helper callbacks are placed in an anonymous namespace to
1321/// permit their use as function template parameters.
1322ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1323 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1324}
1325
1326ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1327 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1328 CK_IntegralComplexCast);
1329}
1330}
1331
1332/// Handle integer arithmetic conversions. Helper function of
1333/// UsualArithmeticConversions()
1334template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1336 ExprResult &RHS, QualType LHSType,
1337 QualType RHSType, bool IsCompAssign) {
1338 // The rules for this case are in C99 6.3.1.8
1339 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1340 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1341 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1342 if (LHSSigned == RHSSigned) {
1343 // Same signedness; use the higher-ranked type
1344 if (order >= 0) {
1345 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1346 return LHSType;
1347 } else if (!IsCompAssign)
1348 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1349 return RHSType;
1350 } else if (order != (LHSSigned ? 1 : -1)) {
1351 // The unsigned type has greater than or equal rank to the
1352 // signed type, so use the unsigned type
1353 if (RHSSigned) {
1354 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1355 return LHSType;
1356 } else if (!IsCompAssign)
1357 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1358 return RHSType;
1359 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1360 // The two types are different widths; if we are here, that
1361 // means the signed type is larger than the unsigned type, so
1362 // use the signed type.
1363 if (LHSSigned) {
1364 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1365 return LHSType;
1366 } else if (!IsCompAssign)
1367 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1368 return RHSType;
1369 } else {
1370 // The signed type is higher-ranked than the unsigned type,
1371 // but isn't actually any bigger (like unsigned int and long
1372 // on most 32-bit systems). Use the unsigned type corresponding
1373 // to the signed type.
1374 QualType result =
1375 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1376 RHS = (*doRHSCast)(S, RHS.get(), result);
1377 if (!IsCompAssign)
1378 LHS = (*doLHSCast)(S, LHS.get(), result);
1379 return result;
1380 }
1381}
1382
1383/// Handle conversions with GCC complex int extension. Helper function
1384/// of UsualArithmeticConversions()
1386 ExprResult &RHS, QualType LHSType,
1387 QualType RHSType,
1388 bool IsCompAssign) {
1389 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1390 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1391
1392 if (LHSComplexInt && RHSComplexInt) {
1393 QualType LHSEltType = LHSComplexInt->getElementType();
1394 QualType RHSEltType = RHSComplexInt->getElementType();
1395 QualType ScalarType =
1397 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1398
1399 return S.Context.getComplexType(ScalarType);
1400 }
1401
1402 if (LHSComplexInt) {
1403 QualType LHSEltType = LHSComplexInt->getElementType();
1404 QualType ScalarType =
1406 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1408 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1409 CK_IntegralRealToComplex);
1410
1411 return ComplexType;
1412 }
1413
1414 assert(RHSComplexInt);
1415
1416 QualType RHSEltType = RHSComplexInt->getElementType();
1417 QualType ScalarType =
1419 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1421
1422 if (!IsCompAssign)
1423 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1424 CK_IntegralRealToComplex);
1425 return ComplexType;
1426}
1427
1429 ExprResult &RHS,
1430 QualType LHSType,
1431 QualType RHSType,
1432 bool IsCompAssign) {
1433
1434 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1435 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1436
1437 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1438 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1439
1440 bool LHSHasTrap =
1441 LhsOBT && LhsOBT->getBehaviorKind() ==
1442 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1443 bool RHSHasTrap =
1444 RhsOBT && RhsOBT->getBehaviorKind() ==
1445 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1446 bool LHSHasWrap =
1447 LhsOBT && LhsOBT->getBehaviorKind() ==
1448 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1449 bool RHSHasWrap =
1450 RhsOBT && RhsOBT->getBehaviorKind() ==
1451 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1452
1453 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1454 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1455
1456 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1457 if (LHSHasTrap || RHSHasTrap)
1458 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1459 else if (LHSHasWrap || RHSHasWrap)
1460 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1461
1462 QualType LHSConvType = LHSUnderlyingType;
1463 QualType RHSConvType = RHSUnderlyingType;
1464 if (DominantBehavior) {
1465 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1466 LHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1467 LHSUnderlyingType);
1468 else
1469 LHSConvType = LHSType;
1470
1471 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1472 RHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1473 RHSUnderlyingType);
1474 else
1475 RHSConvType = RHSType;
1476 }
1477
1479 S, LHS, RHS, LHSConvType, RHSConvType, IsCompAssign);
1480}
1481
1482/// Return the rank of a given fixed point or integer type. The value itself
1483/// doesn't matter, but the values must be increasing with proper increasing
1484/// rank as described in N1169 4.1.1.
1485static unsigned GetFixedPointRank(QualType Ty) {
1486 const auto *BTy = Ty->getAs<BuiltinType>();
1487 assert(BTy && "Expected a builtin type.");
1488
1489 switch (BTy->getKind()) {
1490 case BuiltinType::ShortFract:
1491 case BuiltinType::UShortFract:
1492 case BuiltinType::SatShortFract:
1493 case BuiltinType::SatUShortFract:
1494 return 1;
1495 case BuiltinType::Fract:
1496 case BuiltinType::UFract:
1497 case BuiltinType::SatFract:
1498 case BuiltinType::SatUFract:
1499 return 2;
1500 case BuiltinType::LongFract:
1501 case BuiltinType::ULongFract:
1502 case BuiltinType::SatLongFract:
1503 case BuiltinType::SatULongFract:
1504 return 3;
1505 case BuiltinType::ShortAccum:
1506 case BuiltinType::UShortAccum:
1507 case BuiltinType::SatShortAccum:
1508 case BuiltinType::SatUShortAccum:
1509 return 4;
1510 case BuiltinType::Accum:
1511 case BuiltinType::UAccum:
1512 case BuiltinType::SatAccum:
1513 case BuiltinType::SatUAccum:
1514 return 5;
1515 case BuiltinType::LongAccum:
1516 case BuiltinType::ULongAccum:
1517 case BuiltinType::SatLongAccum:
1518 case BuiltinType::SatULongAccum:
1519 return 6;
1520 default:
1521 if (BTy->isInteger())
1522 return 0;
1523 llvm_unreachable("Unexpected fixed point or integer type");
1524 }
1525}
1526
1527/// handleFixedPointConversion - Fixed point operations between fixed
1528/// point types and integers or other fixed point types do not fall under
1529/// usual arithmetic conversion since these conversions could result in loss
1530/// of precsision (N1169 4.1.4). These operations should be calculated with
1531/// the full precision of their result type (N1169 4.1.6.2.1).
1533 QualType RHSTy) {
1534 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1535 "Expected at least one of the operands to be a fixed point type");
1536 assert((LHSTy->isFixedPointOrIntegerType() ||
1537 RHSTy->isFixedPointOrIntegerType()) &&
1538 "Special fixed point arithmetic operation conversions are only "
1539 "applied to ints or other fixed point types");
1540
1541 // If one operand has signed fixed-point type and the other operand has
1542 // unsigned fixed-point type, then the unsigned fixed-point operand is
1543 // converted to its corresponding signed fixed-point type and the resulting
1544 // type is the type of the converted operand.
1545 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1547 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1549
1550 // The result type is the type with the highest rank, whereby a fixed-point
1551 // conversion rank is always greater than an integer conversion rank; if the
1552 // type of either of the operands is a saturating fixedpoint type, the result
1553 // type shall be the saturating fixed-point type corresponding to the type
1554 // with the highest rank; the resulting value is converted (taking into
1555 // account rounding and overflow) to the precision of the resulting type.
1556 // Same ranks between signed and unsigned types are resolved earlier, so both
1557 // types are either signed or both unsigned at this point.
1558 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1559 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1560
1561 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1562
1564 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1565
1566 return ResultTy;
1567}
1568
1569/// Check that the usual arithmetic conversions can be performed on this pair of
1570/// expressions that might be of enumeration type.
1572 SourceLocation Loc,
1573 ArithConvKind ACK) {
1574 // C++2a [expr.arith.conv]p1:
1575 // If one operand is of enumeration type and the other operand is of a
1576 // different enumeration type or a floating-point type, this behavior is
1577 // deprecated ([depr.arith.conv.enum]).
1578 //
1579 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1580 // Eventually we will presumably reject these cases (in C++23 onwards?).
1582 R = RHS->getEnumCoercedType(Context);
1583 bool LEnum = L->isUnscopedEnumerationType(),
1584 REnum = R->isUnscopedEnumerationType();
1585 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1586 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1587 (REnum && L->isFloatingType())) {
1588 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1590 ? diag::warn_arith_conv_enum_float_cxx20
1591 : diag::warn_arith_conv_enum_float)
1592 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1593 << L << R;
1594 } else if (!IsCompAssign && LEnum && REnum &&
1595 !Context.hasSameUnqualifiedType(L, R)) {
1596 unsigned DiagID;
1597 // In C++ 26, usual arithmetic conversions between 2 different enum types
1598 // are ill-formed.
1600 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1601 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1602 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1603 // If either enumeration type is unnamed, it's less likely that the
1604 // user cares about this, but this situation is still deprecated in
1605 // C++2a. Use a different warning group.
1606 DiagID = getLangOpts().CPlusPlus20
1607 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1608 : diag::warn_arith_conv_mixed_anon_enum_types;
1609 } else if (ACK == ArithConvKind::Conditional) {
1610 // Conditional expressions are separated out because they have
1611 // historically had a different warning flag.
1612 DiagID = getLangOpts().CPlusPlus20
1613 ? diag::warn_conditional_mixed_enum_types_cxx20
1614 : diag::warn_conditional_mixed_enum_types;
1615 } else if (ACK == ArithConvKind::Comparison) {
1616 // Comparison expressions are separated out because they have
1617 // historically had a different warning flag.
1618 DiagID = getLangOpts().CPlusPlus20
1619 ? diag::warn_comparison_mixed_enum_types_cxx20
1620 : diag::warn_comparison_mixed_enum_types;
1621 } else {
1622 DiagID = getLangOpts().CPlusPlus20
1623 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1624 : diag::warn_arith_conv_mixed_enum_types;
1625 }
1626 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1627 << (int)ACK << L << R;
1628 }
1629}
1630
1632 Expr *RHS, SourceLocation Loc,
1633 ArithConvKind ACK) {
1634 QualType LHSType = LHS->getType().getUnqualifiedType();
1635 QualType RHSType = RHS->getType().getUnqualifiedType();
1636
1637 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1638 !RHSType->isUnicodeCharacterType())
1639 return;
1640
1641 if (ACK == ArithConvKind::Comparison) {
1642 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1643 return;
1644
1645 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1646 if (T->isChar8Type())
1647 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1648 if (T->isChar16Type())
1649 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1650 assert(T->isChar32Type());
1651 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1652 };
1653
1654 Expr::EvalResult LHSRes, RHSRes;
1655 bool LHSSuccess = LHS->EvaluateAsInt(LHSRes, SemaRef.getASTContext(),
1657 SemaRef.isConstantEvaluatedContext());
1658 bool RHSuccess = RHS->EvaluateAsInt(RHSRes, SemaRef.getASTContext(),
1660 SemaRef.isConstantEvaluatedContext());
1661
1662 // Don't warn if the one known value is a representable
1663 // in the type of both expressions.
1664 if (LHSSuccess != RHSuccess) {
1665 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1666 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1667 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1668 return;
1669 }
1670
1671 if (!LHSSuccess || !RHSuccess) {
1672 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types)
1673 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1674 << RHSType;
1675 return;
1676 }
1677
1678 llvm::APSInt LHSValue(32);
1679 LHSValue = LHSRes.Val.getInt();
1680 llvm::APSInt RHSValue(32);
1681 RHSValue = RHSRes.Val.getInt();
1682
1683 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1684 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1685 if (LHSSafe && RHSSafe)
1686 return;
1687
1688 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types_constant)
1689 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1690 << FormatUTFCodeUnitAsCodepoint(LHSValue.getExtValue(), LHSType)
1691 << FormatUTFCodeUnitAsCodepoint(RHSValue.getExtValue(), RHSType);
1692 return;
1693 }
1694
1695 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1696 return;
1697
1698 SemaRef.Diag(Loc, diag::warn_arith_conv_mixed_unicode_types)
1699 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1700 << RHSType;
1701}
1702
1703/// UsualArithmeticConversions - Performs various conversions that are common to
1704/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1705/// routine returns the first non-arithmetic type found. The client is
1706/// responsible for emitting appropriate error diagnostics.
1708 SourceLocation Loc,
1709 ArithConvKind ACK) {
1710
1711 checkEnumArithmeticConversions(LHS.get(), RHS.get(), Loc, ACK);
1712
1713 CheckUnicodeArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1714
1715 if (ACK != ArithConvKind::CompAssign) {
1716 LHS = UsualUnaryConversions(LHS.get());
1717 if (LHS.isInvalid())
1718 return QualType();
1719 }
1720
1721 RHS = UsualUnaryConversions(RHS.get());
1722 if (RHS.isInvalid())
1723 return QualType();
1724
1725 // For conversion purposes, we ignore any qualifiers.
1726 // For example, "const float" and "float" are equivalent.
1727 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1728 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1729
1730 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1731 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1732 LHSType = AtomicLHS->getValueType();
1733
1734 // If both types are identical, no conversion is needed.
1735 if (Context.hasSameType(LHSType, RHSType))
1736 return Context.getCommonSugaredType(LHSType, RHSType);
1737
1738 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1739 // The caller can deal with this (e.g. pointer + int).
1740 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1741 return QualType();
1742
1743 // Apply unary and bitfield promotions to the LHS's type.
1744 QualType LHSUnpromotedType = LHSType;
1745 if (Context.isPromotableIntegerType(LHSType))
1746 LHSType = Context.getPromotedIntegerType(LHSType);
1747 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1748 if (!LHSBitfieldPromoteTy.isNull())
1749 LHSType = LHSBitfieldPromoteTy;
1750 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1751 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1752
1753 // If both types are identical, no conversion is needed.
1754 if (Context.hasSameType(LHSType, RHSType))
1755 return Context.getCommonSugaredType(LHSType, RHSType);
1756
1757 // At this point, we have two different arithmetic types.
1758
1759 if ((LHSType->isFixedPointType() && RHSType->isBitIntType()) ||
1760 (LHSType->isBitIntType() && RHSType->isFixedPointType()))
1761 return QualType();
1762
1763 // Diagnose attempts to convert between __ibm128, __float128 and long double
1764 // where such conversions currently can't be handled.
1765 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1766 return QualType();
1767
1768 // Handle complex types first (C99 6.3.1.8p1).
1769 if (LHSType->isComplexType() || RHSType->isComplexType())
1770 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1772
1773 // Now handle "real" floating types (i.e. float, double, long double).
1774 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1775 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1777
1778 // Handle GCC complex int extension.
1779 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1780 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1782
1783 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1784 return handleFixedPointConversion(*this, LHSType, RHSType);
1785
1786 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1788 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1789
1790 // Finally, we have two differing integer types.
1792 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1793}
1794
1795//===----------------------------------------------------------------------===//
1796// Semantic Analysis for various Expression Types
1797//===----------------------------------------------------------------------===//
1798
1799
1801 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1802 bool PredicateIsExpr, void *ControllingExprOrType,
1803 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1804 unsigned NumAssocs = ArgTypes.size();
1805 assert(NumAssocs == ArgExprs.size());
1806
1807 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1808 for (unsigned i = 0; i < NumAssocs; ++i) {
1809 if (ArgTypes[i])
1810 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1811 else
1812 Types[i] = nullptr;
1813 }
1814
1815 // If we have a controlling type, we need to convert it from a parsed type
1816 // into a semantic type and then pass that along.
1817 if (!PredicateIsExpr) {
1818 TypeSourceInfo *ControllingType;
1819 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1820 &ControllingType);
1821 assert(ControllingType && "couldn't get the type out of the parser");
1822 ControllingExprOrType = ControllingType;
1823 }
1824
1826 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1827 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1828 delete [] Types;
1829 return ER;
1830}
1831
1832// Helper function to determine type compatibility for C _Generic expressions.
1833// Multiple compatible types within the same _Generic expression is ambiguous
1834// and not valid.
1836 QualType U) {
1837 // Try to handle special types like OverflowBehaviorTypes
1838 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1839 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1840
1841 if (TOBT || UOBT) {
1842 if (TOBT && UOBT) {
1843 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1844 return Ctx.typesAreCompatible(TOBT->getUnderlyingType(),
1845 UOBT->getUnderlyingType());
1846 return false;
1847 }
1848 return false;
1849 }
1850
1851 // We're dealing with types that don't require special handling.
1852 return Ctx.typesAreCompatible(T, U);
1853}
1854
1856 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1857 bool PredicateIsExpr, void *ControllingExprOrType,
1859 unsigned NumAssocs = Types.size();
1860 assert(NumAssocs == Exprs.size());
1861 assert(ControllingExprOrType &&
1862 "Must have either a controlling expression or a controlling type");
1863
1864 Expr *ControllingExpr = nullptr;
1865 TypeSourceInfo *ControllingType = nullptr;
1866 if (PredicateIsExpr) {
1867 // Decay and strip qualifiers for the controlling expression type, and
1868 // handle placeholder type replacement. See committee discussion from WG14
1869 // DR423.
1873 reinterpret_cast<Expr *>(ControllingExprOrType));
1874 if (R.isInvalid())
1875 return ExprError();
1876 ControllingExpr = R.get();
1877 } else {
1878 // The extension form uses the type directly rather than converting it.
1879 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1880 if (!ControllingType)
1881 return ExprError();
1882 }
1883
1884 bool TypeErrorFound = false,
1885 IsResultDependent = ControllingExpr
1886 ? ControllingExpr->isTypeDependent()
1887 : ControllingType->getType()->isDependentType(),
1888 ContainsUnexpandedParameterPack =
1889 ControllingExpr
1890 ? ControllingExpr->containsUnexpandedParameterPack()
1891 : ControllingType->getType()->containsUnexpandedParameterPack();
1892
1893 // The controlling expression is an unevaluated operand, so side effects are
1894 // likely unintended.
1895 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1896 ControllingExpr->HasSideEffects(Context, false))
1897 Diag(ControllingExpr->getExprLoc(),
1898 diag::warn_side_effects_unevaluated_context);
1899
1900 for (unsigned i = 0; i < NumAssocs; ++i) {
1901 if (Exprs[i]->containsUnexpandedParameterPack())
1902 ContainsUnexpandedParameterPack = true;
1903
1904 if (Types[i]) {
1905 if (Types[i]->getType()->containsUnexpandedParameterPack())
1906 ContainsUnexpandedParameterPack = true;
1907
1908 if (Types[i]->getType()->isDependentType()) {
1909 IsResultDependent = true;
1910 } else {
1911 // We relax the restriction on use of incomplete types and non-object
1912 // types with the type-based extension of _Generic. Allowing incomplete
1913 // objects means those can be used as "tags" for a type-safe way to map
1914 // to a value. Similarly, matching on function types rather than
1915 // function pointer types can be useful. However, the restriction on VM
1916 // types makes sense to retain as there are open questions about how
1917 // the selection can be made at compile time.
1918 //
1919 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1920 // complete object type other than a variably modified type."
1921 // C2y removed the requirement that an expression form must
1922 // use a complete type, though it's still as-if the type has undergone
1923 // lvalue conversion. We support this as an extension in C23 and
1924 // earlier because GCC does so.
1925 unsigned D = 0;
1926 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1927 D = LangOpts.C2y ? diag::compat_c2y_assoc_type_incomplete
1928 : diag::compat_pre_c2y_assoc_type_incomplete;
1929 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1930 D = diag::err_assoc_type_nonobject;
1931 else if (Types[i]->getType()->isVariablyModifiedType())
1932 D = diag::err_assoc_type_variably_modified;
1933 else if (ControllingExpr) {
1934 // Because the controlling expression undergoes lvalue conversion,
1935 // array conversion, and function conversion, an association which is
1936 // of array type, function type, or is qualified can never be
1937 // reached. We will warn about this so users are less surprised by
1938 // the unreachable association. However, we don't have to handle
1939 // function types; that's not an object type, so it's handled above.
1940 //
1941 // The logic is somewhat different for C++ because C++ has different
1942 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1943 // If T is a non-class type, the type of the prvalue is the cv-
1944 // unqualified version of T. Otherwise, the type of the prvalue is T.
1945 // The result of these rules is that all qualified types in an
1946 // association in C are unreachable, and in C++, only qualified non-
1947 // class types are unreachable.
1948 //
1949 // NB: this does not apply when the first operand is a type rather
1950 // than an expression, because the type form does not undergo
1951 // conversion.
1952 unsigned Reason = 0;
1953 QualType QT = Types[i]->getType();
1954 if (QT->isArrayType())
1955 Reason = 1;
1956 else if (QT.hasQualifiers() &&
1957 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1958 Reason = 2;
1959
1960 if (Reason)
1961 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1962 diag::warn_unreachable_association)
1963 << QT << (Reason - 1);
1964 }
1965
1966 if (D != 0) {
1967 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1968 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1969 if (getDiagnostics().getDiagnosticLevel(
1970 D, Types[i]->getTypeLoc().getBeginLoc()) >=
1972 TypeErrorFound = true;
1973 }
1974
1975 // C11 6.5.1.1p2 "No two generic associations in the same generic
1976 // selection shall specify compatible types."
1977 for (unsigned j = i+1; j < NumAssocs; ++j)
1978 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1980 Types[j]->getType())) {
1981 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1982 diag::err_assoc_compatible_types)
1983 << Types[j]->getTypeLoc().getSourceRange()
1984 << Types[j]->getType()
1985 << Types[i]->getType();
1986 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1987 diag::note_compat_assoc)
1988 << Types[i]->getTypeLoc().getSourceRange()
1989 << Types[i]->getType();
1990 TypeErrorFound = true;
1991 }
1992 }
1993 }
1994 }
1995 if (TypeErrorFound)
1996 return ExprError();
1997
1998 // If we determined that the generic selection is result-dependent, don't
1999 // try to compute the result expression.
2000 if (IsResultDependent) {
2001 if (ControllingExpr)
2002 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
2003 Types, Exprs, DefaultLoc, RParenLoc,
2004 ContainsUnexpandedParameterPack);
2005 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
2006 Exprs, DefaultLoc, RParenLoc,
2007 ContainsUnexpandedParameterPack);
2008 }
2009
2010 SmallVector<unsigned, 1> CompatIndices;
2011 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2012 // Look at the canonical type of the controlling expression in case it was a
2013 // deduced type like __auto_type. However, when issuing diagnostics, use the
2014 // type the user wrote in source rather than the canonical one.
2015 for (unsigned i = 0; i < NumAssocs; ++i) {
2016 if (!Types[i])
2017 DefaultIndex = i;
2018 else {
2019 bool Compatible;
2020 QualType ControllingQT =
2021 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2022 : ControllingType->getType().getCanonicalType();
2023 QualType AssocQT = Types[i]->getType();
2024
2025 Compatible =
2026 areTypesCompatibleForGeneric(Context, ControllingQT, AssocQT);
2027
2028 if (Compatible)
2029 CompatIndices.push_back(i);
2030 }
2031 }
2032
2033 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2034 TypeSourceInfo *ControllingType) {
2035 // We strip parens here because the controlling expression is typically
2036 // parenthesized in macro definitions.
2037 if (ControllingExpr)
2038 ControllingExpr = ControllingExpr->IgnoreParens();
2039
2040 SourceRange SR = ControllingExpr
2041 ? ControllingExpr->getSourceRange()
2042 : ControllingType->getTypeLoc().getSourceRange();
2043 QualType QT = ControllingExpr ? ControllingExpr->getType()
2044 : ControllingType->getType();
2045
2046 return std::make_pair(SR, QT);
2047 };
2048
2049 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2050 // type compatible with at most one of the types named in its generic
2051 // association list."
2052 if (CompatIndices.size() > 1) {
2053 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2054 SourceRange SR = P.first;
2055 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
2056 << SR << P.second << (unsigned)CompatIndices.size();
2057 for (unsigned I : CompatIndices) {
2058 Diag(Types[I]->getTypeLoc().getBeginLoc(),
2059 diag::note_compat_assoc)
2060 << Types[I]->getTypeLoc().getSourceRange()
2061 << Types[I]->getType();
2062 }
2063 return ExprError();
2064 }
2065
2066 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2067 // its controlling expression shall have type compatible with exactly one of
2068 // the types named in its generic association list."
2069 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2070 CompatIndices.size() == 0) {
2071 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2072 SourceRange SR = P.first;
2073 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
2074 return ExprError();
2075 }
2076
2077 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2078 // type name that is compatible with the type of the controlling expression,
2079 // then the result expression of the generic selection is the expression
2080 // in that generic association. Otherwise, the result expression of the
2081 // generic selection is the expression in the default generic association."
2082 unsigned ResultIndex =
2083 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2084
2085 if (ControllingExpr) {
2087 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
2088 ContainsUnexpandedParameterPack, ResultIndex);
2089 }
2091 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
2092 ContainsUnexpandedParameterPack, ResultIndex);
2093}
2094
2096 switch (Kind) {
2097 default:
2098 llvm_unreachable("unexpected TokenKind");
2099 case tok::kw___func__:
2100 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2101 case tok::kw___FUNCTION__:
2103 case tok::kw___FUNCDNAME__:
2104 return PredefinedIdentKind::FuncDName; // [MS]
2105 case tok::kw___FUNCSIG__:
2106 return PredefinedIdentKind::FuncSig; // [MS]
2107 case tok::kw_L__FUNCTION__:
2108 return PredefinedIdentKind::LFunction; // [MS]
2109 case tok::kw_L__FUNCSIG__:
2110 return PredefinedIdentKind::LFuncSig; // [MS]
2111 case tok::kw___PRETTY_FUNCTION__:
2113 }
2114}
2115
2116/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2117/// to determine the value of a PredefinedExpr. This can be either a
2118/// block, lambda, captured statement, function, otherwise a nullptr.
2120 auto LSI = S.FunctionScopes.rbegin();
2121
2122 auto tryAdjustLambdaContext = [&S, &LSI](DeclContext *&DC) {
2123 if (isLambdaCallOperator(DC)) {
2124 auto E = S.FunctionScopes.rend();
2125 while (LSI != E && isa<CapturingScopeInfo>(*LSI) &&
2126 !isa<LambdaScopeInfo>(*LSI))
2127 ++LSI;
2128 assert(LSI != E && "Should be in a lambda scope info");
2129 if (dyn_cast<LambdaScopeInfo>(*LSI)->BeforeCompoundStatement)
2130 DC = DC->getParent();
2131 ++LSI;
2132 }
2133 };
2134
2135 tryAdjustLambdaContext(DC);
2136 while (DC &&
2138 DC = DC->getParent();
2139 tryAdjustLambdaContext(DC);
2140 }
2141
2142 return cast_or_null<Decl>(DC);
2143}
2144
2145/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2146/// location of the token and the offset of the ud-suffix within it.
2148 unsigned Offset) {
2149 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
2150 S.getLangOpts());
2151}
2152
2153/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2154/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2156 IdentifierInfo *UDSuffix,
2157 SourceLocation UDSuffixLoc,
2158 ArrayRef<Expr*> Args,
2159 SourceLocation LitEndLoc) {
2160 assert(Args.size() <= 2 && "too many arguments for literal operator");
2161
2162 QualType ArgTy[2];
2163 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2164 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2165 if (ArgTy[ArgIdx]->isArrayType())
2166 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
2167 }
2168
2169 DeclarationName OpName =
2171 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2172 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2173
2174 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2175 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
2176 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2177 /*AllowStringTemplatePack*/ false,
2178 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2179 return ExprError();
2180
2181 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
2182}
2183
2185 // StringToks needs backing storage as it doesn't hold array elements itself
2186 std::vector<Token> ExpandedToks;
2187 if (getLangOpts().MicrosoftExt)
2188 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2189
2190 StringLiteralParser Literal(StringToks, PP,
2192 if (Literal.hadError)
2193 return ExprError();
2194
2195 SmallVector<SourceLocation, 4> StringTokLocs;
2196 for (const Token &Tok : StringToks)
2197 StringTokLocs.push_back(Tok.getLocation());
2198
2199 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2201 false, {}, StringTokLocs);
2202
2203 if (!Literal.getUDSuffix().empty()) {
2204 SourceLocation UDSuffixLoc =
2205 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2206 Literal.getUDSuffixOffset());
2207 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2208 }
2209
2210 return Lit;
2211}
2212
2213std::vector<Token>
2215 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2216 // local macros that expand to string literals that may be concatenated.
2217 // These macros are expanded here (in Sema), because StringLiteralParser
2218 // (in Lex) doesn't know the enclosing function (because it hasn't been
2219 // parsed yet).
2220 assert(getLangOpts().MicrosoftExt);
2221
2222 // Note: Although function local macros are defined only inside functions,
2223 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2224 // expansion of macros into empty string literals without additional checks.
2225 Decl *CurrentDecl = getPredefinedExprDecl(*this, CurContext);
2226 if (!CurrentDecl)
2227 CurrentDecl = Context.getTranslationUnitDecl();
2228
2229 std::vector<Token> ExpandedToks;
2230 ExpandedToks.reserve(Toks.size());
2231 for (const Token &Tok : Toks) {
2233 assert(tok::isStringLiteral(Tok.getKind()));
2234 ExpandedToks.emplace_back(Tok);
2235 continue;
2236 }
2237 if (isa<TranslationUnitDecl>(CurrentDecl))
2238 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2239 // Stringify predefined expression
2240 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2241 << Tok.getKind();
2242 SmallString<64> Str;
2243 llvm::raw_svector_ostream OS(Str);
2244 Token &Exp = ExpandedToks.emplace_back();
2245 Exp.startToken();
2246 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2247 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2248 OS << 'L';
2249 Exp.setKind(tok::wide_string_literal);
2250 } else {
2251 Exp.setKind(tok::string_literal);
2252 }
2253 OS << '"'
2255 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2256 << '"';
2257 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2258 }
2259 return ExpandedToks;
2260}
2261
2264 assert(!StringToks.empty() && "Must have at least one string!");
2265
2266 // StringToks needs backing storage as it doesn't hold array elements itself
2267 std::vector<Token> ExpandedToks;
2268 if (getLangOpts().MicrosoftExt)
2269 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2270
2271 StringLiteralParser Literal(
2273 if (Literal.hadError)
2274 return ExprError();
2275
2276 SmallVector<SourceLocation, 4> StringTokLocs;
2277 for (const Token &Tok : StringToks)
2278 StringTokLocs.push_back(Tok.getLocation());
2279
2280 QualType CharTy = Context.CharTy;
2282 if (Literal.isWide()) {
2283 CharTy = Context.getWideCharType();
2285 } else if (Literal.isUTF8()) {
2286 if (getLangOpts().Char8)
2287 CharTy = Context.Char8Ty;
2288 else if (getLangOpts().C23)
2289 CharTy = Context.UnsignedCharTy;
2291 } else if (Literal.isUTF16()) {
2292 CharTy = Context.Char16Ty;
2294 } else if (Literal.isUTF32()) {
2295 CharTy = Context.Char32Ty;
2297 } else if (Literal.isPascal()) {
2298 CharTy = Context.UnsignedCharTy;
2299 }
2300
2301 // Warn on u8 string literals before C++20 and C23, whose type
2302 // was an array of char before but becomes an array of char8_t.
2303 // In C++20, it cannot be used where a pointer to char is expected.
2304 // In C23, it might have an unexpected value if char was signed.
2305 if (Kind == StringLiteralKind::UTF8 &&
2307 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2308 : !getLangOpts().C23)) {
2309 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2310 ? diag::warn_cxx20_compat_utf8_string
2311 : diag::warn_c23_compat_utf8_string);
2312
2313 // Create removals for all 'u8' prefixes in the string literal(s). This
2314 // ensures C++20/C23 compatibility (but may change the program behavior when
2315 // built by non-Clang compilers for which the execution character set is
2316 // not always UTF-8).
2317 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2318 SourceLocation RemovalDiagLoc;
2319 for (const Token &Tok : StringToks) {
2320 if (Tok.getKind() == tok::utf8_string_literal) {
2321 if (RemovalDiagLoc.isInvalid())
2322 RemovalDiagLoc = Tok.getLocation();
2324 Tok.getLocation(),
2325 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2327 }
2328 }
2329 Diag(RemovalDiagLoc, RemovalDiag);
2330 }
2331
2332 QualType StrTy =
2333 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2334
2335 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2337 Context, Literal.GetString(), Kind, Literal.Pascal, StrTy, StringTokLocs);
2338 if (Literal.getUDSuffix().empty())
2339 return Lit;
2340
2341 // We're building a user-defined literal.
2342 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2343 SourceLocation UDSuffixLoc =
2344 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2345 Literal.getUDSuffixOffset());
2346
2347 // Make sure we're allowed user-defined literals here.
2348 if (!UDLScope)
2349 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2350
2351 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2352 // operator "" X (str, len)
2353 QualType SizeType = Context.getSizeType();
2354
2355 DeclarationName OpName =
2356 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2357 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2358 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2359
2360 QualType ArgTy[] = {
2361 Context.getArrayDecayedType(StrTy), SizeType
2362 };
2363
2364 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2365 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2366 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2367 /*AllowStringTemplatePack*/ true,
2368 /*DiagnoseMissing*/ true, Lit)) {
2369
2370 case LOLR_Cooked: {
2371 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2372 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2373 StringTokLocs[0]);
2374 Expr *Args[] = { Lit, LenArg };
2375
2376 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2377 }
2378
2379 case LOLR_Template: {
2380 TemplateArgumentListInfo ExplicitArgs;
2381 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2382 TemplateArgumentLocInfo ArgInfo(Lit);
2383 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2384 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2385 &ExplicitArgs);
2386 }
2387
2389 TemplateArgumentListInfo ExplicitArgs;
2390
2391 unsigned CharBits = Context.getIntWidth(CharTy);
2392 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2393 llvm::APSInt Value(CharBits, CharIsUnsigned);
2394
2395 TemplateArgument TypeArg(CharTy);
2396 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2397 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2398
2399 SourceLocation Loc = StringTokLocs.back();
2400 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2401 Value = Lit->getCodeUnit(I);
2402 TemplateArgument Arg(Context, Value, CharTy);
2404 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2405 }
2406 return BuildLiteralOperatorCall(R, OpNameInfo, {}, Loc, &ExplicitArgs);
2407 }
2408 case LOLR_Raw:
2410 llvm_unreachable("unexpected literal operator lookup result");
2411 case LOLR_Error:
2412 return ExprError();
2413 }
2414 llvm_unreachable("unexpected literal operator lookup result");
2415}
2416
2419 SourceLocation Loc,
2420 const CXXScopeSpec *SS) {
2421 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2422 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2423}
2424
2427 const DeclarationNameInfo &NameInfo,
2428 const CXXScopeSpec *SS, NamedDecl *FoundD,
2429 SourceLocation TemplateKWLoc,
2430 const TemplateArgumentListInfo *TemplateArgs) {
2433 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2434 TemplateArgs);
2435}
2436
2437// CUDA/HIP: Check whether a captured reference variable is referencing a
2438// host variable in a device or host device lambda.
2440 VarDecl *VD) {
2441 if (!S.getLangOpts().CUDA || !VD->hasInit())
2442 return false;
2443 assert(VD->getType()->isReferenceType());
2444
2445 // Check whether the reference variable is referencing a host variable.
2446 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2447 if (!DRE)
2448 return false;
2449 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2450 if (!Referee || !Referee->hasGlobalStorage() ||
2451 Referee->hasAttr<CUDADeviceAttr>())
2452 return false;
2453
2454 // Check whether the current function is a device or host device lambda.
2455 // Check whether the reference variable is a capture by getDeclContext()
2456 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2457 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2458 if (MD && MD->getParent()->isLambda() &&
2459 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2460 VD->getDeclContext() != MD)
2461 return true;
2462
2463 return false;
2464}
2465
2467 // A declaration named in an unevaluated operand never constitutes an odr-use.
2469 return NOUR_Unevaluated;
2470
2471 // C++2a [basic.def.odr]p4:
2472 // A variable x whose name appears as a potentially-evaluated expression e
2473 // is odr-used by e unless [...] x is a reference that is usable in
2474 // constant expressions.
2475 // CUDA/HIP:
2476 // If a reference variable referencing a host variable is captured in a
2477 // device or host device lambda, the value of the referee must be copied
2478 // to the capture and the reference variable must be treated as odr-use
2479 // since the value of the referee is not known at compile time and must
2480 // be loaded from the captured.
2481 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2482 if (VD->getType()->isReferenceType() &&
2483 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2485 VD->isUsableInConstantExpressions(Context))
2486 return NOUR_Constant;
2487 }
2488
2489 // All remaining non-variable cases constitute an odr-use. For variables, we
2490 // need to wait and see how the expression is used.
2491 return NOUR_None;
2492}
2493
2496 const DeclarationNameInfo &NameInfo,
2497 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2498 SourceLocation TemplateKWLoc,
2499 const TemplateArgumentListInfo *TemplateArgs) {
2500 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2501 NeedToCaptureVariable(D, NameInfo.getLoc());
2502
2504 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2505 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2507
2508 // C++ [except.spec]p17:
2509 // An exception-specification is considered to be needed when:
2510 // - in an expression, the function is the unique lookup result or
2511 // the selected member of a set of overloaded functions.
2512 //
2513 // We delay doing this until after we've built the function reference and
2514 // marked it as used so that:
2515 // a) if the function is defaulted, we get errors from defining it before /
2516 // instead of errors from computing its exception specification, and
2517 // b) if the function is a defaulted comparison, we can use the body we
2518 // build when defining it as input to the exception specification
2519 // computation rather than computing a new body.
2520 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2521 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2522 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2523 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2524 }
2525 }
2526
2527 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2529 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2531
2532 const auto *FD = dyn_cast<FieldDecl>(D);
2533 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2534 FD = IFD->getAnonField();
2535 if (FD) {
2536 UnusedPrivateFields.remove(FD);
2537 // Just in case we're building an illegal pointer-to-member.
2538 if (FD->isBitField())
2540 }
2541
2542 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2543 // designates a bit-field.
2544 if (const auto *BD = dyn_cast<BindingDecl>(D))
2545 if (const auto *BE = BD->getBinding())
2546 E->setObjectKind(BE->getObjectKind());
2547
2548 return E;
2549}
2550
2551void
2554 DeclarationNameInfo &NameInfo,
2555 const TemplateArgumentListInfo *&TemplateArgs) {
2557 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2558 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2559
2560 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2561 Id.TemplateId->NumArgs);
2562 translateTemplateArguments(TemplateArgsPtr, Buffer);
2563
2564 TemplateName TName = Id.TemplateId->Template.get();
2566 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2567 TemplateArgs = &Buffer;
2568 } else {
2569 NameInfo = GetNameFromUnqualifiedId(Id);
2570 TemplateArgs = nullptr;
2571 }
2572}
2573
2575 // During a default argument instantiation the CurContext points
2576 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2577 // function parameter list, hence add an explicit check.
2578 bool isDefaultArgument =
2579 !CodeSynthesisContexts.empty() &&
2580 CodeSynthesisContexts.back().Kind ==
2582 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2583 bool isInstance = CurMethod && CurMethod->isInstance() &&
2584 R.getNamingClass() == CurMethod->getParent() &&
2585 !isDefaultArgument;
2586
2587 // There are two ways we can find a class-scope declaration during template
2588 // instantiation that we did not find in the template definition: if it is a
2589 // member of a dependent base class, or if it is declared after the point of
2590 // use in the same class. Distinguish these by comparing the class in which
2591 // the member was found to the naming class of the lookup.
2592 unsigned DiagID = diag::err_found_in_dependent_base;
2593 unsigned NoteID = diag::note_member_declared_at;
2594 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2595 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2596 : diag::err_found_later_in_class;
2597 } else if (getLangOpts().MSVCCompat) {
2598 DiagID = diag::ext_found_in_dependent_base;
2599 NoteID = diag::note_dependent_member_use;
2600 }
2601
2602 if (isInstance) {
2603 // Give a code modification hint to insert 'this->'.
2604 Diag(R.getNameLoc(), DiagID)
2605 << R.getLookupName()
2606 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2607 CheckCXXThisCapture(R.getNameLoc());
2608 } else {
2609 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2610 // they're not shadowed).
2611 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2612 }
2613
2614 for (const NamedDecl *D : R)
2615 Diag(D->getLocation(), NoteID);
2616
2617 // Return true if we are inside a default argument instantiation
2618 // and the found name refers to an instance member function, otherwise
2619 // the caller will try to create an implicit member call and this is wrong
2620 // for default arguments.
2621 //
2622 // FIXME: Is this special case necessary? We could allow the caller to
2623 // diagnose this.
2624 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2625 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2626 return true;
2627 }
2628
2629 // Tell the callee to try to recover.
2630 return false;
2631}
2632
2635 TemplateArgumentListInfo *ExplicitTemplateArgs,
2636 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2637 DeclarationName Name = R.getLookupName();
2638 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2639
2640 unsigned diagnostic = diag::err_undeclared_var_use;
2641 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2645 diagnostic = diag::err_undeclared_use;
2646 diagnostic_suggest = diag::err_undeclared_use_suggest;
2647 }
2648
2649 // If the original lookup was an unqualified lookup, fake an
2650 // unqualified lookup. This is useful when (for example) the
2651 // original lookup would not have found something because it was a
2652 // dependent name.
2653 DeclContext *DC =
2654 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2655 while (DC) {
2656 if (isa<CXXRecordDecl>(DC)) {
2657 if (ExplicitTemplateArgs) {
2659 R, S, SS, Context.getCanonicalTagType(cast<CXXRecordDecl>(DC)),
2660 /*EnteringContext*/ false, TemplateNameIsRequired,
2661 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2662 return true;
2663 } else {
2664 LookupQualifiedName(R, DC);
2665 }
2666
2667 if (!R.empty()) {
2668 // Don't give errors about ambiguities in this lookup.
2669 R.suppressDiagnostics();
2670
2671 // If there's a best viable function among the results, only mention
2672 // that one in the notes.
2673 OverloadCandidateSet Candidates(R.getNameLoc(),
2675 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2677 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2678 OR_Success) {
2679 R.clear();
2680 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2681 R.resolveKind();
2682 }
2683
2685 }
2686
2687 R.clear();
2688 }
2689
2690 DC = DC->getLookupParent();
2691 }
2692
2693 // We didn't find anything, so try to correct for a typo.
2694 TypoCorrection Corrected;
2695 if (S && (Corrected =
2696 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2697 CCC, CorrectTypoKind::ErrorRecovery, LookupCtx))) {
2698 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2699 bool DroppedSpecifier =
2700 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2701 R.setLookupName(Corrected.getCorrection());
2702
2703 bool AcceptableWithRecovery = false;
2704 bool AcceptableWithoutRecovery = false;
2705 NamedDecl *ND = Corrected.getFoundDecl();
2706 if (ND) {
2707 if (Corrected.isOverloaded()) {
2708 OverloadCandidateSet OCS(R.getNameLoc(),
2711 for (NamedDecl *CD : Corrected) {
2712 if (FunctionTemplateDecl *FTD =
2713 dyn_cast<FunctionTemplateDecl>(CD))
2715 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2716 Args, OCS);
2717 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2718 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2720 Args, OCS);
2721 }
2722 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2723 case OR_Success:
2724 ND = Best->FoundDecl;
2725 Corrected.setCorrectionDecl(ND);
2726 break;
2727 default:
2728 // FIXME: Arbitrarily pick the first declaration for the note.
2729 Corrected.setCorrectionDecl(ND);
2730 break;
2731 }
2732 }
2733 R.addDecl(ND);
2734 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2737 if (!Record)
2740 R.setNamingClass(Record);
2741 }
2742
2743 auto *UnderlyingND = ND->getUnderlyingDecl();
2744 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2745 isa<FunctionTemplateDecl>(UnderlyingND);
2746 // FIXME: If we ended up with a typo for a type name or
2747 // Objective-C class name, we're in trouble because the parser
2748 // is in the wrong place to recover. Suggest the typo
2749 // correction, but don't make it a fix-it since we're not going
2750 // to recover well anyway.
2751 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2752 getAsTypeTemplateDecl(UnderlyingND) ||
2753 isa<ObjCInterfaceDecl>(UnderlyingND);
2754 } else {
2755 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2756 // because we aren't able to recover.
2757 AcceptableWithoutRecovery = true;
2758 }
2759
2760 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2761 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2762 ? diag::note_implicit_param_decl
2763 : diag::note_previous_decl;
2764 if (SS.isEmpty())
2765 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name << NameRange,
2766 PDiag(NoteID), AcceptableWithRecovery);
2767 else
2768 diagnoseTypo(Corrected,
2769 PDiag(diag::err_no_member_suggest)
2770 << Name << computeDeclContext(SS, false)
2771 << DroppedSpecifier << NameRange,
2772 PDiag(NoteID), AcceptableWithRecovery);
2773
2774 if (Corrected.WillReplaceSpecifier()) {
2776 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2777 SS.MakeTrivial(Context, NNS,
2778 NNS ? NameRange.getBegin() : SourceRange());
2779 }
2780
2781 // Tell the callee whether to try to recover.
2782 return !AcceptableWithRecovery;
2783 }
2784 }
2785 R.clear();
2786
2787 // Emit a special diagnostic for failed member lookups.
2788 // FIXME: computing the declaration context might fail here (?)
2789 if (!SS.isEmpty()) {
2790 Diag(R.getNameLoc(), diag::err_no_member)
2791 << Name << computeDeclContext(SS, false) << NameRange;
2792 return true;
2793 }
2794
2795 // Give up, we can't recover.
2796 Diag(R.getNameLoc(), diagnostic) << Name << NameRange;
2797 return true;
2798}
2799
2800/// In Microsoft mode, if we are inside a template class whose parent class has
2801/// dependent base classes, and we can't resolve an unqualified identifier, then
2802/// assume the identifier is a member of a dependent base class. We can only
2803/// recover successfully in static methods, instance methods, and other contexts
2804/// where 'this' is available. This doesn't precisely match MSVC's
2805/// instantiation model, but it's close enough.
2806static Expr *
2808 DeclarationNameInfo &NameInfo,
2809 SourceLocation TemplateKWLoc,
2810 const TemplateArgumentListInfo *TemplateArgs) {
2811 // Only try to recover from lookup into dependent bases in static methods or
2812 // contexts where 'this' is available.
2813 QualType ThisType = S.getCurrentThisType();
2814 const CXXRecordDecl *RD = nullptr;
2815 if (!ThisType.isNull())
2816 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2817 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2818 RD = MD->getParent();
2819 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2820 return nullptr;
2821
2822 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2823 // is available, suggest inserting 'this->' as a fixit.
2824 SourceLocation Loc = NameInfo.getLoc();
2825 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2826 DB << NameInfo.getName() << RD;
2827
2828 if (!ThisType.isNull()) {
2829 DB << FixItHint::CreateInsertion(Loc, "this->");
2831 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2832 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2833 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2834 }
2835
2836 // Synthesize a fake NNS that points to the derived class. This will
2837 // perform name lookup during template instantiation.
2838 CXXScopeSpec SS;
2839 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD)->getTypePtr());
2840 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2842 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2843 TemplateArgs);
2844}
2845
2847 SourceLocation TemplateKWLoc,
2848 UnqualifiedId &Id, bool HasTrailingLParen,
2849 bool IsAddressOfOperand,
2851 bool IsInlineAsmIdentifier) {
2852 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2853 "cannot be direct & operand and have a trailing lparen");
2854 if (SS.isInvalid())
2855 return ExprError();
2856
2857 TemplateArgumentListInfo TemplateArgsBuffer;
2858
2859 // Decompose the UnqualifiedId into the following data.
2860 DeclarationNameInfo NameInfo;
2861 const TemplateArgumentListInfo *TemplateArgs;
2862 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2863
2864 DeclarationName Name = NameInfo.getName();
2866 SourceLocation NameLoc = NameInfo.getLoc();
2867
2868 if (II && II->isEditorPlaceholder()) {
2869 // FIXME: When typed placeholders are supported we can create a typed
2870 // placeholder expression node.
2871 return ExprError();
2872 }
2873
2874 // This specially handles arguments of attributes appertains to a type of C
2875 // struct field such that the name lookup within a struct finds the member
2876 // name, which is not the case for other contexts in C.
2877 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2878 // See if this is reference to a field of struct.
2879 LookupResult R(*this, NameInfo, LookupMemberName);
2880 // LookupName handles a name lookup from within anonymous struct.
2881 if (LookupName(R, S)) {
2882 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2883 QualType type = VD->getType().getNonReferenceType();
2884 // This will eventually be translated into MemberExpr upon
2885 // the use of instantiated struct fields.
2886 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2887 }
2888 }
2889 }
2890
2891 // Perform the required lookup.
2892 LookupResult R(*this, NameInfo,
2896 if (TemplateKWLoc.isValid() || TemplateArgs) {
2897 // Lookup the template name again to correctly establish the context in
2898 // which it was found. This is really unfortunate as we already did the
2899 // lookup to determine that it was a template name in the first place. If
2900 // this becomes a performance hit, we can work harder to preserve those
2901 // results until we get here but it's likely not worth it.
2902 AssumedTemplateKind AssumedTemplate;
2903 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2904 /*EnteringContext=*/false, TemplateKWLoc,
2905 &AssumedTemplate))
2906 return ExprError();
2907
2908 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2909 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2910 IsAddressOfOperand, TemplateArgs);
2911 } else {
2912 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2913 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2914 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2915
2916 // If the result might be in a dependent base class, this is a dependent
2917 // id-expression.
2918 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2919 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2920 IsAddressOfOperand, TemplateArgs);
2921
2922 // If this reference is in an Objective-C method, then we need to do
2923 // some special Objective-C lookup, too.
2924 if (IvarLookupFollowUp) {
2925 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2926 if (E.isInvalid())
2927 return ExprError();
2928
2929 if (Expr *Ex = E.getAs<Expr>())
2930 return Ex;
2931 }
2932 }
2933
2934 if (R.isAmbiguous())
2935 return ExprError();
2936
2937 // This could be an implicitly declared function reference if the language
2938 // mode allows it as a feature.
2939 if (R.empty() && HasTrailingLParen && II &&
2940 getLangOpts().implicitFunctionsAllowed()) {
2941 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2942 if (D) R.addDecl(D);
2943 }
2944
2945 // Determine whether this name might be a candidate for
2946 // argument-dependent lookup.
2947 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2948
2949 if (R.empty() && !ADL) {
2950 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2951 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2952 TemplateKWLoc, TemplateArgs))
2953 return E;
2954 }
2955
2956 // Don't diagnose an empty lookup for inline assembly.
2957 if (IsInlineAsmIdentifier)
2958 return ExprError();
2959
2960 // If this name wasn't predeclared and if this is not a function
2961 // call, diagnose the problem.
2962 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2963 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2964 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2965 "Typo correction callback misconfigured");
2966 if (CCC) {
2967 // Make sure the callback knows what the typo being diagnosed is.
2968 CCC->setTypoName(II);
2969 if (SS.isValid())
2970 CCC->setTypoNNS(SS.getScopeRep());
2971 }
2972 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2973 // a template name, but we happen to have always already looked up the name
2974 // before we get here if it must be a template name.
2975 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2976 {}, nullptr))
2977 return ExprError();
2978
2979 assert(!R.empty() &&
2980 "DiagnoseEmptyLookup returned false but added no results");
2981
2982 // If we found an Objective-C instance variable, let
2983 // LookupInObjCMethod build the appropriate expression to
2984 // reference the ivar.
2985 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2986 R.clear();
2987 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2988 // In a hopelessly buggy code, Objective-C instance variable
2989 // lookup fails and no expression will be built to reference it.
2990 if (!E.isInvalid() && !E.get())
2991 return ExprError();
2992 return E;
2993 }
2994 }
2995
2996 // This is guaranteed from this point on.
2997 assert(!R.empty() || ADL);
2998
2999 // Check whether this might be a C++ implicit instance member access.
3000 // C++ [class.mfct.non-static]p3:
3001 // When an id-expression that is not part of a class member access
3002 // syntax and not used to form a pointer to member is used in the
3003 // body of a non-static member function of class X, if name lookup
3004 // resolves the name in the id-expression to a non-static non-type
3005 // member of some class C, the id-expression is transformed into a
3006 // class member access expression using (*this) as the
3007 // postfix-expression to the left of the . operator.
3008 //
3009 // But we don't actually need to do this for '&' operands if R
3010 // resolved to a function or overloaded function set, because the
3011 // expression is ill-formed if it actually works out to be a
3012 // non-static member function:
3013 //
3014 // C++ [expr.ref]p4:
3015 // Otherwise, if E1.E2 refers to a non-static member function. . .
3016 // [t]he expression can be used only as the left-hand operand of a
3017 // member function call.
3018 //
3019 // There are other safeguards against such uses, but it's important
3020 // to get this right here so that we don't end up making a
3021 // spuriously dependent expression if we're inside a dependent
3022 // instance method.
3023 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3024 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
3025 S);
3026
3027 if (TemplateArgs || TemplateKWLoc.isValid()) {
3028
3029 // In C++1y, if this is a variable template id, then check it
3030 // in BuildTemplateIdExpr().
3031 // The single lookup result must be a variable template declaration.
3035 assert(R.getAsSingle<TemplateDecl>() &&
3036 "There should only be one declaration found.");
3037 }
3038
3039 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
3040 }
3041
3042 return BuildDeclarationNameExpr(SS, R, ADL);
3043}
3044
3046 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3047 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3048 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3049 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
3050
3051 if (R.isAmbiguous())
3052 return ExprError();
3053
3054 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3055 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3056 NameInfo, /*TemplateArgs=*/nullptr);
3057
3058 if (R.empty()) {
3059 // Don't diagnose problems with invalid record decl, the secondary no_member
3060 // diagnostic during template instantiation is likely bogus, e.g. if a class
3061 // is invalid because it's derived from an invalid base class, then missing
3062 // members were likely supposed to be inherited.
3064 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
3065 if (CD->isInvalidDecl() || CD->isBeingDefined())
3066 return ExprError();
3067 Diag(NameInfo.getLoc(), diag::err_no_member)
3068 << NameInfo.getName() << DC << SS.getRange();
3069 return ExprError();
3070 }
3071
3072 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3073 QualType ET;
3074 TypeLocBuilder TLB;
3075 if (auto *TagD = dyn_cast<TagDecl>(TD)) {
3076 ET = SemaRef.Context.getTagType(ElaboratedTypeKeyword::None,
3077 SS.getScopeRep(), TagD,
3078 /*OwnsTag=*/false);
3079 auto TL = TLB.push<TagTypeLoc>(ET);
3081 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3082 TL.setNameLoc(NameInfo.getLoc());
3083 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(TD)) {
3084 ET = SemaRef.Context.getTypedefType(ElaboratedTypeKeyword::None,
3085 SS.getScopeRep(), TypedefD);
3086 TLB.push<TypedefTypeLoc>(ET).set(
3087 /*ElaboratedKeywordLoc=*/SourceLocation(),
3088 SS.getWithLocInContext(Context), NameInfo.getLoc());
3089 } else {
3090 // FIXME: What else can appear here?
3091 ET = SemaRef.Context.getTypeDeclType(TD);
3092 TLB.pushTypeSpec(ET).setNameLoc(NameInfo.getLoc());
3093 assert(SS.isEmpty());
3094 }
3095
3096 // Diagnose a missing typename if this resolved unambiguously to a type in
3097 // a dependent context. If we can recover with a type, downgrade this to
3098 // a warning in Microsoft compatibility mode.
3099 unsigned DiagID = diag::err_typename_missing;
3100 if (RecoveryTSI && getLangOpts().MSVCCompat)
3101 DiagID = diag::ext_typename_missing;
3102 SourceLocation Loc = SS.getBeginLoc();
3103 auto D = Diag(Loc, DiagID);
3104 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3105
3106 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3107 // context.
3108 if (!RecoveryTSI)
3109 return ExprError();
3110
3111 // Only issue the fixit if we're prepared to recover.
3112 D << FixItHint::CreateInsertion(Loc, "typename ");
3113
3114 // Recover by pretending this was an elaborated type.
3115 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3116
3117 return ExprEmpty();
3118 }
3119
3120 // If necessary, build an implicit class member access.
3121 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3123 /*TemplateKWLoc=*/SourceLocation(),
3124 R, /*TemplateArgs=*/nullptr,
3125 /*S=*/nullptr);
3126
3127 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
3128}
3129
3131 NestedNameSpecifier Qualifier,
3132 NamedDecl *FoundDecl,
3133 NamedDecl *Member) {
3134 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3135 if (!RD)
3136 return From;
3137
3138 QualType DestRecordType;
3139 QualType DestType;
3140 QualType FromRecordType;
3141 QualType FromType = From->getType();
3142 bool PointerConversions = false;
3143 if (isa<FieldDecl>(Member)) {
3144 DestRecordType = Context.getCanonicalTagType(RD);
3145 auto FromPtrType = FromType->getAs<PointerType>();
3146 DestRecordType = Context.getAddrSpaceQualType(
3147 DestRecordType, FromPtrType
3148 ? FromType->getPointeeType().getAddressSpace()
3149 : FromType.getAddressSpace());
3150
3151 if (FromPtrType) {
3152 DestType = Context.getPointerType(DestRecordType);
3153 FromRecordType = FromPtrType->getPointeeType();
3154 PointerConversions = true;
3155 } else {
3156 DestType = DestRecordType;
3157 FromRecordType = FromType;
3158 }
3159 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3160 if (!Method->isImplicitObjectMemberFunction())
3161 return From;
3162
3163 DestType = Method->getThisType().getNonReferenceType();
3164 DestRecordType = Method->getFunctionObjectParameterType();
3165
3166 if (FromType->getAs<PointerType>()) {
3167 FromRecordType = FromType->getPointeeType();
3168 PointerConversions = true;
3169 } else {
3170 FromRecordType = FromType;
3171 DestType = DestRecordType;
3172 }
3173
3174 LangAS FromAS = FromRecordType.getAddressSpace();
3175 LangAS DestAS = DestRecordType.getAddressSpace();
3176 if (FromAS != DestAS) {
3177 QualType FromRecordTypeWithoutAS =
3178 Context.removeAddrSpaceQualType(FromRecordType);
3179 QualType FromTypeWithDestAS =
3180 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3181 if (PointerConversions)
3182 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3183 From = ImpCastExprToType(From, FromTypeWithDestAS,
3184 CK_AddressSpaceConversion, From->getValueKind())
3185 .get();
3186 }
3187 } else {
3188 // No conversion necessary.
3189 return From;
3190 }
3191
3192 if (DestType->isDependentType() || FromType->isDependentType())
3193 return From;
3194
3195 // If the unqualified types are the same, no conversion is necessary.
3196 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3197 return From;
3198
3199 SourceRange FromRange = From->getSourceRange();
3200 SourceLocation FromLoc = FromRange.getBegin();
3201
3202 ExprValueKind VK = From->getValueKind();
3203
3204 // C++ [class.member.lookup]p8:
3205 // [...] Ambiguities can often be resolved by qualifying a name with its
3206 // class name.
3207 //
3208 // If the member was a qualified name and the qualified referred to a
3209 // specific base subobject type, we'll cast to that intermediate type
3210 // first and then to the object in which the member is declared. That allows
3211 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3212 //
3213 // class Base { public: int x; };
3214 // class Derived1 : public Base { };
3215 // class Derived2 : public Base { };
3216 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3217 //
3218 // void VeryDerived::f() {
3219 // x = 17; // error: ambiguous base subobjects
3220 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3221 // }
3222 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3223 QualType QType = QualType(Qualifier.getAsType(), 0);
3224 assert(QType->isRecordType() && "lookup done with non-record type");
3225
3226 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3227
3228 // In C++98, the qualifier type doesn't actually have to be a base
3229 // type of the object type, in which case we just ignore it.
3230 // Otherwise build the appropriate casts.
3231 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3232 CXXCastPath BasePath;
3233 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3234 FromLoc, FromRange, &BasePath))
3235 return ExprError();
3236
3237 if (PointerConversions)
3238 QType = Context.getPointerType(QType);
3239 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3240 VK, &BasePath).get();
3241
3242 FromType = QType;
3243 FromRecordType = QRecordType;
3244
3245 // If the qualifier type was the same as the destination type,
3246 // we're done.
3247 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3248 return From;
3249 }
3250 }
3251
3252 CXXCastPath BasePath;
3253 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3254 FromLoc, FromRange, &BasePath,
3255 /*IgnoreAccess=*/true))
3256 return ExprError();
3257
3258 // Propagate qualifiers to base subobjects as per:
3259 // C++ [basic.type.qualifier]p1.2:
3260 // A volatile object is [...] a subobject of a volatile object.
3261 Qualifiers FromTypeQuals = FromType.getQualifiers();
3262 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3263 DestType = Context.getQualifiedType(DestType, FromTypeQuals);
3264
3265 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, VK,
3266 &BasePath);
3267}
3268
3270 const LookupResult &R,
3271 bool HasTrailingLParen) {
3272 // Only when used directly as the postfix-expression of a call.
3273 if (!HasTrailingLParen)
3274 return false;
3275
3276 // Never if a scope specifier was provided.
3277 if (SS.isNotEmpty())
3278 return false;
3279
3280 // Only in C++ or ObjC++.
3281 if (!getLangOpts().CPlusPlus)
3282 return false;
3283
3284 // Turn off ADL when we find certain kinds of declarations during
3285 // normal lookup:
3286 for (const NamedDecl *D : R) {
3287 // C++0x [basic.lookup.argdep]p3:
3288 // -- a declaration of a class member
3289 // Since using decls preserve this property, we check this on the
3290 // original decl.
3291 if (D->isCXXClassMember())
3292 return false;
3293
3294 // C++0x [basic.lookup.argdep]p3:
3295 // -- a block-scope function declaration that is not a
3296 // using-declaration
3297 // NOTE: we also trigger this for function templates (in fact, we
3298 // don't check the decl type at all, since all other decl types
3299 // turn off ADL anyway).
3300 if (isa<UsingShadowDecl>(D))
3301 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3302 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3303 return false;
3304
3305 // C++0x [basic.lookup.argdep]p3:
3306 // -- a declaration that is neither a function or a function
3307 // template
3308 // And also for builtin functions.
3309 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3310 // But also builtin functions.
3311 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3312 return false;
3313 } else if (!isa<FunctionTemplateDecl>(D))
3314 return false;
3315 }
3316
3317 return true;
3318}
3319
3320
3321/// Diagnoses obvious problems with the use of the given declaration
3322/// as an expression. This is only actually called for lookups that
3323/// were not overloaded, and it doesn't promise that the declaration
3324/// will in fact be used.
3326 bool AcceptInvalid) {
3327 if (D->isInvalidDecl() && !AcceptInvalid)
3328 return true;
3329
3330 if (isa<TypedefNameDecl>(D)) {
3331 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3332 return true;
3333 }
3334
3335 if (isa<ObjCInterfaceDecl>(D)) {
3336 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3337 return true;
3338 }
3339
3340 if (isa<NamespaceDecl>(D)) {
3341 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3342 return true;
3343 }
3344
3345 return false;
3346}
3347
3348// Certain multiversion types should be treated as overloaded even when there is
3349// only one result.
3351 assert(R.isSingleResult() && "Expected only a single result");
3352 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3353 return FD &&
3354 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3355}
3356
3358 LookupResult &R, bool NeedsADL,
3359 bool AcceptInvalidDecl) {
3360 // If this is a single, fully-resolved result and we don't need ADL,
3361 // just build an ordinary singleton decl ref.
3362 if (!NeedsADL && R.isSingleResult() &&
3363 !R.getAsSingle<FunctionTemplateDecl>() &&
3365 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3366 R.getRepresentativeDecl(), nullptr,
3367 AcceptInvalidDecl);
3368
3369 // We only need to check the declaration if there's exactly one
3370 // result, because in the overloaded case the results can only be
3371 // functions and function templates.
3372 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3373 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3374 AcceptInvalidDecl))
3375 return ExprError();
3376
3377 // Otherwise, just build an unresolved lookup expression. Suppress
3378 // any lookup-related diagnostics; we'll hash these out later, when
3379 // we've picked a target.
3380 R.suppressDiagnostics();
3381
3383 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
3384 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3385 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3386
3387 return ULE;
3388}
3389
3391 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3392 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3393 bool AcceptInvalidDecl) {
3394 assert(D && "Cannot refer to a NULL declaration");
3395 assert(!isa<FunctionTemplateDecl>(D) &&
3396 "Cannot refer unambiguously to a function template");
3397
3398 SourceLocation Loc = NameInfo.getLoc();
3399 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3400 // Recovery from invalid cases (e.g. D is an invalid Decl).
3401 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3402 // diagnostics, as invalid decls use int as a fallback type.
3403 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3404 }
3405
3406 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3407 // Specifically diagnose references to class templates that are missing
3408 // a template argument list.
3409 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3410 return ExprError();
3411 }
3412
3413 // Make sure that we're referring to a value.
3415 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3416 Diag(D->getLocation(), diag::note_declared_at);
3417 return ExprError();
3418 }
3419
3420 // Check whether this declaration can be used. Note that we suppress
3421 // this check when we're going to perform argument-dependent lookup
3422 // on this function name, because this might not be the function
3423 // that overload resolution actually selects.
3424 if (DiagnoseUseOfDecl(D, Loc))
3425 return ExprError();
3426
3427 auto *VD = cast<ValueDecl>(D);
3428
3429 // Only create DeclRefExpr's for valid Decl's.
3430 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3431 return ExprError();
3432
3433 // Handle members of anonymous structs and unions. If we got here,
3434 // and the reference is to a class member indirect field, then this
3435 // must be the subject of a pointer-to-member expression.
3436 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3437 IndirectField && !IndirectField->isCXXClassMember())
3439 IndirectField);
3440
3441 QualType type = VD->getType();
3442 if (type.isNull())
3443 return ExprError();
3444 ExprValueKind valueKind = VK_PRValue;
3445
3446 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3447 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3448 // is expanded by some outer '...' in the context of the use.
3449 type = type.getNonPackExpansionType();
3450
3451 switch (D->getKind()) {
3452 // Ignore all the non-ValueDecl kinds.
3453#define ABSTRACT_DECL(kind)
3454#define VALUE(type, base)
3455#define DECL(type, base) case Decl::type:
3456#include "clang/AST/DeclNodes.inc"
3457 llvm_unreachable("invalid value decl kind");
3458
3459 // These shouldn't make it here.
3460 case Decl::ObjCAtDefsField:
3461 llvm_unreachable("forming non-member reference to ivar?");
3462
3463 // Enum constants are always r-values and never references.
3464 // Unresolved using declarations are dependent.
3465 case Decl::EnumConstant:
3466 case Decl::UnresolvedUsingValue:
3467 case Decl::OMPDeclareReduction:
3468 case Decl::OMPDeclareMapper:
3469 valueKind = VK_PRValue;
3470 break;
3471
3472 // Fields and indirect fields that got here must be for
3473 // pointer-to-member expressions; we just call them l-values for
3474 // internal consistency, because this subexpression doesn't really
3475 // exist in the high-level semantics.
3476 case Decl::Field:
3477 case Decl::IndirectField:
3478 case Decl::ObjCIvar:
3479 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3480 "building reference to field in C?");
3481
3482 // These can't have reference type in well-formed programs, but
3483 // for internal consistency we do this anyway.
3484 type = type.getNonReferenceType();
3485 valueKind = VK_LValue;
3486 break;
3487
3488 // Non-type template parameters are either l-values or r-values
3489 // depending on the type.
3490 case Decl::NonTypeTemplateParm: {
3491 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3492 type = reftype->getPointeeType();
3493 valueKind = VK_LValue; // even if the parameter is an r-value reference
3494 break;
3495 }
3496
3497 // [expr.prim.id.unqual]p2:
3498 // If the entity is a template parameter object for a template
3499 // parameter of type T, the type of the expression is const T.
3500 // [...] The expression is an lvalue if the entity is a [...] template
3501 // parameter object.
3502 if (type->isRecordType()) {
3503 type = type.getUnqualifiedType().withConst();
3504 valueKind = VK_LValue;
3505 break;
3506 }
3507
3508 // For non-references, we need to strip qualifiers just in case
3509 // the template parameter was declared as 'const int' or whatever.
3510 valueKind = VK_PRValue;
3511 type = type.getUnqualifiedType();
3512 break;
3513 }
3514
3515 case Decl::Var:
3516 case Decl::VarTemplateSpecialization:
3517 case Decl::VarTemplatePartialSpecialization:
3518 case Decl::Decomposition:
3519 case Decl::Binding:
3520 case Decl::OMPCapturedExpr:
3521 // In C, "extern void blah;" is valid and is an r-value.
3522 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3523 type->isVoidType()) {
3524 valueKind = VK_PRValue;
3525 break;
3526 }
3527 [[fallthrough]];
3528
3529 case Decl::ImplicitParam:
3530 case Decl::ParmVar: {
3531 // These are always l-values.
3532 valueKind = VK_LValue;
3533 type = type.getNonReferenceType();
3534
3535 // FIXME: Does the addition of const really only apply in
3536 // potentially-evaluated contexts? Since the variable isn't actually
3537 // captured in an unevaluated context, it seems that the answer is no.
3538 if (!isUnevaluatedContext()) {
3539 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3540 if (!CapturedType.isNull())
3541 type = CapturedType;
3542 }
3543 break;
3544 }
3545
3546 case Decl::Function: {
3547 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3548 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3549 type = Context.BuiltinFnTy;
3550 valueKind = VK_PRValue;
3551 break;
3552 }
3553 }
3554
3555 const FunctionType *fty = type->castAs<FunctionType>();
3556
3557 // If we're referring to a function with an __unknown_anytype
3558 // result type, make the entire expression __unknown_anytype.
3559 if (fty->getReturnType() == Context.UnknownAnyTy) {
3560 type = Context.UnknownAnyTy;
3561 valueKind = VK_PRValue;
3562 break;
3563 }
3564
3565 // Functions are l-values in C++.
3566 if (getLangOpts().CPlusPlus) {
3567 valueKind = VK_LValue;
3568 break;
3569 }
3570
3571 // C99 DR 316 says that, if a function type comes from a
3572 // function definition (without a prototype), that type is only
3573 // used for checking compatibility. Therefore, when referencing
3574 // the function, we pretend that we don't have the full function
3575 // type.
3576 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3577 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3578 fty->getExtInfo());
3579
3580 // Functions are r-values in C.
3581 valueKind = VK_PRValue;
3582 break;
3583 }
3584
3585 case Decl::CXXDeductionGuide:
3586 llvm_unreachable("building reference to deduction guide");
3587
3588 case Decl::MSProperty:
3589 case Decl::MSGuid:
3590 case Decl::TemplateParamObject:
3591 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3592 // capture in OpenMP, or duplicated between host and device?
3593 valueKind = VK_LValue;
3594 break;
3595
3596 case Decl::UnnamedGlobalConstant:
3597 valueKind = VK_LValue;
3598 break;
3599
3600 case Decl::CXXMethod:
3601 // If we're referring to a method with an __unknown_anytype
3602 // result type, make the entire expression __unknown_anytype.
3603 // This should only be possible with a type written directly.
3604 if (const FunctionProtoType *proto =
3605 dyn_cast<FunctionProtoType>(VD->getType()))
3606 if (proto->getReturnType() == Context.UnknownAnyTy) {
3607 type = Context.UnknownAnyTy;
3608 valueKind = VK_PRValue;
3609 break;
3610 }
3611
3612 // C++ methods are l-values if static, r-values if non-static.
3613 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3614 valueKind = VK_LValue;
3615 break;
3616 }
3617 [[fallthrough]];
3618
3619 case Decl::CXXConversion:
3620 case Decl::CXXDestructor:
3621 case Decl::CXXConstructor:
3622 valueKind = VK_PRValue;
3623 break;
3624 }
3625
3626 auto *E =
3627 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3628 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3629 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3630 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3631 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3632 // diagnostics).
3633 if (VD->isInvalidDecl() && E)
3634 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3635 return E;
3636}
3637
3638static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3640 Target.resize(CharByteWidth * (Source.size() + 1));
3641 char *ResultPtr = &Target[0];
3642 const llvm::UTF8 *ErrorPtr;
3643 bool success =
3644 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3645 (void)success;
3646 assert(success);
3647 Target.resize(ResultPtr - &Target[0]);
3648}
3649
3652 Decl *currentDecl = getPredefinedExprDecl(*this, CurContext);
3653 if (!currentDecl) {
3654 Diag(Loc, diag::ext_predef_outside_function);
3655 currentDecl = Context.getTranslationUnitDecl();
3656 }
3657
3658 QualType ResTy;
3659 StringLiteral *SL = nullptr;
3660 if (cast<DeclContext>(currentDecl)->isDependentContext())
3661 ResTy = Context.DependentTy;
3662 else {
3663 // Pre-defined identifiers are of type char[x], where x is the length of
3664 // the string.
3665 bool ForceElaboratedPrinting =
3666 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3667 auto Str =
3668 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3669 unsigned Length = Str.length();
3670
3671 llvm::APInt LengthI(32, Length + 1);
3674 ResTy =
3675 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3676 SmallString<32> RawChars;
3677 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3678 Str, RawChars);
3679 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3681 /*IndexTypeQuals*/ 0);
3683 /*Pascal*/ false, ResTy, Loc);
3684 } else {
3685 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3686 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3688 /*IndexTypeQuals*/ 0);
3690 /*Pascal*/ false, ResTy, Loc);
3691 }
3692 }
3693
3694 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3695 SL);
3696}
3697
3701
3703 SmallString<16> CharBuffer;
3704 bool Invalid = false;
3705 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3706 if (Invalid)
3707 return ExprError();
3708
3709 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3710 PP, Tok.getKind());
3711 if (Literal.hadError())
3712 return ExprError();
3713
3714 QualType Ty;
3715 if (Literal.isWide())
3716 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3717 else if (Literal.isUTF8() && getLangOpts().C23)
3718 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3719 else if (Literal.isUTF8() && getLangOpts().Char8)
3720 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3721 else if (Literal.isUTF16())
3722 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3723 else if (Literal.isUTF32())
3724 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3725 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3726 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3727 else
3728 Ty = Context.CharTy; // 'x' -> char in C++;
3729 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3730
3732 if (Literal.isWide())
3734 else if (Literal.isUTF16())
3736 else if (Literal.isUTF32())
3738 else if (Literal.isUTF8())
3740
3741 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3742 Tok.getLocation());
3743
3744 if (Literal.getUDSuffix().empty())
3745 return Lit;
3746
3747 // We're building a user-defined literal.
3748 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3749 SourceLocation UDSuffixLoc =
3750 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3751
3752 // Make sure we're allowed user-defined literals here.
3753 if (!UDLScope)
3754 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3755
3756 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3757 // operator "" X (ch)
3758 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3759 Lit, Tok.getLocation());
3760}
3761
3763 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3765 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3766 Context.IntTy, Loc);
3767}
3768
3770 ExprResult Inner;
3771 if (getLangOpts().CPlusPlus) {
3772 Inner = ActOnCXXBoolLiteral(Loc, Value ? tok::kw_true : tok::kw_false);
3773 } else {
3774 // C doesn't actually have a way to represent literal values of type
3775 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
3776 Inner = ActOnIntegerConstant(Loc, Value ? 1 : 0);
3777 Inner =
3778 ImpCastExprToType(Inner.get(), Context.BoolTy, CK_IntegralToBoolean);
3779 }
3780 return Inner;
3781}
3782
3784 QualType Ty, SourceLocation Loc) {
3785 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3786
3787 using llvm::APFloat;
3788 APFloat Val(Format);
3789
3790 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3791 if (RM == llvm::RoundingMode::Dynamic)
3792 RM = llvm::RoundingMode::NearestTiesToEven;
3793 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3794
3795 // Overflow is always an error, but underflow is only an error if
3796 // we underflowed to zero (APFloat reports denormals as underflow).
3797 if ((result & APFloat::opOverflow) ||
3798 ((result & APFloat::opUnderflow) && Val.isZero())) {
3799 unsigned diagnostic;
3800 SmallString<20> buffer;
3801 if (result & APFloat::opOverflow) {
3802 diagnostic = diag::warn_float_overflow;
3803 APFloat::getLargest(Format).toString(buffer);
3804 } else {
3805 diagnostic = diag::warn_float_underflow;
3806 APFloat::getSmallest(Format).toString(buffer);
3807 }
3808
3809 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3810 }
3811
3812 bool isExact = (result == APFloat::opOK);
3813 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3814}
3815
3816bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3817 assert(E && "Invalid expression");
3818
3819 if (E->isValueDependent())
3820 return false;
3821
3822 QualType QT = E->getType();
3823 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3824 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3825 return true;
3826 }
3827
3828 llvm::APSInt ValueAPS;
3830
3831 if (R.isInvalid())
3832 return true;
3833
3834 // GCC allows the value of unroll count to be 0.
3835 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3836 // "The values of 0 and 1 block any unrolling of the loop."
3837 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3838 // '#pragma unroll' cases.
3839 bool ValueIsPositive =
3840 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3841 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3842 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3843 << toString(ValueAPS, 10) << ValueIsPositive;
3844 return true;
3845 }
3846
3847 return false;
3848}
3849
3851 // Fast path for a single digit (which is quite common). A single digit
3852 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3853 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3854 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3855 return ActOnIntegerConstant(Tok.getLocation(), Val);
3856 }
3857
3858 SmallString<128> SpellingBuffer;
3859 // NumericLiteralParser wants to overread by one character. Add padding to
3860 // the buffer in case the token is copied to the buffer. If getSpelling()
3861 // returns a StringRef to the memory buffer, it should have a null char at
3862 // the EOF, so it is also safe.
3863 SpellingBuffer.resize(Tok.getLength() + 1);
3864
3865 // Get the spelling of the token, which eliminates trigraphs, etc.
3866 bool Invalid = false;
3867 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3868 if (Invalid)
3869 return ExprError();
3870
3871 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3872 PP.getSourceManager(), PP.getLangOpts(),
3873 PP.getTargetInfo(), PP.getDiagnostics());
3874 if (Literal.hadError)
3875 return ExprError();
3876
3877 if (Literal.hasUDSuffix()) {
3878 // We're building a user-defined literal.
3879 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3880 SourceLocation UDSuffixLoc =
3881 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3882
3883 // Make sure we're allowed user-defined literals here.
3884 if (!UDLScope)
3885 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3886
3887 QualType CookedTy;
3888 if (Literal.isFloatingLiteral()) {
3889 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3890 // long double, the literal is treated as a call of the form
3891 // operator "" X (f L)
3892 CookedTy = Context.LongDoubleTy;
3893 } else {
3894 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3895 // unsigned long long, the literal is treated as a call of the form
3896 // operator "" X (n ULL)
3897 CookedTy = Context.UnsignedLongLongTy;
3898 }
3899
3900 DeclarationName OpName =
3901 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3902 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3903 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3904
3905 SourceLocation TokLoc = Tok.getLocation();
3906
3907 // Perform literal operator lookup to determine if we're building a raw
3908 // literal or a cooked one.
3909 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3910 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3911 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3912 /*AllowStringTemplatePack*/ false,
3913 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3915 // Lookup failure for imaginary constants isn't fatal, there's still the
3916 // GNU extension producing _Complex types.
3917 break;
3918 case LOLR_Error:
3919 return ExprError();
3920 case LOLR_Cooked: {
3921 Expr *Lit;
3922 if (Literal.isFloatingLiteral()) {
3923 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3924 } else {
3925 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3926 if (Literal.GetIntegerValue(ResultVal))
3927 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3928 << /* Unsigned */ 1;
3929 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3930 Tok.getLocation());
3931 }
3932 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3933 }
3934
3935 case LOLR_Raw: {
3936 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3937 // literal is treated as a call of the form
3938 // operator "" X ("n")
3939 unsigned Length = Literal.getUDSuffixOffset();
3940 QualType StrTy = Context.getConstantArrayType(
3941 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3942 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3943 Expr *Lit =
3944 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3946 /*Pascal*/ false, StrTy, TokLoc);
3947 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3948 }
3949
3950 case LOLR_Template: {
3951 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3952 // template), L is treated as a call fo the form
3953 // operator "" X <'c1', 'c2', ... 'ck'>()
3954 // where n is the source character sequence c1 c2 ... ck.
3955 TemplateArgumentListInfo ExplicitArgs;
3956 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3957 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3958 llvm::APSInt Value(CharBits, CharIsUnsigned);
3959 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3960 Value = TokSpelling[I];
3961 TemplateArgument Arg(Context, Value, Context.CharTy);
3963 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3964 }
3965 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
3966 }
3968 llvm_unreachable("unexpected literal operator lookup result");
3969 }
3970 }
3971
3972 Expr *Res;
3973
3974 if (Literal.isFixedPointLiteral()) {
3975 QualType Ty;
3976
3977 if (Literal.isAccum) {
3978 if (Literal.isHalf) {
3979 Ty = Context.ShortAccumTy;
3980 } else if (Literal.isLong) {
3981 Ty = Context.LongAccumTy;
3982 } else {
3983 Ty = Context.AccumTy;
3984 }
3985 } else if (Literal.isFract) {
3986 if (Literal.isHalf) {
3987 Ty = Context.ShortFractTy;
3988 } else if (Literal.isLong) {
3989 Ty = Context.LongFractTy;
3990 } else {
3991 Ty = Context.FractTy;
3992 }
3993 }
3994
3995 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3996
3997 bool isSigned = !Literal.isUnsigned;
3998 unsigned scale = Context.getFixedPointScale(Ty);
3999 unsigned bit_width = Context.getTypeInfo(Ty).Width;
4000
4001 llvm::APInt Val(bit_width, 0, isSigned);
4002 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
4003 bool ValIsZero = Val.isZero() && !Overflowed;
4004
4005 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4006 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4007 // Clause 6.4.4 - The value of a constant shall be in the range of
4008 // representable values for its type, with exception for constants of a
4009 // fract type with a value of exactly 1; such a constant shall denote
4010 // the maximal value for the type.
4011 --Val;
4012 else if (Val.ugt(MaxVal) || Overflowed)
4013 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
4014
4016 Tok.getLocation(), scale);
4017 } else if (Literal.isFloatingLiteral()) {
4018 QualType Ty;
4019 if (Literal.isHalf){
4020 if (getLangOpts().HLSL ||
4021 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
4022 Ty = Context.HalfTy;
4023 else {
4024 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
4025 return ExprError();
4026 }
4027 } else if (Literal.isFloat)
4028 Ty = Context.FloatTy;
4029 else if (Literal.isLong)
4030 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
4031 else if (Literal.isFloat16)
4032 Ty = Context.Float16Ty;
4033 else if (Literal.isFloat128)
4034 Ty = Context.Float128Ty;
4035 else if (getLangOpts().HLSL)
4036 Ty = Context.FloatTy;
4037 else
4038 Ty = Context.DoubleTy;
4039
4040 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
4041
4042 if (Ty == Context.DoubleTy) {
4043 if (getLangOpts().SinglePrecisionConstants) {
4044 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4045 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4046 }
4047 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4048 "cl_khr_fp64", getLangOpts())) {
4049 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4050 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4052 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4053 }
4054 }
4055 } else if (!Literal.isIntegerLiteral()) {
4056 return ExprError();
4057 } else {
4058 QualType Ty;
4059
4060 // 'z/uz' literals are a C++23 feature.
4061 if (Literal.isSizeT)
4062 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
4064 ? diag::warn_cxx20_compat_size_t_suffix
4065 : diag::ext_cxx23_size_t_suffix
4066 : diag::err_cxx23_size_t_suffix);
4067
4068 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4069 // but we do not currently support the suffix in C++ mode because it's not
4070 // entirely clear whether WG21 will prefer this suffix to return a library
4071 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4072 // literals are a C++ extension.
4073 if (Literal.isBitInt)
4074 PP.Diag(Tok.getLocation(),
4075 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4076 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4077 : diag::ext_c23_bitint_suffix);
4078
4079 // Get the value in the widest-possible width. What is "widest" depends on
4080 // whether the literal is a bit-precise integer or not. For a bit-precise
4081 // integer type, try to scan the source to determine how many bits are
4082 // needed to represent the value. This may seem a bit expensive, but trying
4083 // to get the integer value from an overly-wide APInt is *extremely*
4084 // expensive, so the naive approach of assuming
4085 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4086 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4087 if (Literal.isBitInt)
4088 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4089 Literal.getLiteralDigits(), Literal.getRadix());
4090 if (Literal.MicrosoftInteger) {
4091 if (Literal.MicrosoftInteger == 128 &&
4092 !Context.getTargetInfo().hasInt128Type())
4093 PP.Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4094 << Literal.isUnsigned;
4095 BitsNeeded = Literal.MicrosoftInteger;
4096 }
4097
4098 llvm::APInt ResultVal(BitsNeeded, 0);
4099
4100 if (Literal.GetIntegerValue(ResultVal)) {
4101 // If this value didn't fit into uintmax_t, error and force to ull.
4102 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4103 << /* Unsigned */ 1;
4104 Ty = Context.UnsignedLongLongTy;
4105 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4106 "long long is not intmax_t?");
4107 } else {
4108 // If this value fits into a ULL, try to figure out what else it fits into
4109 // according to the rules of C99 6.4.4.1p5.
4110
4111 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4112 // be an unsigned int.
4113 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4114
4115 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4116 // suffix for portability of code with C++, but both `l` and `ll` are
4117 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4118 // same.
4119 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4120 Literal.isLong = true;
4121 Literal.isLongLong = false;
4122 }
4123
4124 // Check from smallest to largest, picking the smallest type we can.
4125 unsigned Width = 0;
4126
4127 // Microsoft specific integer suffixes are explicitly sized.
4128 if (Literal.MicrosoftInteger) {
4129 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4130 Width = 8;
4131 Ty = Context.CharTy;
4132 } else {
4133 Width = Literal.MicrosoftInteger;
4134 Ty = Context.getIntTypeForBitwidth(Width,
4135 /*Signed=*/!Literal.isUnsigned);
4136 }
4137 }
4138
4139 // Bit-precise integer literals are automagically-sized based on the
4140 // width required by the literal.
4141 if (Literal.isBitInt) {
4142 // The signed version has one more bit for the sign value. There are no
4143 // zero-width bit-precise integers, even if the literal value is 0.
4144 Width = std::max(ResultVal.getActiveBits(), 1u) +
4145 (Literal.isUnsigned ? 0u : 1u);
4146
4147 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4148 // and reset the type to the largest supported width.
4149 unsigned int MaxBitIntWidth =
4150 Context.getTargetInfo().getMaxBitIntWidth();
4151 if (Width > MaxBitIntWidth) {
4152 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4153 << Literal.isUnsigned;
4154 Width = MaxBitIntWidth;
4155 }
4156
4157 // Reset the result value to the smaller APInt and select the correct
4158 // type to be used. Note, we zext even for signed values because the
4159 // literal itself is always an unsigned value (a preceeding - is a
4160 // unary operator, not part of the literal).
4161 ResultVal = ResultVal.zextOrTrunc(Width);
4162 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4163 }
4164
4165 // Check C++23 size_t literals.
4166 if (Literal.isSizeT) {
4167 assert(!Literal.MicrosoftInteger &&
4168 "size_t literals can't be Microsoft literals");
4169 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4170 Context.getTargetInfo().getSizeType());
4171
4172 // Does it fit in size_t?
4173 if (ResultVal.isIntN(SizeTSize)) {
4174 // Does it fit in ssize_t?
4175 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4176 Ty = Context.getSignedSizeType();
4177 else if (AllowUnsigned)
4178 Ty = Context.getSizeType();
4179 Width = SizeTSize;
4180 }
4181 }
4182
4183 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4184 !Literal.isSizeT) {
4185 // Are int/unsigned possibilities?
4186 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4187
4188 // Does it fit in a unsigned int?
4189 if (ResultVal.isIntN(IntSize)) {
4190 // Does it fit in a signed int?
4191 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4192 Ty = Context.IntTy;
4193 else if (AllowUnsigned)
4194 Ty = Context.UnsignedIntTy;
4195 Width = IntSize;
4196 }
4197 }
4198
4199 // Are long/unsigned long possibilities?
4200 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4201 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4202
4203 // Does it fit in a unsigned long?
4204 if (ResultVal.isIntN(LongSize)) {
4205 // Does it fit in a signed long?
4206 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4207 Ty = Context.LongTy;
4208 else if (AllowUnsigned)
4209 Ty = Context.UnsignedLongTy;
4210 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4211 // is compatible.
4212 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4213 const unsigned LongLongSize =
4214 Context.getTargetInfo().getLongLongWidth();
4215 Diag(Tok.getLocation(),
4217 ? Literal.isLong
4218 ? diag::warn_old_implicitly_unsigned_long_cxx
4219 : /*C++98 UB*/ diag::
4220 ext_old_implicitly_unsigned_long_cxx
4221 : diag::warn_old_implicitly_unsigned_long)
4222 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4223 : /*will be ill-formed*/ 1);
4224 Ty = Context.UnsignedLongTy;
4225 }
4226 Width = LongSize;
4227 }
4228 }
4229
4230 // Check long long if needed.
4231 if (Ty.isNull() && !Literal.isSizeT) {
4232 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4233
4234 // Does it fit in a unsigned long long?
4235 if (ResultVal.isIntN(LongLongSize)) {
4236 // Does it fit in a signed long long?
4237 // To be compatible with MSVC, hex integer literals ending with the
4238 // LL or i64 suffix are always signed in Microsoft mode.
4239 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4240 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4241 Ty = Context.LongLongTy;
4242 else if (AllowUnsigned)
4243 Ty = Context.UnsignedLongLongTy;
4244 Width = LongLongSize;
4245
4246 // 'long long' is a C99 or C++11 feature, whether the literal
4247 // explicitly specified 'long long' or we needed the extra width.
4248 if (getLangOpts().CPlusPlus)
4249 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4250 ? diag::warn_cxx98_compat_longlong
4251 : diag::ext_cxx11_longlong);
4252 else if (!getLangOpts().C99)
4253 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4254 }
4255 }
4256
4257 // If we still couldn't decide a type, we either have 'size_t' literal
4258 // that is out of range, or a decimal literal that does not fit in a
4259 // signed long long and has no U suffix.
4260 if (Ty.isNull()) {
4261 if (Literal.isSizeT)
4262 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4263 << Literal.isUnsigned;
4264 else
4265 Diag(Tok.getLocation(),
4266 diag::ext_integer_literal_too_large_for_signed);
4267 Ty = Context.UnsignedLongLongTy;
4268 Width = Context.getTargetInfo().getLongLongWidth();
4269 }
4270
4271 if (ResultVal.getBitWidth() != Width)
4272 ResultVal = ResultVal.trunc(Width);
4273 }
4274 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4275 }
4276
4277 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4278 if (Literal.isImaginary) {
4279 Res = new (Context) ImaginaryLiteral(Res,
4280 Context.getComplexType(Res->getType()));
4281
4282 // In C++, this is a GNU extension. In C, it's a C2y extension.
4283 if (getLangOpts().CPlusPlus)
4284 Diag(Tok.getLocation(), diag::ext_gnu_imaginary_constant);
4285 else
4286 DiagCompat(Tok.getLocation(), diag_compat::imaginary_constant);
4287 }
4288 return Res;
4289}
4290
4292 assert(E && "ActOnParenExpr() missing expr");
4293 QualType ExprTy = E->getType();
4294 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4295 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4296 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4297 return new (Context) ParenExpr(L, R, E);
4298}
4299
4301 SourceLocation Loc,
4302 SourceRange ArgRange) {
4303 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4304 // scalar or vector data type argument..."
4305 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4306 // type (C99 6.2.5p18) or void.
4307 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4308 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4309 << T << ArgRange;
4310 return true;
4311 }
4312
4313 assert((T->isVoidType() || !T->isIncompleteType()) &&
4314 "Scalar types should always be complete");
4315 return false;
4316}
4317
4319 SourceLocation Loc,
4320 SourceRange ArgRange) {
4321 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4322 if (!T->isVectorType() && !T->isSizelessVectorType())
4323 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4324 << ""
4325 << "__builtin_vectorelements" << T << ArgRange;
4326
4327 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
4328 if (T->isSVESizelessBuiltinType()) {
4329 llvm::StringMap<bool> CallerFeatureMap;
4330 S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
4331 return S.ARM().checkSVETypeSupport(T, Loc, FD, CallerFeatureMap);
4332 }
4333 }
4334
4335 return false;
4336}
4337
4339 SourceLocation Loc,
4340 SourceRange ArgRange) {
4341 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4342 return true;
4343
4344 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4345 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4346 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4347 return true;
4348 }
4349
4350 return false;
4351}
4352
4354 SourceLocation Loc,
4355 SourceRange ArgRange,
4356 UnaryExprOrTypeTrait TraitKind) {
4357 // Invalid types must be hard errors for SFINAE in C++.
4358 if (S.LangOpts.CPlusPlus)
4359 return true;
4360
4361 // C99 6.5.3.4p1:
4362 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4363 TraitKind == UETT_PreferredAlignOf) {
4364
4365 // sizeof(function)/alignof(function) is allowed as an extension.
4366 if (T->isFunctionType()) {
4367 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4368 << getTraitSpelling(TraitKind) << ArgRange;
4369 return false;
4370 }
4371
4372 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4373 // this is an error (OpenCL v1.1 s6.3.k)
4374 if (T->isVoidType()) {
4375 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4376 : diag::ext_sizeof_alignof_void_type;
4377 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4378 return false;
4379 }
4380 }
4381 return true;
4382}
4383
4385 SourceLocation Loc,
4386 SourceRange ArgRange,
4387 UnaryExprOrTypeTrait TraitKind) {
4388 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4389 // runtime doesn't allow it.
4390 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4391 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4392 << T << (TraitKind == UETT_SizeOf)
4393 << ArgRange;
4394 return true;
4395 }
4396
4397 return false;
4398}
4399
4400/// Check whether E is a pointer from a decayed array type (the decayed
4401/// pointer type is equal to T) and emit a warning if it is.
4403 const Expr *E) {
4404 // Don't warn if the operation changed the type.
4405 if (T != E->getType())
4406 return;
4407
4408 // Now look for array decays.
4409 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4410 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4411 return;
4412
4413 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4414 << ICE->getType()
4415 << ICE->getSubExpr()->getType();
4416}
4417
4419 UnaryExprOrTypeTrait ExprKind) {
4420 QualType ExprTy = E->getType();
4421 assert(!ExprTy->isReferenceType());
4422
4423 bool IsUnevaluatedOperand =
4424 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4425 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4426 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4427 if (IsUnevaluatedOperand) {
4429 if (Result.isInvalid())
4430 return true;
4431 E = Result.get();
4432 }
4433
4434 // The operand for sizeof and alignof is in an unevaluated expression context,
4435 // so side effects could result in unintended consequences.
4436 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4437 // used to build SFINAE gadgets.
4438 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4439 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4441 !E->getType()->isVariableArrayType() &&
4442 E->HasSideEffects(Context, false))
4443 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4444
4445 if (ExprKind == UETT_VecStep)
4446 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4447 E->getSourceRange());
4448
4449 if (ExprKind == UETT_VectorElements)
4450 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4451 E->getSourceRange());
4452
4453 // Explicitly list some types as extensions.
4454 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4455 E->getSourceRange(), ExprKind))
4456 return false;
4457
4458 // WebAssembly tables are always illegal operands to unary expressions and
4459 // type traits.
4460 if (Context.getTargetInfo().getTriple().isWasm() &&
4462 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4463 << getTraitSpelling(ExprKind);
4464 return true;
4465 }
4466
4467 // 'alignof' applied to an expression only requires the base element type of
4468 // the expression to be complete. 'sizeof' requires the expression's type to
4469 // be complete (and will attempt to complete it if it's an array of unknown
4470 // bound).
4471 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4473 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4474 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4475 getTraitSpelling(ExprKind), E->getSourceRange()))
4476 return true;
4477 } else {
4479 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4480 getTraitSpelling(ExprKind), E->getSourceRange()))
4481 return true;
4482 }
4483
4484 // Completing the expression's type may have changed it.
4485 ExprTy = E->getType();
4486 assert(!ExprTy->isReferenceType());
4487
4488 if (ExprTy->isFunctionType()) {
4489 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4490 << getTraitSpelling(ExprKind) << E->getSourceRange();
4491 return true;
4492 }
4493
4494 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4495 E->getSourceRange(), ExprKind))
4496 return true;
4497
4498 if (ExprKind == UETT_CountOf) {
4499 // The type has to be an array type. We already checked for incomplete
4500 // types above.
4501 QualType ExprType = E->IgnoreParens()->getType();
4502 if (!ExprType->isArrayType()) {
4503 Diag(E->getExprLoc(), diag::err_countof_arg_not_array_type) << ExprType;
4504 return true;
4505 }
4506 // FIXME: warn on _Countof on an array parameter. Not warning on it
4507 // currently because there are papers in WG14 about array types which do
4508 // not decay that could impact this behavior, so we want to see if anything
4509 // changes here before coming up with a warning group for _Countof-related
4510 // diagnostics.
4511 }
4512
4513 if (ExprKind == UETT_SizeOf) {
4514 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4515 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4516 QualType OType = PVD->getOriginalType();
4517 QualType Type = PVD->getType();
4518 if (Type->isPointerType() && OType->isArrayType()) {
4519 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4520 << Type << OType;
4521 Diag(PVD->getLocation(), diag::note_declared_at);
4522 }
4523 }
4524 }
4525
4526 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4527 // decays into a pointer and returns an unintended result. This is most
4528 // likely a typo for "sizeof(array) op x".
4529 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4530 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4531 BO->getLHS());
4532 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4533 BO->getRHS());
4534 }
4535 }
4536
4537 return false;
4538}
4539
4540static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4541 // Cannot know anything else if the expression is dependent.
4542 if (E->isTypeDependent())
4543 return false;
4544
4545 if (E->getObjectKind() == OK_BitField) {
4546 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4547 << 1 << E->getSourceRange();
4548 return true;
4549 }
4550
4551 ValueDecl *D = nullptr;
4552 Expr *Inner = E->IgnoreParens();
4553 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4554 D = DRE->getDecl();
4555 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4556 D = ME->getMemberDecl();
4557 }
4558
4559 // If it's a field, require the containing struct to have a
4560 // complete definition so that we can compute the layout.
4561 //
4562 // This can happen in C++11 onwards, either by naming the member
4563 // in a way that is not transformed into a member access expression
4564 // (in an unevaluated operand, for instance), or by naming the member
4565 // in a trailing-return-type.
4566 //
4567 // For the record, since __alignof__ on expressions is a GCC
4568 // extension, GCC seems to permit this but always gives the
4569 // nonsensical answer 0.
4570 //
4571 // We don't really need the layout here --- we could instead just
4572 // directly check for all the appropriate alignment-lowing
4573 // attributes --- but that would require duplicating a lot of
4574 // logic that just isn't worth duplicating for such a marginal
4575 // use-case.
4576 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4577 // Fast path this check, since we at least know the record has a
4578 // definition if we can find a member of it.
4579 if (!FD->getParent()->isCompleteDefinition()) {
4580 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4581 << E->getSourceRange();
4582 return true;
4583 }
4584
4585 // Otherwise, if it's a field, and the field doesn't have
4586 // reference type, then it must have a complete type (or be a
4587 // flexible array member, which we explicitly want to
4588 // white-list anyway), which makes the following checks trivial.
4589 if (!FD->getType()->isReferenceType())
4590 return false;
4591 }
4592
4593 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4594}
4595
4597 E = E->IgnoreParens();
4598
4599 // Cannot know anything else if the expression is dependent.
4600 if (E->isTypeDependent())
4601 return false;
4602
4603 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4604}
4605
4607 CapturingScopeInfo *CSI) {
4608 assert(T->isVariablyModifiedType());
4609 assert(CSI != nullptr);
4610
4611 // We're going to walk down into the type and look for VLA expressions.
4612 do {
4613 const Type *Ty = T.getTypePtr();
4614 switch (Ty->getTypeClass()) {
4615#define TYPE(Class, Base)
4616#define ABSTRACT_TYPE(Class, Base)
4617#define NON_CANONICAL_TYPE(Class, Base)
4618#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4619#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4620#include "clang/AST/TypeNodes.inc"
4621 T = QualType();
4622 break;
4623 // These types are never variably-modified.
4624 case Type::Builtin:
4625 case Type::Complex:
4626 case Type::Vector:
4627 case Type::ExtVector:
4628 case Type::ConstantMatrix:
4629 case Type::Record:
4630 case Type::Enum:
4631 case Type::TemplateSpecialization:
4632 case Type::ObjCObject:
4633 case Type::ObjCInterface:
4634 case Type::ObjCObjectPointer:
4635 case Type::ObjCTypeParam:
4636 case Type::Pipe:
4637 case Type::BitInt:
4638 case Type::HLSLInlineSpirv:
4639 llvm_unreachable("type class is never variably-modified!");
4640 case Type::Adjusted:
4641 T = cast<AdjustedType>(Ty)->getOriginalType();
4642 break;
4643 case Type::Decayed:
4644 T = cast<DecayedType>(Ty)->getPointeeType();
4645 break;
4646 case Type::ArrayParameter:
4647 T = cast<ArrayParameterType>(Ty)->getElementType();
4648 break;
4649 case Type::Pointer:
4650 T = cast<PointerType>(Ty)->getPointeeType();
4651 break;
4652 case Type::BlockPointer:
4653 T = cast<BlockPointerType>(Ty)->getPointeeType();
4654 break;
4655 case Type::LValueReference:
4656 case Type::RValueReference:
4657 T = cast<ReferenceType>(Ty)->getPointeeType();
4658 break;
4659 case Type::MemberPointer:
4660 T = cast<MemberPointerType>(Ty)->getPointeeType();
4661 break;
4662 case Type::ConstantArray:
4663 case Type::IncompleteArray:
4664 // Losing element qualification here is fine.
4665 T = cast<ArrayType>(Ty)->getElementType();
4666 break;
4667 case Type::VariableArray: {
4668 // Losing element qualification here is fine.
4670
4671 // Unknown size indication requires no size computation.
4672 // Otherwise, evaluate and record it.
4673 auto Size = VAT->getSizeExpr();
4674 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4676 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4677
4678 T = VAT->getElementType();
4679 break;
4680 }
4681 case Type::FunctionProto:
4682 case Type::FunctionNoProto:
4683 T = cast<FunctionType>(Ty)->getReturnType();
4684 break;
4685 case Type::Paren:
4686 case Type::TypeOf:
4687 case Type::UnaryTransform:
4688 case Type::Attributed:
4689 case Type::BTFTagAttributed:
4690 case Type::OverflowBehavior:
4691 case Type::HLSLAttributedResource:
4692 case Type::SubstTemplateTypeParm:
4693 case Type::MacroQualified:
4694 case Type::CountAttributed:
4695 case Type::LateParsedAttr:
4696 // Keep walking after single level desugaring.
4697 T = T.getSingleStepDesugaredType(Context);
4698 break;
4699 case Type::Typedef:
4700 T = cast<TypedefType>(Ty)->desugar();
4701 break;
4702 case Type::Decltype:
4703 T = cast<DecltypeType>(Ty)->desugar();
4704 break;
4705 case Type::PackIndexing:
4706 T = cast<PackIndexingType>(Ty)->desugar();
4707 break;
4708 case Type::Using:
4709 T = cast<UsingType>(Ty)->desugar();
4710 break;
4711 case Type::Auto:
4712 case Type::DeducedTemplateSpecialization:
4713 T = cast<DeducedType>(Ty)->getDeducedType();
4714 break;
4715 case Type::TypeOfExpr:
4716 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4717 break;
4718 case Type::Atomic:
4719 T = cast<AtomicType>(Ty)->getValueType();
4720 break;
4721 case Type::PredefinedSugar:
4722 T = cast<PredefinedSugarType>(Ty)->desugar();
4723 break;
4724 }
4725 } while (!T.isNull() && T->isVariablyModifiedType());
4726}
4727
4729 SourceLocation OpLoc,
4730 SourceRange ExprRange,
4731 UnaryExprOrTypeTrait ExprKind,
4732 StringRef KWName) {
4733 if (ExprType->isDependentType())
4734 return false;
4735
4736 // C++ [expr.sizeof]p2:
4737 // When applied to a reference or a reference type, the result
4738 // is the size of the referenced type.
4739 // C++11 [expr.alignof]p3:
4740 // When alignof is applied to a reference type, the result
4741 // shall be the alignment of the referenced type.
4742 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4743 ExprType = Ref->getPointeeType();
4744
4745 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4746 // When alignof or _Alignof is applied to an array type, the result
4747 // is the alignment of the element type.
4748 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4749 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4750 // If the trait is 'alignof' in C before C2y, the ability to apply the
4751 // trait to an incomplete array is an extension.
4752 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4753 ExprType->isIncompleteArrayType())
4754 DiagCompat(OpLoc, diag_compat::alignof_incomplete_array);
4755 ExprType = Context.getBaseElementType(ExprType);
4756 }
4757
4758 if (ExprKind == UETT_VecStep)
4759 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4760
4761 if (ExprKind == UETT_VectorElements)
4762 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4763 ExprRange);
4764
4765 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4766 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4767 ExprRange);
4768
4769 // Explicitly list some types as extensions.
4770 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4771 ExprKind))
4772 return false;
4773
4775 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4776 KWName, ExprRange))
4777 return true;
4778
4779 if (ExprType->isFunctionType()) {
4780 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4781 return true;
4782 }
4783
4784 if (ExprKind == UETT_CountOf) {
4785 // The type has to be an array type. We already checked for incomplete
4786 // types above.
4787 if (!ExprType->isArrayType()) {
4788 Diag(OpLoc, diag::err_countof_arg_not_array_type) << ExprType;
4789 return true;
4790 }
4791 }
4792
4793 // WebAssembly tables are always illegal operands to unary expressions and
4794 // type traits.
4795 if (Context.getTargetInfo().getTriple().isWasm() &&
4796 ExprType->isWebAssemblyTableType()) {
4797 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4798 << getTraitSpelling(ExprKind);
4799 return true;
4800 }
4801
4802 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4803 ExprKind))
4804 return true;
4805
4806 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4807 if (auto *TT = ExprType->getAs<TypedefType>()) {
4808 for (auto I = FunctionScopes.rbegin(),
4809 E = std::prev(FunctionScopes.rend());
4810 I != E; ++I) {
4811 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4812 if (CSI == nullptr)
4813 break;
4814 DeclContext *DC = nullptr;
4815 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4816 DC = LSI->CallOperator;
4817 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4818 DC = CRSI->TheCapturedDecl;
4819 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4820 DC = BSI->TheDecl;
4821 if (DC) {
4822 if (DC->containsDecl(TT->getDecl()))
4823 break;
4824 captureVariablyModifiedType(Context, ExprType, CSI);
4825 }
4826 }
4827 }
4828 }
4829
4830 return false;
4831}
4832
4834 SourceLocation OpLoc,
4835 UnaryExprOrTypeTrait ExprKind,
4836 SourceRange R) {
4837 if (!TInfo)
4838 return ExprError();
4839
4840 QualType T = TInfo->getType();
4841
4842 if (!T->isDependentType() &&
4843 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4844 getTraitSpelling(ExprKind)))
4845 return ExprError();
4846
4847 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4848 // properly deal with VLAs in nested calls of sizeof and typeof.
4849 if (currentEvaluationContext().isUnevaluated() &&
4850 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4851 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4852 TInfo->getType()->isVariablyModifiedType())
4853 TInfo = TransformToPotentiallyEvaluated(TInfo);
4854
4855 // It's possible that the transformation above failed.
4856 if (!TInfo)
4857 return ExprError();
4858
4859 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4860 return new (Context) UnaryExprOrTypeTraitExpr(
4861 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4862}
4863
4866 UnaryExprOrTypeTrait ExprKind) {
4868 if (PE.isInvalid())
4869 return ExprError();
4870
4871 E = PE.get();
4872
4873 // Verify that the operand is valid.
4874 bool isInvalid = false;
4875 if (E->isTypeDependent()) {
4876 // Delay type-checking for type-dependent expressions.
4877 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4878 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4879 } else if (ExprKind == UETT_VecStep) {
4881 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4882 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4883 isInvalid = true;
4884 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4885 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4886 isInvalid = true;
4887 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4888 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4890 }
4891
4892 if (isInvalid)
4893 return ExprError();
4894
4895 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4896 E->getType()->isVariableArrayType()) {
4898 if (PE.isInvalid()) return ExprError();
4899 E = PE.get();
4900 }
4901
4902 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4903 return new (Context) UnaryExprOrTypeTraitExpr(
4904 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4905}
4906
4909 UnaryExprOrTypeTrait ExprKind, bool IsType,
4910 void *TyOrEx, SourceRange ArgRange) {
4911 // If error parsing type, ignore.
4912 if (!TyOrEx) return ExprError();
4913
4914 if (IsType) {
4915 TypeSourceInfo *TInfo;
4916 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4917 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4918 }
4919
4920 Expr *ArgEx = (Expr *)TyOrEx;
4921 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4922 return Result;
4923}
4924
4926 SourceLocation OpLoc, SourceRange R) {
4927 if (!TInfo)
4928 return true;
4929 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4930 UETT_AlignOf, KWName);
4931}
4932
4934 SourceLocation OpLoc, SourceRange R) {
4935 TypeSourceInfo *TInfo;
4937 &TInfo);
4938 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4939}
4940
4942 bool IsReal) {
4943 if (V.get()->isTypeDependent())
4944 return S.Context.DependentTy;
4945
4946 // _Real and _Imag are only l-values for normal l-values.
4947 if (V.get()->getObjectKind() != OK_Ordinary) {
4948 V = S.DefaultLvalueConversion(V.get());
4949 if (V.isInvalid())
4950 return QualType();
4951 }
4952
4953 // These operators return the element type of a complex type.
4954 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4955 return CT->getElementType();
4956
4957 // Otherwise they pass through real integer and floating point types here.
4958 if (V.get()->getType()->isArithmeticType())
4959 return V.get()->getType();
4960
4961 // Test for placeholders.
4962 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4963 if (PR.isInvalid()) return QualType();
4964 if (PR.get() != V.get()) {
4965 V = PR;
4966 return CheckRealImagOperand(S, V, Loc, IsReal);
4967 }
4968
4969 // Reject anything else.
4970 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4971 << (IsReal ? "__real" : "__imag");
4972 return QualType();
4973}
4974
4975
4976
4979 tok::TokenKind Kind, Expr *Input) {
4981 switch (Kind) {
4982 default: llvm_unreachable("Unknown unary op!");
4983 case tok::plusplus: Opc = UO_PostInc; break;
4984 case tok::minusminus: Opc = UO_PostDec; break;
4985 }
4986
4987 // Since this might is a postfix expression, get rid of ParenListExprs.
4989 if (Result.isInvalid()) return ExprError();
4990 Input = Result.get();
4991
4992 return BuildUnaryOp(S, OpLoc, Opc, Input);
4993}
4994
4995/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4996///
4997/// \return true on error
4999 SourceLocation opLoc,
5000 Expr *op) {
5001 assert(op->getType()->isObjCObjectPointerType());
5003 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
5004 return false;
5005
5006 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
5008 << op->getSourceRange();
5009 return true;
5010}
5011
5013 auto *BaseNoParens = Base->IgnoreParens();
5014 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
5015 return MSProp->getPropertyDecl()->getType()->isArrayType();
5016 return isa<MSPropertySubscriptExpr>(BaseNoParens);
5017}
5018
5019// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5020// Typically this is DependentTy, but can sometimes be more precise.
5021//
5022// There are cases when we could determine a non-dependent type:
5023// - LHS and RHS may have non-dependent types despite being type-dependent
5024// (e.g. unbounded array static members of the current instantiation)
5025// - one may be a dependent-sized array with known element type
5026// - one may be a dependent-typed valid index (enum in current instantiation)
5027//
5028// We *always* return a dependent type, in such cases it is DependentTy.
5029// This avoids creating type-dependent expressions with non-dependent types.
5030// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5032 const ASTContext &Ctx) {
5033 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5034 QualType LTy = LHS->getType(), RTy = RHS->getType();
5036 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5037 if (const PointerType *PT = LTy->getAs<PointerType>())
5038 Result = PT->getPointeeType();
5039 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5040 Result = AT->getElementType();
5041 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5042 if (const PointerType *PT = RTy->getAs<PointerType>())
5043 Result = PT->getPointeeType();
5044 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5045 Result = AT->getElementType();
5046 }
5047 // Ensure we return a dependent type.
5048 return Result->isDependentType() ? Result : Ctx.DependentTy;
5049}
5050
5052 SourceLocation lbLoc,
5053 MultiExprArg ArgExprs,
5054 SourceLocation rbLoc) {
5055
5056 if (base && !base->getType().isNull() &&
5057 base->hasPlaceholderType(BuiltinType::ArraySection)) {
5058 auto *AS = cast<ArraySectionExpr>(base);
5059 if (AS->isOMPArraySection())
5061 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
5062 /*Length*/ nullptr,
5063 /*Stride=*/nullptr, rbLoc);
5064
5065 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
5066 SourceLocation(), /*Length*/ nullptr,
5067 rbLoc);
5068 }
5069
5070 // Since this might be a postfix expression, get rid of ParenListExprs.
5071 if (isa<ParenListExpr>(base)) {
5073 if (result.isInvalid())
5074 return ExprError();
5075 base = result.get();
5076 }
5077
5078 // Check if base and idx form a MatrixSubscriptExpr.
5079 //
5080 // Helper to check for comma expressions, which are not allowed as indices for
5081 // matrix subscript expressions.
5082 //
5083 // In C++23, we get multiple arguments instead of a comma expression.
5084 auto CheckAndReportCommaError = [&](Expr *E) {
5085 if (ArgExprs.size() > 1 ||
5086 (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp())) {
5087 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
5088 << SourceRange(base->getBeginLoc(), rbLoc);
5089 return true;
5090 }
5091 return false;
5092 };
5093 // The matrix subscript operator ([][])is considered a single operator.
5094 // Separating the index expressions by parenthesis is not allowed.
5095 if (base && !base->getType().isNull() &&
5096 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
5097 !isa<MatrixSubscriptExpr>(base)) {
5098 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
5099 << SourceRange(base->getBeginLoc(), rbLoc);
5100 return ExprError();
5101 }
5102 // If the base is a MatrixSubscriptExpr, try to create a new
5103 // MatrixSubscriptExpr.
5104 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
5105 if (matSubscriptE && matSubscriptE->isIncomplete()) {
5106 if (CheckAndReportCommaError(ArgExprs.front()))
5107 return ExprError();
5108
5109 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
5110 matSubscriptE->getRowIdx(),
5111 ArgExprs.front(), rbLoc);
5112 }
5113 if (base->getType()->isWebAssemblyTableType()) {
5114 Diag(base->getExprLoc(), diag::err_wasm_table_art)
5115 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5116 return ExprError();
5117 }
5118
5119 CheckInvalidBuiltinCountedByRef(base,
5121
5122 // Handle any non-overload placeholder types in the base and index
5123 // expressions. We can't handle overloads here because the other
5124 // operand might be an overloadable type, in which case the overload
5125 // resolution for the operator overload should get the first crack
5126 // at the overload.
5127 bool IsMSPropertySubscript = false;
5128 if (base->getType()->isNonOverloadPlaceholderType()) {
5129 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5130 if (!IsMSPropertySubscript) {
5131 ExprResult result = CheckPlaceholderExpr(base);
5132 if (result.isInvalid())
5133 return ExprError();
5134 base = result.get();
5135 }
5136 }
5137
5138 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5139 if (base->getType()->isMatrixType()) {
5140 if (CheckAndReportCommaError(ArgExprs.front()))
5141 return ExprError();
5142
5143 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5144 rbLoc);
5145 }
5146
5147 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5148 Expr *idx = ArgExprs[0];
5149 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5151 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5152 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5153 << SourceRange(base->getBeginLoc(), rbLoc);
5154 }
5155 }
5156
5157 if (ArgExprs.size() == 1 &&
5158 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5159 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5160 if (result.isInvalid())
5161 return ExprError();
5162 ArgExprs[0] = result.get();
5163 } else {
5164 if (CheckArgsForPlaceholders(ArgExprs))
5165 return ExprError();
5166 }
5167
5168 // Build an unanalyzed expression if either operand is type-dependent.
5169 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5170 (base->isTypeDependent() ||
5172 !isa<PackExpansionExpr>(ArgExprs[0])) {
5173 return new (Context) ArraySubscriptExpr(
5174 base, ArgExprs.front(),
5175 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5176 VK_LValue, OK_Ordinary, rbLoc);
5177 }
5178
5179 // MSDN, property (C++)
5180 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5181 // This attribute can also be used in the declaration of an empty array in a
5182 // class or structure definition. For example:
5183 // __declspec(property(get=GetX, put=PutX)) int x[];
5184 // The above statement indicates that x[] can be used with one or more array
5185 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5186 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5187 if (IsMSPropertySubscript) {
5188 if (ArgExprs.size() > 1) {
5189 Diag(base->getExprLoc(),
5190 diag::err_ms_property_subscript_expects_single_arg);
5191 return ExprError();
5192 }
5193
5194 // Build MS property subscript expression if base is MS property reference
5195 // or MS property subscript.
5196 return new (Context)
5197 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5198 VK_LValue, OK_Ordinary, rbLoc);
5199 }
5200
5201 // Use C++ overloaded-operator rules if either operand has record
5202 // type. The spec says to do this if either type is *overloadable*,
5203 // but enum types can't declare subscript operators or conversion
5204 // operators, so there's nothing interesting for overload resolution
5205 // to do if there aren't any record types involved.
5206 //
5207 // ObjC pointers have their own subscripting logic that is not tied
5208 // to overload resolution and so should not take this path.
5209 //
5210 // Issue a better diagnostic if we tried to pass multiple arguments to
5211 // a builtin subscript operator rather than diagnosing this as a generic
5212 // overload resolution failure.
5213 if (ArgExprs.size() != 1 && !base->getType()->isDependentType() &&
5214 !base->getType()->isRecordType() &&
5215 !base->getType()->isObjCObjectPointerType()) {
5216 Diag(base->getExprLoc(), diag::err_ovl_builtin_subscript_expects_single_arg)
5217 << base->getType() << base->getSourceRange();
5218 return ExprError();
5219 }
5220
5222 ((base->getType()->isRecordType() ||
5223 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5224 ArgExprs[0]->getType()->isRecordType())))) {
5225 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5226 }
5227
5228 ExprResult Res =
5229 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5230
5231 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5232 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5233
5234 return Res;
5235}
5236
5239 InitializationKind Kind =
5241 InitializationSequence InitSeq(*this, Entity, Kind, E);
5242 return InitSeq.Perform(*this, Entity, Kind, E);
5243}
5244
5246 Expr *RowIdx,
5247 SourceLocation RBLoc) {
5249 if (BaseR.isInvalid())
5250 return BaseR;
5251 Base = BaseR.get();
5252
5253 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5254 if (RowR.isInvalid())
5255 return RowR;
5256 RowIdx = RowR.get();
5257
5258 // Build an unanalyzed expression if any of the operands is type-dependent.
5259 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5260 return new (Context)
5261 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5262
5263 // Check that IndexExpr is an integer expression. If it is a constant
5264 // expression, check that it is less than Dim (= the number of elements in the
5265 // corresponding dimension).
5266 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5267 bool IsColumnIdx) -> Expr * {
5268 if (!IndexExpr->getType()->isIntegerType() &&
5269 !IndexExpr->isTypeDependent()) {
5270 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5271 << IsColumnIdx;
5272 return nullptr;
5273 }
5274
5275 if (std::optional<llvm::APSInt> Idx =
5276 IndexExpr->getIntegerConstantExpr(Context)) {
5277 if ((*Idx < 0 || *Idx >= Dim)) {
5278 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5279 << IsColumnIdx << Dim;
5280 return nullptr;
5281 }
5282 }
5283
5284 ExprResult ConvExpr = IndexExpr;
5285 assert(!ConvExpr.isInvalid() &&
5286 "should be able to convert any integer type to size type");
5287 return ConvExpr.get();
5288 };
5289
5290 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5291 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5292 if (!RowIdx)
5293 return ExprError();
5294
5295 QualType RowVecQT =
5296 Context.getExtVectorType(MTy->getElementType(), MTy->getNumColumns());
5297
5298 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5299}
5300
5302 Expr *ColumnIdx,
5303 SourceLocation RBLoc) {
5305 if (BaseR.isInvalid())
5306 return BaseR;
5307 Base = BaseR.get();
5308
5309 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5310 if (RowR.isInvalid())
5311 return RowR;
5312 RowIdx = RowR.get();
5313
5314 if (!ColumnIdx)
5315 return new (Context) MatrixSubscriptExpr(
5316 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5317
5318 // Build an unanalyzed expression if any of the operands is type-dependent.
5319 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5320 ColumnIdx->isTypeDependent())
5321 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5322 Context.DependentTy, RBLoc);
5323
5324 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5325 if (ColumnR.isInvalid())
5326 return ColumnR;
5327 ColumnIdx = ColumnR.get();
5328
5329 // Check that IndexExpr is an integer expression. If it is a constant
5330 // expression, check that it is less than Dim (= the number of elements in the
5331 // corresponding dimension).
5332 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5333 bool IsColumnIdx) -> Expr * {
5334 if (!IndexExpr->getType()->isIntegerType() &&
5335 !IndexExpr->isTypeDependent()) {
5336 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5337 << IsColumnIdx;
5338 return nullptr;
5339 }
5340
5341 if (std::optional<llvm::APSInt> Idx =
5342 IndexExpr->getIntegerConstantExpr(Context)) {
5343 if ((*Idx < 0 || *Idx >= Dim)) {
5344 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5345 << IsColumnIdx << Dim;
5346 return nullptr;
5347 }
5348 }
5349
5350 ExprResult ConvExpr = IndexExpr;
5351 assert(!ConvExpr.isInvalid() &&
5352 "should be able to convert any integer type to size type");
5353 return ConvExpr.get();
5354 };
5355
5356 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5357 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5358 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5359 if (!RowIdx || !ColumnIdx)
5360 return ExprError();
5361
5362 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5363 MTy->getElementType(), RBLoc);
5364}
5365
5366void Sema::CheckAddressOfNoDeref(const Expr *E) {
5367 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5368 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5369
5370 // For expressions like `&(*s).b`, the base is recorded and what should be
5371 // checked.
5372 const MemberExpr *Member = nullptr;
5373 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5374 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5375
5376 LastRecord.PossibleDerefs.erase(StrippedExpr);
5377}
5378
5379void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5381 return;
5382
5383 QualType ResultTy = E->getType();
5384 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5385
5386 // Bail if the element is an array since it is not memory access.
5387 if (isa<ArrayType>(ResultTy))
5388 return;
5389
5390 if (ResultTy->hasAttr(attr::NoDeref)) {
5391 LastRecord.PossibleDerefs.insert(E);
5392 return;
5393 }
5394
5395 // Check if the base type is a pointer to a member access of a struct
5396 // marked with noderef.
5397 const Expr *Base = E->getBase();
5398 QualType BaseTy = Base->getType();
5399 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5400 // Not a pointer access
5401 return;
5402
5403 const MemberExpr *Member = nullptr;
5404 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5405 Member->isArrow())
5406 Base = Member->getBase();
5407
5408 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5409 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5410 LastRecord.PossibleDerefs.insert(E);
5411 }
5412}
5413
5416 Expr *Idx, SourceLocation RLoc) {
5417 Expr *LHSExp = Base;
5418 Expr *RHSExp = Idx;
5419
5422
5423 // Per C++ core issue 1213, the result is an xvalue if either operand is
5424 // a non-lvalue array, and an lvalue otherwise.
5425 if (getLangOpts().CPlusPlus11) {
5426 for (auto *Op : {LHSExp, RHSExp}) {
5427 Op = Op->IgnoreImplicit();
5428 if (Op->getType()->isArrayType() && !Op->isLValue())
5429 VK = VK_XValue;
5430 }
5431 }
5432
5433 // Perform default conversions.
5434 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5436 if (Result.isInvalid())
5437 return ExprError();
5438 LHSExp = Result.get();
5439 }
5441 if (Result.isInvalid())
5442 return ExprError();
5443 RHSExp = Result.get();
5444
5445 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5446
5447 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5448 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5449 // in the subscript position. As a result, we need to derive the array base
5450 // and index from the expression types.
5451 Expr *BaseExpr, *IndexExpr;
5452 QualType ResultType;
5453 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5454 BaseExpr = LHSExp;
5455 IndexExpr = RHSExp;
5456 ResultType =
5458 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5459 BaseExpr = LHSExp;
5460 IndexExpr = RHSExp;
5461 ResultType = PTy->getPointeeType();
5462 } else if (const ObjCObjectPointerType *PTy =
5463 LHSTy->getAs<ObjCObjectPointerType>()) {
5464 BaseExpr = LHSExp;
5465 IndexExpr = RHSExp;
5466
5467 // Use custom logic if this should be the pseudo-object subscript
5468 // expression.
5469 if (!LangOpts.isSubscriptPointerArithmetic())
5470 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5471 nullptr, nullptr);
5472
5473 ResultType = PTy->getPointeeType();
5474 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5475 // Handle the uncommon case of "123[Ptr]".
5476 BaseExpr = RHSExp;
5477 IndexExpr = LHSExp;
5478 ResultType = PTy->getPointeeType();
5479 } else if (const ObjCObjectPointerType *PTy =
5480 RHSTy->getAs<ObjCObjectPointerType>()) {
5481 // Handle the uncommon case of "123[Ptr]".
5482 BaseExpr = RHSExp;
5483 IndexExpr = LHSExp;
5484 ResultType = PTy->getPointeeType();
5485 if (!LangOpts.isSubscriptPointerArithmetic()) {
5486 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5487 << ResultType << BaseExpr->getSourceRange();
5488 return ExprError();
5489 }
5490 } else if (LHSTy->isSubscriptableVectorType()) {
5491 if (LHSTy->isBuiltinType() &&
5492 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5493 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5494 if (BTy->isSVEBool())
5495 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5496 << LHSExp->getSourceRange()
5497 << RHSExp->getSourceRange());
5498 ResultType = BTy->getSveEltType(Context);
5499 } else {
5500 const VectorType *VTy = LHSTy->getAs<VectorType>();
5501 ResultType = VTy->getElementType();
5502 }
5503 BaseExpr = LHSExp; // vectors: V[123]
5504 IndexExpr = RHSExp;
5505 // We apply C++ DR1213 to vector subscripting too.
5506 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5507 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5508 if (Materialized.isInvalid())
5509 return ExprError();
5510 LHSExp = Materialized.get();
5511 }
5512 VK = LHSExp->getValueKind();
5513 if (VK != VK_PRValue)
5514 OK = OK_VectorComponent;
5515
5516 QualType BaseType = BaseExpr->getType();
5517 Qualifiers BaseQuals = BaseType.getQualifiers();
5518 Qualifiers MemberQuals = ResultType.getQualifiers();
5519 Qualifiers Combined = BaseQuals + MemberQuals;
5520 if (Combined != MemberQuals)
5521 ResultType = Context.getQualifiedType(ResultType, Combined);
5522 } else if (LHSTy->isArrayType()) {
5523 // If we see an array that wasn't promoted by
5524 // DefaultFunctionArrayLvalueConversion, it must be an array that
5525 // wasn't promoted because of the C90 rule that doesn't
5526 // allow promoting non-lvalue arrays. Warn, then
5527 // force the promotion here.
5528 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5529 << LHSExp->getSourceRange();
5530 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5531 CK_ArrayToPointerDecay).get();
5532 LHSTy = LHSExp->getType();
5533
5534 BaseExpr = LHSExp;
5535 IndexExpr = RHSExp;
5536 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5537 } else if (RHSTy->isArrayType()) {
5538 // Same as previous, except for 123[f().a] case
5539 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5540 << RHSExp->getSourceRange();
5541 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5542 CK_ArrayToPointerDecay).get();
5543 RHSTy = RHSExp->getType();
5544
5545 BaseExpr = RHSExp;
5546 IndexExpr = LHSExp;
5547 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5548 } else {
5549 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5550 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5551 }
5552 // C99 6.5.2.1p1
5553 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5554 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5555 << IndexExpr->getSourceRange());
5556
5557 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5558 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5559 !IndexExpr->isTypeDependent()) {
5560 std::optional<llvm::APSInt> IntegerContantExpr =
5562 if (!IntegerContantExpr.has_value() ||
5563 IntegerContantExpr.value().isNegative())
5564 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5565 }
5566
5567 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5568 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5569 // type. Note that Functions are not objects, and that (in C99 parlance)
5570 // incomplete types are not object types.
5571 if (ResultType->isFunctionType()) {
5572 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5573 << ResultType << BaseExpr->getSourceRange();
5574 return ExprError();
5575 }
5576
5577 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5578 // GNU extension: subscripting on pointer to void
5579 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5580 << BaseExpr->getSourceRange();
5581
5582 // C forbids expressions of unqualified void type from being l-values.
5583 // See IsCForbiddenLValueType.
5584 if (!ResultType.hasQualifiers())
5585 VK = VK_PRValue;
5586 } else if (!ResultType->isDependentType() &&
5587 !ResultType.isWebAssemblyReferenceType() &&
5589 LLoc, ResultType,
5590 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5591 return ExprError();
5592
5593 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5594 !ResultType.isCForbiddenLValueType());
5595
5597 FunctionScopes.size() > 1) {
5598 if (auto *TT =
5599 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5600 for (auto I = FunctionScopes.rbegin(),
5601 E = std::prev(FunctionScopes.rend());
5602 I != E; ++I) {
5603 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5604 if (CSI == nullptr)
5605 break;
5606 DeclContext *DC = nullptr;
5607 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5608 DC = LSI->CallOperator;
5609 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5610 DC = CRSI->TheCapturedDecl;
5611 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5612 DC = BSI->TheDecl;
5613 if (DC) {
5614 if (DC->containsDecl(TT->getDecl()))
5615 break;
5617 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5618 }
5619 }
5620 }
5621 }
5622
5623 return new (Context)
5624 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5625}
5626
5628 ParmVarDecl *Param, Expr *RewrittenInit,
5629 bool SkipImmediateInvocations) {
5630 if (Param->hasUnparsedDefaultArg()) {
5631 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5632 // If we've already cleared out the location for the default argument,
5633 // that means we're parsing it right now.
5634 if (!UnparsedDefaultArgLocs.count(Param)) {
5635 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5636 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5637 Param->setInvalidDecl();
5638 return true;
5639 }
5640
5641 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5642 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5644 diag::note_default_argument_declared_here);
5645 return true;
5646 }
5647
5648 if (Param->hasUninstantiatedDefaultArg()) {
5649 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5650 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5651 return true;
5652 }
5653
5654 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5655 assert(Init && "default argument but no initializer?");
5656
5657 // If the default expression creates temporaries, we need to
5658 // push them to the current stack of expression temporaries so they'll
5659 // be properly destroyed.
5660 // FIXME: We should really be rebuilding the default argument with new
5661 // bound temporaries; see the comment in PR5810.
5662 // We don't need to do that with block decls, though, because
5663 // blocks in default argument expression can never capture anything.
5664 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5665 // Set the "needs cleanups" bit regardless of whether there are
5666 // any explicit objects.
5667 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5668 // Append all the objects to the cleanup list. Right now, this
5669 // should always be a no-op, because blocks in default argument
5670 // expressions should never be able to capture anything.
5671 assert(!InitWithCleanup->getNumObjects() &&
5672 "default argument expression has capturing blocks?");
5673 }
5674 // C++ [expr.const]p15.1:
5675 // An expression or conversion is in an immediate function context if it is
5676 // potentially evaluated and [...] its innermost enclosing non-block scope
5677 // is a function parameter scope of an immediate function.
5679 *this,
5683 Param);
5684 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5685 SkipImmediateInvocations;
5686 runWithSufficientStackSpace(CallLoc, [&] {
5687 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5688 });
5689 return false;
5690}
5691
5696 }
5697
5698 bool HasImmediateCalls = false;
5699
5700 bool VisitCallExpr(CallExpr *E) override {
5701 if (const FunctionDecl *FD = E->getDirectCallee())
5702 HasImmediateCalls |= FD->isImmediateFunction();
5704 }
5705
5707 if (const FunctionDecl *FD = E->getConstructor())
5708 HasImmediateCalls |= FD->isImmediateFunction();
5710 }
5711
5712 // SourceLocExpr are not immediate invocations
5713 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5714 // need to be rebuilt so that they refer to the correct SourceLocation and
5715 // DeclContext.
5717 HasImmediateCalls = true;
5719 }
5720
5721 // A nested lambda might have parameters with immediate invocations
5722 // in their default arguments.
5723 // The compound statement is not visited (as it does not constitute a
5724 // subexpression).
5725 // FIXME: We should consider visiting and transforming captures
5726 // with init expressions.
5727 bool VisitLambdaExpr(LambdaExpr *E) override {
5728 return VisitCXXMethodDecl(E->getCallOperator());
5729 }
5730
5732 return TraverseStmt(E->getExpr());
5733 }
5734
5736 return TraverseStmt(E->getExpr());
5737 }
5738};
5739
5741 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5744
5745 bool AlwaysRebuild() { return true; }
5746
5747 // Lambda can only have immediate invocations in the default
5748 // args of their parameters, which is transformed upon calling the closure.
5749 // The body is not a subexpression, so we have nothing to do.
5750 // FIXME: Immediate calls in capture initializers should be transformed.
5753
5754 // Make sure we don't rebuild the this pointer as it would
5755 // cause it to incorrectly point it to the outermost class
5756 // in the case of nested struct initialization.
5758
5759 // Rewrite to source location to refer to the context in which they are used.
5761 DeclContext *DC = E->getParentContext();
5762 if (DC == SemaRef.CurContext)
5763 return E;
5764
5765 // FIXME: During instantiation, because the rebuild of defaults arguments
5766 // is not always done in the context of the template instantiator,
5767 // we run the risk of producing a dependent source location
5768 // that would never be rebuilt.
5769 // This usually happens during overload resolution, or in contexts
5770 // where the value of the source location does not matter.
5771 // However, we should find a better way to deal with source location
5772 // of function templates.
5773 if (!SemaRef.CurrentInstantiationScope ||
5774 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5775 DC = SemaRef.CurContext;
5776
5777 return getDerived().RebuildSourceLocExpr(
5778 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5779 }
5780};
5781
5783 FunctionDecl *FD, ParmVarDecl *Param,
5784 Expr *Init) {
5785 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5786
5787 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5788 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5789 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5790 InitializationContext =
5792 if (!InitializationContext.has_value())
5793 InitializationContext.emplace(CallLoc, Param, CurContext);
5794
5795 if (!Init && !Param->hasUnparsedDefaultArg()) {
5796 // Mark that we are replacing a default argument first.
5797 // If we are instantiating a template we won't have to
5798 // retransform immediate calls.
5799 // C++ [expr.const]p15.1:
5800 // An expression or conversion is in an immediate function context if it
5801 // is potentially evaluated and [...] its innermost enclosing non-block
5802 // scope is a function parameter scope of an immediate function.
5804 *this,
5808 Param);
5809
5810 if (Param->hasUninstantiatedDefaultArg()) {
5811 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5812 return ExprError();
5813 }
5814 // CWG2631
5815 // An immediate invocation that is not evaluated where it appears is
5816 // evaluated and checked for whether it is a constant expression at the
5817 // point where the enclosing initializer is used in a function call.
5819 if (!NestedDefaultChecking)
5820 V.TraverseDecl(Param);
5821
5822 // Rewrite the call argument that was created from the corresponding
5823 // parameter's default argument.
5824 if (V.HasImmediateCalls ||
5825 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5826 if (V.HasImmediateCalls)
5827 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5828 CallLoc, Param, CurContext};
5829 // Pass down lifetime extending flag, and collect temporaries in
5830 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5834 ExprResult Res;
5835 runWithSufficientStackSpace(CallLoc, [&] {
5836 Res = Immediate.TransformInitializer(Param->getInit(),
5837 /*NotCopy=*/false);
5838 });
5839 if (Res.isInvalid())
5840 return ExprError();
5841 Res = ConvertParamDefaultArgument(Param, Res.get(),
5842 Res.get()->getBeginLoc());
5843 if (Res.isInvalid())
5844 return ExprError();
5845 Init = Res.get();
5846 }
5847 }
5848
5850 CallLoc, FD, Param, Init,
5851 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5852 return ExprError();
5853
5854 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5855 Init, InitializationContext->Context);
5856}
5857
5859 FieldDecl *Field) {
5860 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5861 return Pattern;
5862 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5863 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5865 ClassPattern->lookup(Field->getDeclName());
5866 auto Rng = llvm::make_filter_range(
5867 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5868 if (Rng.empty())
5869 return nullptr;
5870 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5871 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5872 // && "Duplicated instantiation pattern for field decl");
5873 return cast<FieldDecl>(*Rng.begin());
5874}
5875
5877 assert(Field->hasInClassInitializer());
5878
5879 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5880
5881 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5882
5883 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5884 InitializationContext =
5886 if (!InitializationContext.has_value())
5887 InitializationContext.emplace(Loc, Field, CurContext);
5888
5889 Expr *Init = nullptr;
5890
5891 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5892 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5895
5896 if (!Field->getInClassInitializer()) {
5897 // Maybe we haven't instantiated the in-class initializer. Go check the
5898 // pattern FieldDecl to see if it has one.
5899 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5900 FieldDecl *Pattern =
5902 assert(Pattern && "We must have set the Pattern!");
5903 if (!Pattern->hasInClassInitializer() ||
5904 InstantiateInClassInitializer(Loc, Field, Pattern,
5906 Field->setInvalidDecl();
5907 return ExprError();
5908 }
5909 }
5910 }
5911
5912 // CWG2631
5913 // An immediate invocation that is not evaluated where it appears is
5914 // evaluated and checked for whether it is a constant expression at the
5915 // point where the enclosing initializer is used in a [...] a constructor
5916 // definition, or an aggregate initialization.
5918 if (!NestedDefaultChecking)
5919 V.TraverseDecl(Field);
5920
5921 // CWG1815
5922 // Support lifetime extension of temporary created by aggregate
5923 // initialization using a default member initializer. We should rebuild
5924 // the initializer in a lifetime extension context if the initializer
5925 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5926 // extension code recurses into the default initializer and does lifetime
5927 // extension when warranted.
5928 bool ContainsAnyTemporaries =
5929 isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());
5930 if (Field->getInClassInitializer() &&
5931 !Field->getInClassInitializer()->containsErrors() &&
5932 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5933 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5934 CurContext};
5935 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5936 NestedDefaultChecking;
5937 // Pass down lifetime extending flag, and collect temporaries in
5938 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5942 ExprResult Res;
5944 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5945 /*CXXDirectInit=*/false);
5946 });
5947 if (!Res.isInvalid())
5948 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5949 if (Res.isInvalid()) {
5950 Field->setInvalidDecl();
5951 return ExprError();
5952 }
5953 Init = Res.get();
5954 }
5955
5956 if (Field->getInClassInitializer()) {
5957 Expr *E = Init ? Init : Field->getInClassInitializer();
5958 if (!NestedDefaultChecking)
5960 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5961 });
5964 // C++11 [class.base.init]p7:
5965 // The initialization of each base and member constitutes a
5966 // full-expression.
5967 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5968 if (Res.isInvalid()) {
5969 Field->setInvalidDecl();
5970 return ExprError();
5971 }
5972 Init = Res.get();
5973
5974 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5975 Field, InitializationContext->Context,
5976 Init);
5977 }
5978
5979 // DR1351:
5980 // If the brace-or-equal-initializer of a non-static data member
5981 // invokes a defaulted default constructor of its class or of an
5982 // enclosing class in a potentially evaluated subexpression, the
5983 // program is ill-formed.
5984 //
5985 // This resolution is unworkable: the exception specification of the
5986 // default constructor can be needed in an unevaluated context, in
5987 // particular, in the operand of a noexcept-expression, and we can be
5988 // unable to compute an exception specification for an enclosed class.
5989 //
5990 // Any attempt to resolve the exception specification of a defaulted default
5991 // constructor before the initializer is lexically complete will ultimately
5992 // come here at which point we can diagnose it.
5993 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5994 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5995 << OutermostClass << Field;
5996 Diag(Field->getEndLoc(),
5997 diag::note_default_member_initializer_not_yet_parsed);
5998 // Recover by marking the field invalid, unless we're in a SFINAE context.
5999 if (!isSFINAEContext())
6000 Field->setInvalidDecl();
6001 return ExprError();
6002}
6003
6005 const FunctionProtoType *Proto,
6006 Expr *Fn) {
6007 if (Proto && Proto->isVariadic()) {
6008 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
6010 else if (Fn && Fn->getType()->isBlockPointerType())
6012 else if (FDecl) {
6013 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6014 if (Method->isInstance())
6016 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6019 }
6021}
6022
6023namespace {
6024class FunctionCallCCC final : public FunctionCallFilterCCC {
6025public:
6026 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6027 unsigned NumArgs, MemberExpr *ME)
6028 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6029 FunctionName(FuncName) {}
6030
6031 bool ValidateCandidate(const TypoCorrection &candidate) override {
6032 if (!candidate.getCorrectionSpecifier() ||
6033 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6034 return false;
6035 }
6036
6038 }
6039
6040 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6041 return std::make_unique<FunctionCallCCC>(*this);
6042 }
6043
6044private:
6045 const IdentifierInfo *const FunctionName;
6046};
6047}
6048
6050 FunctionDecl *FDecl,
6051 ArrayRef<Expr *> Args) {
6052 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
6053 DeclarationName FuncName = FDecl->getDeclName();
6054 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6055
6056 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6057 if (TypoCorrection Corrected = S.CorrectTypo(
6059 S.getScopeForContext(S.CurContext), nullptr, CCC,
6061 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6062 if (Corrected.isOverloaded()) {
6065 for (NamedDecl *CD : Corrected) {
6066 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6068 OCS);
6069 }
6070 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6071 case OR_Success:
6072 ND = Best->FoundDecl;
6073 Corrected.setCorrectionDecl(ND);
6074 break;
6075 default:
6076 break;
6077 }
6078 }
6079 ND = ND->getUnderlyingDecl();
6081 return Corrected;
6082 }
6083 }
6084 return TypoCorrection();
6085}
6086
6087// [C++26][[expr.unary.op]/p4
6088// A pointer to member is only formed when an explicit &
6089// is used and its operand is a qualified-id not enclosed in parentheses.
6091 if (!isa<ParenExpr>(Fn))
6092 return false;
6093
6094 Fn = Fn->IgnoreParens();
6095
6096 auto *UO = dyn_cast<UnaryOperator>(Fn);
6097 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6098 return false;
6099 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
6100 return DRE->hasQualifier();
6101 }
6102 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
6103 return bool(OVL->getQualifier());
6104 return false;
6105}
6106
6107bool
6109 FunctionDecl *FDecl,
6110 const FunctionProtoType *Proto,
6111 ArrayRef<Expr *> Args,
6112 SourceLocation RParenLoc,
6113 bool IsExecConfig) {
6114 // Bail out early if calling a builtin with custom typechecking.
6115 // For HLSL builtin aliases, argument conversion is still needed because
6116 // overload resolution may have selected a conversion sequence (e.g.,
6117 // vector-to-scalar truncation) that must be applied before the custom
6118 // type checker runs.
6119 if (FDecl)
6120 if (unsigned ID = FDecl->getBuiltinID())
6121 if (Context.BuiltinInfo.hasCustomTypechecking(ID) &&
6122 !(Context.getLangOpts().HLSL && FDecl->hasAttr<BuiltinAliasAttr>()))
6123 return false;
6124
6125 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6126 // assignment, to the types of the corresponding parameter, ...
6127
6128 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6129 bool HasExplicitObjectParameter =
6130 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6131 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6132 unsigned NumParams = Proto->getNumParams();
6133 bool Invalid = false;
6134 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6135 unsigned FnKind = Fn->getType()->isBlockPointerType()
6136 ? 1 /* block */
6137 : (IsExecConfig ? 3 /* kernel function (exec config) */
6138 : 0 /* function */);
6139
6140 // If too few arguments are available (and we don't have default
6141 // arguments for the remaining parameters), don't make the call.
6142 if (Args.size() < NumParams) {
6143 if (Args.size() < MinArgs) {
6144 TypoCorrection TC;
6145 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6146 unsigned diag_id =
6147 MinArgs == NumParams && !Proto->isVariadic()
6148 ? diag::err_typecheck_call_too_few_args_suggest
6149 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6151 TC, PDiag(diag_id)
6152 << FnKind << MinArgs - ExplicitObjectParameterOffset
6153 << static_cast<unsigned>(Args.size()) -
6154 ExplicitObjectParameterOffset
6155 << HasExplicitObjectParameter << TC.getCorrectionRange());
6156 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6157 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6158 ->getDeclName())
6159 Diag(RParenLoc,
6160 MinArgs == NumParams && !Proto->isVariadic()
6161 ? diag::err_typecheck_call_too_few_args_one
6162 : diag::err_typecheck_call_too_few_args_at_least_one)
6163 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6164 << HasExplicitObjectParameter << Fn->getSourceRange();
6165 else
6166 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6167 ? diag::err_typecheck_call_too_few_args
6168 : diag::err_typecheck_call_too_few_args_at_least)
6169 << FnKind << MinArgs - ExplicitObjectParameterOffset
6170 << static_cast<unsigned>(Args.size()) -
6171 ExplicitObjectParameterOffset
6172 << HasExplicitObjectParameter << Fn->getSourceRange();
6173
6174 // Emit the location of the prototype.
6175 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6176 Diag(FDecl->getLocation(), diag::note_callee_decl)
6177 << FDecl << FDecl->getParametersSourceRange();
6178
6179 return true;
6180 }
6181 // We reserve space for the default arguments when we create
6182 // the call expression, before calling ConvertArgumentsForCall.
6183 assert((Call->getNumArgs() == NumParams) &&
6184 "We should have reserved space for the default arguments before!");
6185 }
6186
6187 // If too many are passed and not variadic, error on the extras and drop
6188 // them.
6189 if (Args.size() > NumParams) {
6190 if (!Proto->isVariadic()) {
6191 TypoCorrection TC;
6192 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6193 unsigned diag_id =
6194 MinArgs == NumParams && !Proto->isVariadic()
6195 ? diag::err_typecheck_call_too_many_args_suggest
6196 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6198 TC, PDiag(diag_id)
6199 << FnKind << NumParams - ExplicitObjectParameterOffset
6200 << static_cast<unsigned>(Args.size()) -
6201 ExplicitObjectParameterOffset
6202 << HasExplicitObjectParameter << TC.getCorrectionRange());
6203 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6204 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6205 ->getDeclName())
6206 Diag(Args[NumParams]->getBeginLoc(),
6207 MinArgs == NumParams
6208 ? diag::err_typecheck_call_too_many_args_one
6209 : diag::err_typecheck_call_too_many_args_at_most_one)
6210 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6211 << static_cast<unsigned>(Args.size()) -
6212 ExplicitObjectParameterOffset
6213 << HasExplicitObjectParameter << Fn->getSourceRange()
6214 << SourceRange(Args[NumParams]->getBeginLoc(),
6215 Args.back()->getEndLoc());
6216 else
6217 Diag(Args[NumParams]->getBeginLoc(),
6218 MinArgs == NumParams
6219 ? diag::err_typecheck_call_too_many_args
6220 : diag::err_typecheck_call_too_many_args_at_most)
6221 << FnKind << NumParams - ExplicitObjectParameterOffset
6222 << static_cast<unsigned>(Args.size()) -
6223 ExplicitObjectParameterOffset
6224 << HasExplicitObjectParameter << Fn->getSourceRange()
6225 << SourceRange(Args[NumParams]->getBeginLoc(),
6226 Args.back()->getEndLoc());
6227
6228 // Emit the location of the prototype.
6229 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6230 Diag(FDecl->getLocation(), diag::note_callee_decl)
6231 << FDecl << FDecl->getParametersSourceRange();
6232
6233 // This deletes the extra arguments.
6234 Call->shrinkNumArgs(NumParams);
6235 return true;
6236 }
6237 }
6238 SmallVector<Expr *, 8> AllArgs;
6239 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6240
6241 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
6242 AllArgs, CallType);
6243 if (Invalid)
6244 return true;
6245 unsigned TotalNumArgs = AllArgs.size();
6246 for (unsigned i = 0; i < TotalNumArgs; ++i)
6247 Call->setArg(i, AllArgs[i]);
6248
6249 Call->computeDependence();
6250 return false;
6251}
6252
6254 const FunctionProtoType *Proto,
6255 unsigned FirstParam, ArrayRef<Expr *> Args,
6256 SmallVectorImpl<Expr *> &AllArgs,
6257 VariadicCallType CallType, bool AllowExplicit,
6258 bool IsListInitialization) {
6259 unsigned NumParams = Proto->getNumParams();
6260 bool Invalid = false;
6261 size_t ArgIx = 0;
6262 // Continue to check argument types (even if we have too few/many args).
6263 for (unsigned i = FirstParam; i < NumParams; i++) {
6264 QualType ProtoArgType = Proto->getParamType(i);
6265
6266 Expr *Arg;
6267 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6268 if (ArgIx < Args.size()) {
6269 Arg = Args[ArgIx++];
6270
6271 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6272 diag::err_call_incomplete_argument, Arg))
6273 return true;
6274
6275 // Strip the unbridged-cast placeholder expression off, if applicable.
6276 bool CFAudited = false;
6277 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6278 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6279 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6280 Arg = ObjC().stripARCUnbridgedCast(Arg);
6281 else if (getLangOpts().ObjCAutoRefCount &&
6282 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6283 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6284 CFAudited = true;
6285
6286 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6287 ProtoArgType->isBlockPointerType())
6288 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6289 BE->getBlockDecl()->setDoesNotEscape();
6290 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
6292 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6293 if (ArgExpr.isInvalid())
6294 return true;
6295 Arg = ArgExpr.getAs<Expr>();
6296 }
6297
6298 InitializedEntity Entity =
6300 ProtoArgType)
6302 Context, ProtoArgType, Proto->isParamConsumed(i));
6303
6304 // Remember that parameter belongs to a CF audited API.
6305 if (CFAudited)
6306 Entity.setParameterCFAudited();
6307
6308 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6309 // function boundaries is a common oversight.
6310 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6311 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6312 bool isPedantic =
6313 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6314 Diag(Arg->getExprLoc(),
6315 isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6316 : diag::warn_obt_discarded_at_function_boundary)
6317 << Arg->getType() << ProtoArgType;
6318 }
6319
6321 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6322 if (ArgE.isInvalid())
6323 return true;
6324
6325 Arg = ArgE.getAs<Expr>();
6326 } else {
6327 assert(Param && "can't use default arguments without a known callee");
6328
6329 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6330 if (ArgExpr.isInvalid())
6331 return true;
6332
6333 Arg = ArgExpr.getAs<Expr>();
6334 }
6335
6336 // Check for array bounds violations for each argument to the call. This
6337 // check only triggers warnings when the argument isn't a more complex Expr
6338 // with its own checking, such as a BinaryOperator.
6339 CheckArrayAccess(Arg);
6340
6341 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6342 CheckStaticArrayArgument(CallLoc, Param, Arg);
6343
6344 AllArgs.push_back(Arg);
6345 }
6346
6347 // If this is a variadic call, handle args passed through "...".
6348 if (CallType != VariadicCallType::DoesNotApply) {
6349 // Assume that extern "C" functions with variadic arguments that
6350 // return __unknown_anytype aren't *really* variadic.
6351 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6352 FDecl->isExternC()) {
6353 for (Expr *A : Args.slice(ArgIx)) {
6354 QualType paramType; // ignored
6355 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6356 Invalid |= arg.isInvalid();
6357 AllArgs.push_back(arg.get());
6358 }
6359
6360 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6361 } else {
6362 for (Expr *A : Args.slice(ArgIx)) {
6363 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6364 Invalid |= Arg.isInvalid();
6365 AllArgs.push_back(Arg.get());
6366 }
6367 }
6368
6369 // Check for array bounds violations.
6370 for (Expr *A : Args.slice(ArgIx))
6371 CheckArrayAccess(A);
6372 }
6373 return Invalid;
6374}
6375
6377 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6378 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6379 TL = DTL.getOriginalLoc();
6380 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6381 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6382 << ATL.getLocalSourceRange();
6383}
6384
6385void
6387 ParmVarDecl *Param,
6388 const Expr *ArgExpr) {
6389 // Static array parameters are not supported in C++.
6390 if (!Param || getLangOpts().CPlusPlus)
6391 return;
6392
6393 QualType OrigTy = Param->getOriginalType();
6394
6395 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6396 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6397 return;
6398
6399 if (ArgExpr->isNullPointerConstant(Context,
6401 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6402 DiagnoseCalleeStaticArrayParam(*this, Param);
6403 return;
6404 }
6405
6406 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6407 if (!CAT)
6408 return;
6409
6410 const ConstantArrayType *ArgCAT =
6411 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6412 if (!ArgCAT)
6413 return;
6414
6415 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6416 ArgCAT->getElementType())) {
6417 if (ArgCAT->getSize().ult(CAT->getSize())) {
6418 Diag(CallLoc, diag::warn_static_array_too_small)
6419 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6420 << (unsigned)CAT->getZExtSize() << 0;
6421 DiagnoseCalleeStaticArrayParam(*this, Param);
6422 }
6423 return;
6424 }
6425
6426 std::optional<CharUnits> ArgSize =
6428 std::optional<CharUnits> ParmSize =
6430 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6431 Diag(CallLoc, diag::warn_static_array_too_small)
6432 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6433 << (unsigned)ParmSize->getQuantity() << 1;
6434 DiagnoseCalleeStaticArrayParam(*this, Param);
6435 }
6436}
6437
6438/// Given a function expression of unknown-any type, try to rebuild it
6439/// to have a function type.
6441
6442/// Is the given type a placeholder that we need to lower out
6443/// immediately during argument processing?
6445 // Placeholders are never sugared.
6446 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6447 if (!placeholder) return false;
6448
6449 switch (placeholder->getKind()) {
6450 // Ignore all the non-placeholder types.
6451#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6452 case BuiltinType::Id:
6453#include "clang/Basic/OpenCLImageTypes.def"
6454#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6455 case BuiltinType::Id:
6456#include "clang/Basic/OpenCLExtensionTypes.def"
6457 // In practice we'll never use this, since all SVE types are sugared
6458 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6459#define SVE_TYPE(Name, Id, SingletonId) \
6460 case BuiltinType::Id:
6461#include "clang/Basic/AArch64ACLETypes.def"
6462#define PPC_VECTOR_TYPE(Name, Id, Size) \
6463 case BuiltinType::Id:
6464#include "clang/Basic/PPCTypes.def"
6465#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6466#include "clang/Basic/RISCVVTypes.def"
6467#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6468#include "clang/Basic/WebAssemblyReferenceTypes.def"
6469#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6470#include "clang/Basic/AMDGPUTypes.def"
6471#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6472#include "clang/Basic/HLSLIntangibleTypes.def"
6473#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6474#include "clang/Basic/SPIRVTypes.def"
6475#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6476#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6477#include "clang/AST/BuiltinTypes.def"
6478 return false;
6479
6480 case BuiltinType::UnresolvedTemplate:
6481 // We cannot lower out overload sets; they might validly be resolved
6482 // by the call machinery.
6483 case BuiltinType::Overload:
6484 return false;
6485
6486 // Unbridged casts in ARC can be handled in some call positions and
6487 // should be left in place.
6488 case BuiltinType::ARCUnbridgedCast:
6489 return false;
6490
6491 // Pseudo-objects should be converted as soon as possible.
6492 case BuiltinType::PseudoObject:
6493 return true;
6494
6495 // The debugger mode could theoretically but currently does not try
6496 // to resolve unknown-typed arguments based on known parameter types.
6497 case BuiltinType::UnknownAny:
6498 return true;
6499
6500 // These are always invalid as call arguments and should be reported.
6501 case BuiltinType::BoundMember:
6502 case BuiltinType::BuiltinFn:
6503 case BuiltinType::IncompleteMatrixIdx:
6504 case BuiltinType::ArraySection:
6505 case BuiltinType::OMPArrayShaping:
6506 case BuiltinType::OMPIterator:
6507 return true;
6508
6509 }
6510 llvm_unreachable("bad builtin type kind");
6511}
6512
6514 // Apply this processing to all the arguments at once instead of
6515 // dying at the first failure.
6516 bool hasInvalid = false;
6517 for (size_t i = 0, e = args.size(); i != e; i++) {
6518 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6519 ExprResult result = CheckPlaceholderExpr(args[i]);
6520 if (result.isInvalid()) hasInvalid = true;
6521 else args[i] = result.get();
6522 }
6523 }
6524 return hasInvalid;
6525}
6526
6527/// If a builtin function has a pointer argument with no explicit address
6528/// space, then it should be able to accept a pointer to any address
6529/// space as input. In order to do this, we need to replace the
6530/// standard builtin declaration with one that uses the same address space
6531/// as the call.
6532///
6533/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6534/// it does not contain any pointer arguments without
6535/// an address space qualifer. Otherwise the rewritten
6536/// FunctionDecl is returned.
6537/// TODO: Handle pointer return types.
6539 FunctionDecl *FDecl,
6540 MultiExprArg ArgExprs) {
6541
6542 QualType DeclType = FDecl->getType();
6543 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6544
6545 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6546 ArgExprs.size() < FT->getNumParams())
6547 return nullptr;
6548
6549 bool NeedsNewDecl = false;
6550 unsigned i = 0;
6551 SmallVector<QualType, 8> OverloadParams;
6552
6553 {
6554 // The lvalue conversions in this loop are only for type resolution and
6555 // don't actually occur.
6558 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6559
6560 for (QualType ParamType : FT->param_types()) {
6561
6562 // Convert array arguments to pointer to simplify type lookup.
6563 ExprResult ArgRes =
6565 if (ArgRes.isInvalid())
6566 return nullptr;
6567 Expr *Arg = ArgRes.get();
6568 QualType ArgType = Arg->getType();
6569 if (!ParamType->isPointerType() ||
6570 ParamType->getPointeeType().hasAddressSpace() ||
6571 !ArgType->isPointerType() ||
6572 !ArgType->getPointeeType().hasAddressSpace() ||
6573 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6574 OverloadParams.push_back(ParamType);
6575 continue;
6576 }
6577
6578 QualType PointeeType = ParamType->getPointeeType();
6579 NeedsNewDecl = true;
6580 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6581
6582 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6583 OverloadParams.push_back(Context.getPointerType(PointeeType));
6584 }
6585 }
6586
6587 if (!NeedsNewDecl)
6588 return nullptr;
6589
6591 EPI.Variadic = FT->isVariadic();
6592 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6593 OverloadParams, EPI);
6594 DeclContext *Parent = FDecl->getParent();
6595 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6596 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6597 FDecl->getIdentifier(), OverloadTy,
6598 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6599 false,
6600 /*hasPrototype=*/true);
6602 FT = cast<FunctionProtoType>(OverloadTy);
6603 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6604 QualType ParamType = FT->getParamType(i);
6605 ParmVarDecl *Parm =
6606 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6607 SourceLocation(), nullptr, ParamType,
6608 /*TInfo=*/nullptr, SC_None, nullptr);
6609 Parm->setScopeInfo(0, i);
6610 Params.push_back(Parm);
6611 }
6612 OverloadDecl->setParams(Params);
6613 // We cannot merge host/device attributes of redeclarations. They have to
6614 // be consistent when created.
6615 if (Sema->LangOpts.CUDA) {
6616 if (FDecl->hasAttr<CUDAHostAttr>())
6617 OverloadDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
6618 if (FDecl->hasAttr<CUDADeviceAttr>())
6619 OverloadDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
6620 }
6621 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6622 return OverloadDecl;
6623}
6624
6625static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6626 FunctionDecl *Callee,
6627 MultiExprArg ArgExprs) {
6628 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6629 // similar attributes) really don't like it when functions are called with an
6630 // invalid number of args.
6631 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6632 /*PartialOverloading=*/false) &&
6633 !Callee->isVariadic())
6634 return;
6635 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6636 return;
6637
6638 if (const EnableIfAttr *Attr =
6639 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6640 S.Diag(Fn->getBeginLoc(),
6641 isa<CXXMethodDecl>(Callee)
6642 ? diag::err_ovl_no_viable_member_function_in_call
6643 : diag::err_ovl_no_viable_function_in_call)
6644 << Callee << Callee->getSourceRange();
6645 S.Diag(Callee->getLocation(),
6646 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6647 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6648 return;
6649 }
6650}
6651
6653 const UnresolvedMemberExpr *const UME, Sema &S) {
6654
6655 const auto GetFunctionLevelDCIfCXXClass =
6656 [](Sema &S) -> const CXXRecordDecl * {
6657 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6658 if (!DC || !DC->getParent())
6659 return nullptr;
6660
6661 // If the call to some member function was made from within a member
6662 // function body 'M' return return 'M's parent.
6663 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6664 return MD->getParent()->getCanonicalDecl();
6665 // else the call was made from within a default member initializer of a
6666 // class, so return the class.
6667 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6668 return RD->getCanonicalDecl();
6669 return nullptr;
6670 };
6671 // If our DeclContext is neither a member function nor a class (in the
6672 // case of a lambda in a default member initializer), we can't have an
6673 // enclosing 'this'.
6674
6675 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6676 if (!CurParentClass)
6677 return false;
6678
6679 // The naming class for implicit member functions call is the class in which
6680 // name lookup starts.
6681 const CXXRecordDecl *const NamingClass =
6683 assert(NamingClass && "Must have naming class even for implicit access");
6684
6685 // If the unresolved member functions were found in a 'naming class' that is
6686 // related (either the same or derived from) to the class that contains the
6687 // member function that itself contained the implicit member access.
6688
6689 return CurParentClass == NamingClass ||
6690 CurParentClass->isDerivedFrom(NamingClass);
6691}
6692
6693static void
6695 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6696
6697 if (!UME)
6698 return;
6699
6700 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6701 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6702 // already been captured, or if this is an implicit member function call (if
6703 // it isn't, an attempt to capture 'this' should already have been made).
6704 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6705 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6706 return;
6707
6708 // Check if the naming class in which the unresolved members were found is
6709 // related (same as or is a base of) to the enclosing class.
6710
6712 return;
6713
6714
6715 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6716 // If the enclosing function is not dependent, then this lambda is
6717 // capture ready, so if we can capture this, do so.
6718 if (!EnclosingFunctionCtx->isDependentContext()) {
6719 // If the current lambda and all enclosing lambdas can capture 'this' -
6720 // then go ahead and capture 'this' (since our unresolved overload set
6721 // contains at least one non-static member function).
6722 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6723 S.CheckCXXThisCapture(CallLoc);
6724 } else if (S.CurContext->isDependentContext()) {
6725 // ... since this is an implicit member reference, that might potentially
6726 // involve a 'this' capture, mark 'this' for potential capture in
6727 // enclosing lambdas.
6728 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6729 CurLSI->addPotentialThisCapture(CallLoc);
6730 }
6731}
6732
6733// Once a call is fully resolved, warn for unqualified calls to specific
6734// C++ standard functions, like move and forward.
6736 const CallExpr *Call) {
6737 // We are only checking unary move and forward so exit early here.
6738 if (Call->getNumArgs() != 1)
6739 return;
6740
6741 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6742 if (!E || isa<UnresolvedLookupExpr>(E))
6743 return;
6744 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6745 if (!DRE || !DRE->getLocation().isValid())
6746 return;
6747
6748 if (DRE->getQualifier())
6749 return;
6750
6751 const FunctionDecl *FD = Call->getDirectCallee();
6752 if (!FD)
6753 return;
6754
6755 // Only warn for some functions deemed more frequent or problematic.
6756 unsigned BuiltinID = FD->getBuiltinID();
6757 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6758 return;
6759
6760 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6762 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6763}
6764
6766 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6767 Expr *ExecConfig) {
6769 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6770 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6771 if (Call.isInvalid())
6772 return Call;
6773
6774 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6775 // language modes.
6776 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6777 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6778 DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id)
6779 << ULE->getName();
6780 }
6781
6782 if (LangOpts.OpenMP)
6783 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6784 ExecConfig);
6785 if (LangOpts.CPlusPlus) {
6786 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6788
6789 // If we previously found that the id-expression of this call refers to a
6790 // consteval function but the call is dependent, we should not treat is an
6791 // an invalid immediate call.
6792 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6793 DRE && Call.get()->isValueDependent()) {
6795 }
6796 }
6797 return Call;
6798}
6799
6800// Any type that could be used to form a callable expression
6801static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6802 QualType T = E->getType();
6803 if (T->isDependentType())
6804 return true;
6805
6806 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6807 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6808 T->isFunctionType() || T->isFunctionReferenceType() ||
6809 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6810 T->isBlockPointerType() || T->isRecordType() || T->isUndeducedType())
6811 return true;
6812
6815}
6816
6818 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6819 Expr *ExecConfig, bool IsExecConfig,
6820 bool AllowRecovery) {
6821 // Since this might be a postfix expression, get rid of ParenListExprs.
6823 if (Result.isInvalid()) return ExprError();
6824 Fn = Result.get();
6825
6826 // The __builtin_amdgcn_is_invocable builtin is special, and will be resolved
6827 // later, when we check boolean conditions, for now we merely forward it
6828 // without any additional checking.
6829 if (Fn->getType() == Context.BuiltinFnTy && ArgExprs.size() == 1 &&
6830 ArgExprs[0]->getType() == Context.BuiltinFnTy) {
6831 const auto *FD = cast<FunctionDecl>(Fn->getReferencedDeclOfCallee());
6832
6833 if (FD->getName() == "__builtin_amdgcn_is_invocable") {
6834 QualType FnPtrTy = Context.getPointerType(FD->getType());
6835 Expr *R = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6836 return CallExpr::Create(
6837 Context, R, ArgExprs, Context.AMDGPUFeaturePredicateTy,
6839 }
6840 }
6841
6842 if (CheckArgsForPlaceholders(ArgExprs))
6843 return ExprError();
6844
6845 // The result of __builtin_counted_by_ref cannot be used as a function
6846 // argument. It allows leaking and modification of bounds safety information.
6847 for (const Expr *Arg : ArgExprs)
6848 if (CheckInvalidBuiltinCountedByRef(Arg,
6850 return ExprError();
6851
6852 if (getLangOpts().CPlusPlus) {
6853 // If this is a pseudo-destructor expression, build the call immediately.
6855 if (!ArgExprs.empty()) {
6856 // Pseudo-destructor calls should not have any arguments.
6857 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6859 SourceRange(ArgExprs.front()->getBeginLoc(),
6860 ArgExprs.back()->getEndLoc()));
6861 }
6862
6863 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6864 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6865 }
6866 if (Fn->getType() == Context.PseudoObjectTy) {
6867 ExprResult result = CheckPlaceholderExpr(Fn);
6868 if (result.isInvalid()) return ExprError();
6869 Fn = result.get();
6870 }
6871
6872 // Determine whether this is a dependent call inside a C++ template,
6873 // in which case we won't do any semantic analysis now.
6874 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6875 if (ExecConfig) {
6877 cast<CallExpr>(ExecConfig), ArgExprs,
6878 Context.DependentTy, VK_PRValue,
6879 RParenLoc, CurFPFeatureOverrides());
6880 } else {
6881
6883 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6884 Fn->getBeginLoc());
6885
6886 // If the type of the function itself is not dependent
6887 // check that it is a reasonable as a function, as type deduction
6888 // later assume the CallExpr has a sensible TYPE.
6889 if (!MayBeFunctionType(Context, Fn))
6890 return ExprError(
6891 Diag(LParenLoc, diag::err_typecheck_call_not_function)
6892 << Fn->getType() << Fn->getSourceRange());
6893
6894 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6895 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6896 }
6897 }
6898
6899 // Determine whether this is a call to an object (C++ [over.call.object]).
6900 if (Fn->getType()->isRecordType())
6901 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6902 RParenLoc);
6903
6904 if (Fn->getType() == Context.UnknownAnyTy) {
6905 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6906 if (result.isInvalid()) return ExprError();
6907 Fn = result.get();
6908 }
6909
6910 if (Fn->getType() == Context.BoundMemberTy) {
6911 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6912 RParenLoc, ExecConfig, IsExecConfig,
6913 AllowRecovery);
6914 }
6915 }
6916
6917 // Check for overloaded calls. This can happen even in C due to extensions.
6918 if (Fn->getType() == Context.OverloadTy) {
6920
6921 // We aren't supposed to apply this logic if there's an '&' involved.
6924 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6925 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6926 OverloadExpr *ovl = find.Expression;
6927 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6929 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6930 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6931 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6932 RParenLoc, ExecConfig, IsExecConfig,
6933 AllowRecovery);
6934 }
6935 }
6936
6937 // If we're directly calling a function, get the appropriate declaration.
6938 if (Fn->getType() == Context.UnknownAnyTy) {
6939 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6940 if (result.isInvalid()) return ExprError();
6941 Fn = result.get();
6942 }
6943
6944 Expr *NakedFn = Fn->IgnoreParens();
6945
6946 bool CallingNDeclIndirectly = false;
6947 NamedDecl *NDecl = nullptr;
6948 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6949 if (UnOp->getOpcode() == UO_AddrOf) {
6950 CallingNDeclIndirectly = true;
6951 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6952 }
6953 }
6954
6955 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6956 NDecl = DRE->getDecl();
6957
6958 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6959 if (FDecl && FDecl->getBuiltinID()) {
6960 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
6961 if (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD) {
6962 if (Context.BuiltinInfo.isTSBuiltin(FDecl->getBuiltinID()) &&
6963 !Context.BuiltinInfo.isAuxBuiltinID(FDecl->getBuiltinID())) {
6965 getFunctionLevelDeclContext(/*AllowLambda=*/true)));
6966 }
6967 }
6968
6969 // Rewrite the function decl for this builtin by replacing parameters
6970 // with no explicit address space with the address space of the arguments
6971 // in ArgExprs.
6972 if ((FDecl =
6973 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6974 NDecl = FDecl;
6976 Context, DRE->getQualifierLoc(), SourceLocation(), FDecl, false,
6977 SourceLocation(), Fn->getType() /* BuiltinFnTy */,
6978 Fn->getValueKind(), FDecl, nullptr, DRE->isNonOdrUse());
6979 }
6980 }
6981 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6982 NDecl = ME->getMemberDecl();
6983
6984 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6985 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6986 FD, /*Complain=*/true, Fn->getBeginLoc()))
6987 return ExprError();
6988
6989 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6990
6991 // If this expression is a call to a builtin function in HIP compilation,
6992 // allow a pointer-type argument to default address space to be passed as a
6993 // pointer-type parameter to a non-default address space. If Arg is declared
6994 // in the default address space and Param is declared in a non-default
6995 // address space, perform an implicit address space cast to the parameter
6996 // type.
6997 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
6998 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6999 ++Idx) {
7000 ParmVarDecl *Param = FD->getParamDecl(Idx);
7001 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7002 !ArgExprs[Idx]->getType()->isPointerType())
7003 continue;
7004
7005 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7006 auto ArgTy = ArgExprs[Idx]->getType();
7007 auto ArgPtTy = ArgTy->getPointeeType();
7008 auto ArgAS = ArgPtTy.getAddressSpace();
7009
7010 // Add address space cast if target address spaces are different
7011 bool NeedImplicitASC =
7012 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7013 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7014 // or from specific AS which has target AS matching that of Param.
7016 if (!NeedImplicitASC)
7017 continue;
7018
7019 // First, ensure that the Arg is an RValue.
7020 if (ArgExprs[Idx]->isGLValue()) {
7021 ExprResult Res = DefaultLvalueConversion(ArgExprs[Idx]);
7022 if (Res.isInvalid())
7023 return ExprError();
7024 ArgExprs[Idx] = Res.get();
7025 }
7026
7027 // Construct a new arg type with address space of Param
7028 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7029 ArgPtQuals.setAddressSpace(ParamAS);
7030 auto NewArgPtTy =
7031 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
7032 auto NewArgTy =
7033 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
7034 ArgTy.getQualifiers());
7035
7036 // Finally perform an implicit address space cast
7037 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
7038 CK_AddressSpaceConversion)
7039 .get();
7040 }
7041 }
7042 }
7043
7044 if (Context.isDependenceAllowed() &&
7045 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
7046 assert(!getLangOpts().CPlusPlus);
7047 assert((Fn->containsErrors() ||
7048 llvm::any_of(ArgExprs,
7049 [](clang::Expr *E) { return E->containsErrors(); })) &&
7050 "should only occur in error-recovery path.");
7051 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7052 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7053 }
7054 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
7055 ExecConfig, IsExecConfig);
7056}
7057
7059 MultiExprArg CallArgs) {
7060 std::string Name = Context.BuiltinInfo.getName(Id);
7061 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7063 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
7064
7065 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7066 assert(BuiltInDecl && "failed to find builtin declaration");
7067
7068 ExprResult DeclRef =
7069 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7070 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7071
7073 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
7074
7075 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7076 return Call.get();
7077}
7078
7080 SourceLocation BuiltinLoc,
7081 SourceLocation RParenLoc) {
7082 QualType DstTy = GetTypeFromParser(ParsedDestTy);
7083 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
7084}
7085
7087 SourceLocation BuiltinLoc,
7088 SourceLocation RParenLoc) {
7091 QualType SrcTy = E->getType();
7092 if (!SrcTy->isDependentType() &&
7093 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7094 return ExprError(
7095 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7096 << DestTy << SrcTy << E->getSourceRange());
7097 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7098}
7099
7101 SourceLocation BuiltinLoc,
7102 SourceLocation RParenLoc) {
7103 TypeSourceInfo *TInfo;
7104 GetTypeFromParser(ParsedDestTy, &TInfo);
7105 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7106}
7107
7109 SourceLocation LParenLoc,
7110 ArrayRef<Expr *> Args,
7111 SourceLocation RParenLoc, Expr *Config,
7112 bool IsExecConfig, ADLCallKind UsesADL) {
7113 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
7114 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7115
7116 auto IsSJLJ = [&] {
7117 switch (BuiltinID) {
7118 case Builtin::BI__builtin_longjmp:
7119 case Builtin::BI__builtin_setjmp:
7120 case Builtin::BI__sigsetjmp:
7121 case Builtin::BI_longjmp:
7122 case Builtin::BI_setjmp:
7123 case Builtin::BIlongjmp:
7124 case Builtin::BIsetjmp:
7125 case Builtin::BIsiglongjmp:
7126 case Builtin::BIsigsetjmp:
7127 return true;
7128 default:
7129 return false;
7130 }
7131 };
7132
7133 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7134 if (!CurrentDefer.empty() && IsSJLJ()) {
7135 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7136 // for more than just blocks (e.g. lambdas, nested classes...).
7137 Scope *DeferParent = CurrentDefer.back().first;
7138 Scope *Block = CurScope->getBlockParent();
7139 if (DeferParent->Contains(*CurScope) &&
7140 (!Block || !DeferParent->Contains(*Block)))
7141 Diag(Fn->getExprLoc(), diag::err_defer_invalid_sjlj) << FDecl;
7142 }
7143
7144 // Functions with 'interrupt' attribute cannot be called directly.
7145 if (FDecl) {
7146 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7147 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7148 return ExprError();
7149 }
7150 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7151 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
7152 return ExprError();
7153 }
7154 }
7155
7156 // X86 interrupt handlers may only call routines with attribute
7157 // no_caller_saved_registers since there is no efficient way to
7158 // save and restore the non-GPR state.
7159 if (auto *Caller = getCurFunctionDecl()) {
7160 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7161 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7162 const TargetInfo &TI = Context.getTargetInfo();
7163 bool HasNonGPRRegisters =
7164 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
7165 if (HasNonGPRRegisters &&
7166 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7167 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
7168 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7169 if (FDecl)
7170 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7171 }
7172 }
7173 }
7174
7175 // Extract the return type from the builtin function pointer type.
7176 QualType ResultTy;
7177 if (BuiltinID)
7178 ResultTy = FDecl->getCallResultType();
7179 else
7180 ResultTy = Context.BoolTy;
7181
7182 // Promote the function operand.
7183 // We special-case function promotion here because we only allow promoting
7184 // builtin functions to function pointers in the callee of a call.
7186 if (BuiltinID &&
7187 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7188 // FIXME Several builtins still have setType in
7189 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7190 // Builtins.td to ensure they are correct before removing setType calls.
7191 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7192 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7193 } else
7195 if (Result.isInvalid())
7196 return ExprError();
7197 Fn = Result.get();
7198
7199 // Check for a valid function type, but only if it is not a builtin which
7200 // requires custom type checking. These will be handled by
7201 // CheckBuiltinFunctionCall below just after creation of the call expression.
7202 const FunctionType *FuncT = nullptr;
7203 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7204 retry:
7205 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7206 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7207 // have type pointer to function".
7208 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7209 if (!FuncT)
7210 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7211 << Fn->getType() << Fn->getSourceRange());
7212 } else if (const BlockPointerType *BPT =
7213 Fn->getType()->getAs<BlockPointerType>()) {
7214 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7215 } else {
7216 // Handle calls to expressions of unknown-any type.
7217 if (Fn->getType() == Context.UnknownAnyTy) {
7218 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7219 if (rewrite.isInvalid())
7220 return ExprError();
7221 Fn = rewrite.get();
7222 goto retry;
7223 }
7224
7225 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7226 << Fn->getType() << Fn->getSourceRange());
7227 }
7228 }
7229
7230 // Get the number of parameters in the function prototype, if any.
7231 // We will allocate space for max(Args.size(), NumParams) arguments
7232 // in the call expression.
7233 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7234 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7235
7236 CallExpr *TheCall;
7237 if (Config) {
7238 assert(UsesADL == ADLCallKind::NotADL &&
7239 "CUDAKernelCallExpr should not use ADL");
7240 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7241 Args, ResultTy, VK_PRValue, RParenLoc,
7242 CurFPFeatureOverrides(), NumParams);
7243 } else {
7244 TheCall =
7245 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7246 CurFPFeatureOverrides(), NumParams, UsesADL);
7247 }
7248
7249 // Bail out early if calling a builtin with custom type checking.
7250 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7251 // For HLSL builtin aliases, the call was resolved via overload resolution
7252 // which may have selected a conversion sequence (e.g., vector-to-scalar
7253 // truncation). Convert arguments to match the declared prototype before
7254 // the custom type checker runs, otherwise the builtin will operate on
7255 // the unconverted argument types.
7256 if (getLangOpts().HLSL && FDecl && FDecl->hasAttr<BuiltinAliasAttr>()) {
7257 if (const auto *P = FDecl->getType()->getAs<FunctionProtoType>()) {
7258 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, P, Args, RParenLoc,
7259 IsExecConfig))
7260 return ExprError();
7261 }
7262 }
7263 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7264 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
7265 E = CheckForImmediateInvocation(E, FDecl);
7266 return E;
7267 }
7268
7269 if (getLangOpts().CUDA) {
7270 if (Config) {
7271 // CUDA: Kernel calls must be to global functions
7272 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7273 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7274 << FDecl << Fn->getSourceRange());
7275
7276 // CUDA: Kernel function must have 'void' return type
7277 if (!FuncT->getReturnType()->isVoidType() &&
7278 !FuncT->getReturnType()->getAs<AutoType>() &&
7280 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7281 << Fn->getType() << Fn->getSourceRange());
7282 } else {
7283 // CUDA: Calls to global functions must be configured
7284 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7285 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7286 << FDecl << Fn->getSourceRange());
7287 }
7288 }
7289
7290 // Check for a valid return type
7291 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7292 FDecl))
7293 return ExprError();
7294
7295 // We know the result type of the call, set it.
7296 TheCall->setType(FuncT->getCallResultType(Context));
7298
7299 // WebAssembly tables can't be used as arguments.
7300 if (Context.getTargetInfo().getTriple().isWasm()) {
7301 for (const Expr *Arg : Args) {
7302 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7303 return ExprError(Diag(Arg->getExprLoc(),
7304 diag::err_wasm_table_as_function_parameter));
7305 }
7306 }
7307 }
7308
7309 // Check read_image{i|ui} sampler argument before ConvertArgumentsForCall
7310 // replaces sampler DeclRefExprs with their integer initializers.
7311 if (getLangOpts().OpenCL && FDecl) {
7312 OpenCL().checkBuiltinReadImage(FDecl, TheCall);
7313 }
7314
7315 if (Proto) {
7316 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7317 IsExecConfig))
7318 return ExprError();
7319 } else {
7320 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7321
7322 if (FDecl) {
7323 // Check if we have too few/too many template arguments, based
7324 // on our knowledge of the function definition.
7325 const FunctionDecl *Def = nullptr;
7326 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7327 Proto = Def->getType()->getAs<FunctionProtoType>();
7328 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7329 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7330 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7331 }
7332
7333 // If the function we're calling isn't a function prototype, but we have
7334 // a function prototype from a prior declaratiom, use that prototype.
7335 if (!FDecl->hasPrototype())
7336 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7337 }
7338
7339 // If we still haven't found a prototype to use but there are arguments to
7340 // the call, diagnose this as calling a function without a prototype.
7341 // However, if we found a function declaration, check to see if
7342 // -Wdeprecated-non-prototype was disabled where the function was declared.
7343 // If so, we will silence the diagnostic here on the assumption that this
7344 // interface is intentional and the user knows what they're doing. We will
7345 // also silence the diagnostic if there is a function declaration but it
7346 // was implicitly defined (the user already gets diagnostics about the
7347 // creation of the implicit function declaration, so the additional warning
7348 // is not helpful).
7349 if (!Proto && !Args.empty() &&
7350 (!FDecl || (!FDecl->isImplicit() &&
7351 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7352 FDecl->getLocation()))))
7353 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7354 << (FDecl != nullptr) << FDecl;
7355
7356 // Promote the arguments (C99 6.5.2.2p6).
7357 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7358 Expr *Arg = Args[i];
7359
7360 if (Proto && i < Proto->getNumParams()) {
7362 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7363 ExprResult ArgE =
7365 if (ArgE.isInvalid())
7366 return true;
7367
7368 Arg = ArgE.getAs<Expr>();
7369
7370 } else {
7372
7373 if (ArgE.isInvalid())
7374 return true;
7375
7376 Arg = ArgE.getAs<Expr>();
7377 }
7378
7379 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7380 diag::err_call_incomplete_argument, Arg))
7381 return ExprError();
7382
7383 TheCall->setArg(i, Arg);
7384 }
7385 TheCall->computeDependence();
7386 }
7387
7388 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7389 if (Method->isImplicitObjectMemberFunction())
7390 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7391 << Fn->getSourceRange() << 0);
7392
7393 // Check for sentinels
7394 if (NDecl)
7395 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7396
7397 // Warn for unions passing across security boundary (CMSE).
7398 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7399 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7400 if (const auto *RT =
7401 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7402 if (RT->getDecl()->isOrContainsUnion())
7403 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7404 << 0 << i;
7405 }
7406 }
7407 }
7408
7409 // Do special checking on direct calls to functions.
7410 if (FDecl) {
7411 if (CheckFunctionCall(FDecl, TheCall, Proto))
7412 return ExprError();
7413
7414 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7415 checkFortifiedLibcArgument(FDecl, TheCall);
7416
7417 if (BuiltinID)
7418 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7419 } else if (NDecl) {
7420 if (CheckPointerCall(NDecl, TheCall, Proto))
7421 return ExprError();
7422 } else {
7423 if (CheckOtherCall(TheCall, Proto))
7424 return ExprError();
7425 }
7426
7427 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7428}
7429
7432 SourceLocation RParenLoc, Expr *InitExpr) {
7433 assert(Ty && "ActOnCompoundLiteral(): missing type");
7434 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7435
7436 TypeSourceInfo *TInfo;
7437 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7438 if (!TInfo)
7439 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7440
7441 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7442}
7443
7446 SourceLocation RParenLoc, Expr *LiteralExpr) {
7447 QualType literalType = TInfo->getType();
7448
7449 if (literalType->isArrayType()) {
7451 LParenLoc, Context.getBaseElementType(literalType),
7452 diag::err_array_incomplete_or_sizeless_type,
7453 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7454 return ExprError();
7455 if (literalType->isVariableArrayType()) {
7456 // C23 6.7.10p4: An entity of variable length array type shall not be
7457 // initialized except by an empty initializer.
7458 //
7459 // The C extension warnings are issued from ParseBraceInitializer() and
7460 // do not need to be issued here. However, we continue to issue an error
7461 // in the case there are initializers or we are compiling C++. We allow
7462 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7463 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7464 // FIXME: should we allow this construct in C++ when it makes sense to do
7465 // so?
7466 //
7467 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7468 // shall specify an object type or an array of unknown size, but not a
7469 // variable length array type. This seems odd, as it allows 'int a[size] =
7470 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7471 // says, this is what's implemented here for C (except for the extension
7472 // that permits constant foldable size arrays)
7473
7474 auto diagID = LangOpts.CPlusPlus
7475 ? diag::err_variable_object_no_init
7476 : diag::err_compound_literal_with_vla_type;
7477 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7478 diagID))
7479 return ExprError();
7480 }
7481 } else if (!literalType->isDependentType() &&
7482 RequireCompleteType(LParenLoc, literalType,
7483 diag::err_typecheck_decl_incomplete_type,
7484 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7485 return ExprError();
7486
7487 InitializedEntity Entity
7491 SourceRange(LParenLoc, RParenLoc),
7492 /*InitList=*/true);
7493 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7494 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7495 &literalType);
7496 if (Result.isInvalid())
7497 return ExprError();
7498 LiteralExpr = Result.get();
7499
7500 // We treat the compound literal as being at file scope if it's not in a
7501 // function or method body, or within the function's prototype scope. This
7502 // means the following compound literal is not at file scope:
7503 // void func(char *para[(int [1]){ 0 }[0]);
7504 const Scope *S = getCurScope();
7505 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7506 !S->isInCFunctionScope() &&
7507 (!S || !S->isFunctionPrototypeScope());
7508
7509 // In C, compound literals are l-values for some reason.
7510 // For GCC compatibility, in C++, file-scope array compound literals with
7511 // constant initializers are also l-values, and compound literals are
7512 // otherwise prvalues.
7513 //
7514 // (GCC also treats C++ list-initialized file-scope array prvalues with
7515 // constant initializers as l-values, but that's non-conforming, so we don't
7516 // follow it there.)
7517 //
7518 // FIXME: It would be better to handle the lvalue cases as materializing and
7519 // lifetime-extending a temporary object, but our materialized temporaries
7520 // representation only supports lifetime extension from a variable, not "out
7521 // of thin air".
7522 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7523 // is bound to the result of applying array-to-pointer decay to the compound
7524 // literal.
7525 // FIXME: GCC supports compound literals of reference type, which should
7526 // obviously have a value kind derived from the kind of reference involved.
7528 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7529 ? VK_PRValue
7530 : VK_LValue;
7531
7532 // C99 6.5.2.5
7533 // "If the compound literal occurs outside the body of a function, the
7534 // initializer list shall consist of constant expressions."
7535 if (IsFileScope)
7536 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7537 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7538 Expr *Init = ILE->getInit(i);
7539 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7540 !Init->isConstantInitializer(Context)) {
7541 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7542 << Init->getSourceBitField();
7543 return ExprError();
7544 }
7545
7546 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7547 }
7548
7549 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7550 LiteralExpr, IsFileScope);
7551 if (IsFileScope) {
7552 if (!LiteralExpr->isTypeDependent() &&
7553 !LiteralExpr->isValueDependent() &&
7554 !literalType->isDependentType()) // C99 6.5.2.5p3
7555 if (CheckForConstantInitializer(LiteralExpr))
7556 return ExprError();
7557 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7558 literalType.getAddressSpace() != LangAS::Default) {
7559 // Embedded-C extensions to C99 6.5.2.5:
7560 // "If the compound literal occurs inside the body of a function, the
7561 // type name shall not be qualified by an address-space qualifier."
7562 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7563 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7564 return ExprError();
7565 }
7566
7567 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7568 // Compound literals that have automatic storage duration are destroyed at
7569 // the end of the scope in C; in C++, they're just temporaries.
7570
7571 // Emit diagnostics if it is or contains a C union type that is non-trivial
7572 // to destruct.
7577
7578 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7579 if (literalType.isDestructedType()) {
7580 Cleanup.setExprNeedsCleanups(true);
7581 ExprCleanupObjects.push_back(E);
7583 }
7584 }
7585
7588 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7589 E->getInitializer()->getExprLoc());
7590
7591 return MaybeBindToTemporary(E);
7592}
7593
7596 SourceLocation RBraceLoc) {
7597 // Only produce each kind of designated initialization diagnostic once.
7598 SourceLocation FirstDesignator;
7599 bool DiagnosedArrayDesignator = false;
7600 bool DiagnosedNestedDesignator = false;
7601 bool DiagnosedMixedDesignator = false;
7602
7603 // Check that any designated initializers are syntactically valid in the
7604 // current language mode.
7605 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7606 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7607 if (FirstDesignator.isInvalid())
7608 FirstDesignator = DIE->getBeginLoc();
7609
7610 if (!getLangOpts().CPlusPlus)
7611 break;
7612
7613 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7614 DiagnosedNestedDesignator = true;
7615 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7616 << DIE->getDesignatorsSourceRange();
7617 }
7618
7619 for (auto &Desig : DIE->designators()) {
7620 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7621 DiagnosedArrayDesignator = true;
7622 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7623 << Desig.getSourceRange();
7624 }
7625 }
7626
7627 if (!DiagnosedMixedDesignator &&
7628 !isa<DesignatedInitExpr>(InitArgList[0])) {
7629 DiagnosedMixedDesignator = true;
7630 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7631 << DIE->getSourceRange();
7632 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7633 << InitArgList[0]->getSourceRange();
7634 }
7635 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7636 isa<DesignatedInitExpr>(InitArgList[0])) {
7637 DiagnosedMixedDesignator = true;
7638 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7639 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7640 << DIE->getSourceRange();
7641 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7642 << InitArgList[I]->getSourceRange();
7643 }
7644 }
7645
7646 if (FirstDesignator.isValid()) {
7647 // Only diagnose designated initiaization as a C++20 extension if we didn't
7648 // already diagnose use of (non-C++20) C99 designator syntax.
7649 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7650 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7651 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7652 ? diag::warn_cxx17_compat_designated_init
7653 : diag::ext_cxx_designated_init);
7654 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7655 Diag(FirstDesignator, diag::ext_designated_init);
7656 }
7657 }
7658
7659 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc, /*IsExplicit=*/true);
7660}
7661
7663 MultiExprArg InitArgList,
7664 SourceLocation RBraceLoc, bool IsExplicit) {
7665 // Semantic analysis for initializers is done by ActOnDeclarator() and
7666 // CheckInitializer() - it requires knowledge of the object being initialized.
7667
7668 // Immediately handle non-overload placeholders. Overloads can be
7669 // resolved contextually, but everything else here can't.
7670 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7671 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7672 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7673
7674 // Ignore failures; dropping the entire initializer list because
7675 // of one failure would be terrible for indexing/etc.
7676 if (result.isInvalid()) continue;
7677
7678 InitArgList[I] = result.get();
7679 }
7680 }
7681
7682 InitListExpr *E = new (Context)
7683 InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc, IsExplicit);
7684 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7685 return E;
7686}
7687
7689 assert(E.get()->getType()->isBlockPointerType());
7690 assert(E.get()->isPRValue());
7691
7692 // Only do this in an r-value context.
7693 if (!getLangOpts().ObjCAutoRefCount) return;
7694
7696 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7697 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7698 Cleanup.setExprNeedsCleanups(true);
7699}
7700
7702 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7703 // Also, callers should have filtered out the invalid cases with
7704 // pointers. Everything else should be possible.
7705
7706 QualType SrcTy = Src.get()->getType();
7707 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7708 return CK_NoOp;
7709
7710 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7712 llvm_unreachable("member pointer type in C");
7713
7714 case Type::STK_CPointer:
7717 switch (DestTy->getScalarTypeKind()) {
7718 case Type::STK_CPointer: {
7719 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7720 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7721 if (SrcAS != DestAS)
7722 return CK_AddressSpaceConversion;
7723 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7724 return CK_NoOp;
7725 return CK_BitCast;
7726 }
7728 return (SrcKind == Type::STK_BlockPointer
7729 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7731 if (SrcKind == Type::STK_ObjCObjectPointer)
7732 return CK_BitCast;
7733 if (SrcKind == Type::STK_CPointer)
7734 return CK_CPointerToObjCPointerCast;
7736 return CK_BlockPointerToObjCPointerCast;
7737 case Type::STK_Bool:
7738 return CK_PointerToBoolean;
7739 case Type::STK_Integral:
7740 return CK_PointerToIntegral;
7741 case Type::STK_Floating:
7746 llvm_unreachable("illegal cast from pointer");
7747 }
7748 llvm_unreachable("Should have returned before this");
7749
7751 switch (DestTy->getScalarTypeKind()) {
7753 return CK_FixedPointCast;
7754 case Type::STK_Bool:
7755 return CK_FixedPointToBoolean;
7756 case Type::STK_Integral:
7757 return CK_FixedPointToIntegral;
7758 case Type::STK_Floating:
7759 return CK_FixedPointToFloating;
7762 Diag(Src.get()->getExprLoc(),
7763 diag::err_unimplemented_conversion_with_fixed_point_type)
7764 << DestTy;
7765 return CK_IntegralCast;
7766 case Type::STK_CPointer:
7770 llvm_unreachable("illegal cast to pointer type");
7771 }
7772 llvm_unreachable("Should have returned before this");
7773
7774 case Type::STK_Bool: // casting from bool is like casting from an integer
7775 case Type::STK_Integral:
7776 switch (DestTy->getScalarTypeKind()) {
7777 case Type::STK_CPointer:
7782 return CK_NullToPointer;
7783 return CK_IntegralToPointer;
7784 case Type::STK_Bool:
7785 return CK_IntegralToBoolean;
7786 case Type::STK_Integral:
7787 return CK_IntegralCast;
7788 case Type::STK_Floating:
7789 return CK_IntegralToFloating;
7791 Src = ImpCastExprToType(Src.get(),
7792 DestTy->castAs<ComplexType>()->getElementType(),
7793 CK_IntegralCast);
7794 return CK_IntegralRealToComplex;
7796 Src = ImpCastExprToType(Src.get(),
7797 DestTy->castAs<ComplexType>()->getElementType(),
7798 CK_IntegralToFloating);
7799 return CK_FloatingRealToComplex;
7801 llvm_unreachable("member pointer type in C");
7803 return CK_IntegralToFixedPoint;
7804 }
7805 llvm_unreachable("Should have returned before this");
7806
7807 case Type::STK_Floating:
7808 switch (DestTy->getScalarTypeKind()) {
7809 case Type::STK_Floating:
7810 return CK_FloatingCast;
7811 case Type::STK_Bool:
7812 return CK_FloatingToBoolean;
7813 case Type::STK_Integral:
7814 return CK_FloatingToIntegral;
7816 Src = ImpCastExprToType(Src.get(),
7817 DestTy->castAs<ComplexType>()->getElementType(),
7818 CK_FloatingCast);
7819 return CK_FloatingRealToComplex;
7821 Src = ImpCastExprToType(Src.get(),
7822 DestTy->castAs<ComplexType>()->getElementType(),
7823 CK_FloatingToIntegral);
7824 return CK_IntegralRealToComplex;
7825 case Type::STK_CPointer:
7828 llvm_unreachable("valid float->pointer cast?");
7830 llvm_unreachable("member pointer type in C");
7832 return CK_FloatingToFixedPoint;
7833 }
7834 llvm_unreachable("Should have returned before this");
7835
7837 switch (DestTy->getScalarTypeKind()) {
7839 return CK_FloatingComplexCast;
7841 return CK_FloatingComplexToIntegralComplex;
7842 case Type::STK_Floating: {
7843 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7844 if (Context.hasSameType(ET, DestTy))
7845 return CK_FloatingComplexToReal;
7846 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7847 return CK_FloatingCast;
7848 }
7849 case Type::STK_Bool:
7850 return CK_FloatingComplexToBoolean;
7851 case Type::STK_Integral:
7852 Src = ImpCastExprToType(Src.get(),
7853 SrcTy->castAs<ComplexType>()->getElementType(),
7854 CK_FloatingComplexToReal);
7855 return CK_FloatingToIntegral;
7856 case Type::STK_CPointer:
7859 llvm_unreachable("valid complex float->pointer cast?");
7861 llvm_unreachable("member pointer type in C");
7863 Diag(Src.get()->getExprLoc(),
7864 diag::err_unimplemented_conversion_with_fixed_point_type)
7865 << SrcTy;
7866 return CK_IntegralCast;
7867 }
7868 llvm_unreachable("Should have returned before this");
7869
7871 switch (DestTy->getScalarTypeKind()) {
7873 return CK_IntegralComplexToFloatingComplex;
7875 return CK_IntegralComplexCast;
7876 case Type::STK_Integral: {
7877 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7878 if (Context.hasSameType(ET, DestTy))
7879 return CK_IntegralComplexToReal;
7880 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7881 return CK_IntegralCast;
7882 }
7883 case Type::STK_Bool:
7884 return CK_IntegralComplexToBoolean;
7885 case Type::STK_Floating:
7886 Src = ImpCastExprToType(Src.get(),
7887 SrcTy->castAs<ComplexType>()->getElementType(),
7888 CK_IntegralComplexToReal);
7889 return CK_IntegralToFloating;
7890 case Type::STK_CPointer:
7893 llvm_unreachable("valid complex int->pointer cast?");
7895 llvm_unreachable("member pointer type in C");
7897 Diag(Src.get()->getExprLoc(),
7898 diag::err_unimplemented_conversion_with_fixed_point_type)
7899 << SrcTy;
7900 return CK_IntegralCast;
7901 }
7902 llvm_unreachable("Should have returned before this");
7903 }
7904
7905 llvm_unreachable("Unhandled scalar cast");
7906}
7907
7908static bool breakDownVectorType(QualType type, uint64_t &len,
7909 QualType &eltType) {
7910 // Vectors are simple.
7911 if (const VectorType *vecType = type->getAs<VectorType>()) {
7912 len = vecType->getNumElements();
7913 eltType = vecType->getElementType();
7914 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7915 return true;
7916 }
7917
7918 // We allow lax conversion to and from non-vector types, but only if
7919 // they're real types (i.e. non-complex, non-pointer scalar types).
7920 if (!type->isRealType()) return false;
7921
7922 len = 1;
7923 eltType = type;
7924 return true;
7925}
7926
7928 assert(srcTy->isVectorType() || destTy->isVectorType());
7929
7930 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7931 if (!FirstType->isSVESizelessBuiltinType())
7932 return false;
7933
7934 const auto *VecTy = SecondType->getAs<VectorType>();
7935 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7936 };
7937
7938 return ValidScalableConversion(srcTy, destTy) ||
7939 ValidScalableConversion(destTy, srcTy);
7940}
7941
7943 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7944 return false;
7945
7946 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7947 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7948
7949 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7950 matSrcType->getNumColumns() == matDestType->getNumColumns();
7951}
7952
7954 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7955
7956 uint64_t SrcLen, DestLen;
7957 QualType SrcEltTy, DestEltTy;
7958 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7959 return false;
7960 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7961 return false;
7962
7963 // ASTContext::getTypeSize will return the size rounded up to a
7964 // power of 2, so instead of using that, we need to use the raw
7965 // element size multiplied by the element count.
7966 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7967 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7968
7969 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7970}
7971
7973 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7974 "expected at least one type to be a vector here");
7975
7976 bool IsSrcTyAltivec =
7977 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7979 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7981 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7983
7984 bool IsDestTyAltivec = DestTy->isVectorType() &&
7985 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7987 (DestTy->castAs<VectorType>()->getVectorKind() ==
7989 (DestTy->castAs<VectorType>()->getVectorKind() ==
7991
7992 return (IsSrcTyAltivec || IsDestTyAltivec);
7993}
7994
7996 assert(destTy->isVectorType() || srcTy->isVectorType());
7997
7998 // Disallow lax conversions between scalars and ExtVectors (these
7999 // conversions are allowed for other vector types because common headers
8000 // depend on them). Most scalar OP ExtVector cases are handled by the
8001 // splat path anyway, which does what we want (convert, not bitcast).
8002 // What this rules out for ExtVectors is crazy things like char4*float.
8003 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8004 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8005
8006 return areVectorTypesSameSize(srcTy, destTy);
8007}
8008
8010 assert(destTy->isVectorType() || srcTy->isVectorType());
8011
8012 switch (Context.getLangOpts().getLaxVectorConversions()) {
8014 return false;
8015
8017 if (!srcTy->isIntegralOrEnumerationType()) {
8018 auto *Vec = srcTy->getAs<VectorType>();
8019 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8020 return false;
8021 }
8022 if (!destTy->isIntegralOrEnumerationType()) {
8023 auto *Vec = destTy->getAs<VectorType>();
8024 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8025 return false;
8026 }
8027 // OK, integer (vector) -> integer (vector) bitcast.
8028 break;
8029
8031 break;
8032 }
8033
8034 return areLaxCompatibleVectorTypes(srcTy, destTy);
8035}
8036
8038 CastKind &Kind) {
8039 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8040 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
8041 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
8042 << DestTy << SrcTy << R;
8043 }
8044 } else if (SrcTy->isMatrixType()) {
8045 return Diag(R.getBegin(),
8046 diag::err_invalid_conversion_between_matrix_and_type)
8047 << SrcTy << DestTy << R;
8048 } else if (DestTy->isMatrixType()) {
8049 return Diag(R.getBegin(),
8050 diag::err_invalid_conversion_between_matrix_and_type)
8051 << DestTy << SrcTy << R;
8052 }
8053
8054 Kind = CK_MatrixCast;
8055 return false;
8056}
8057
8059 CastKind &Kind) {
8060 assert(VectorTy->isVectorType() && "Not a vector type!");
8061
8062 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
8063 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8064 return Diag(R.getBegin(),
8065 Ty->isVectorType() ?
8066 diag::err_invalid_conversion_between_vectors :
8067 diag::err_invalid_conversion_between_vector_and_integer)
8068 << VectorTy << Ty << R;
8069 } else
8070 return Diag(R.getBegin(),
8071 diag::err_invalid_conversion_between_vector_and_scalar)
8072 << VectorTy << Ty << R;
8073
8074 Kind = CK_BitCast;
8075 return false;
8076}
8077
8079 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8080
8081 if (DestElemTy == SplattedExpr->getType())
8082 return SplattedExpr;
8083
8084 assert(DestElemTy->isFloatingType() ||
8085 DestElemTy->isIntegralOrEnumerationType());
8086
8087 CastKind CK;
8088 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8089 // OpenCL requires that we convert `true` boolean expressions to -1, but
8090 // only when splatting vectors.
8091 if (DestElemTy->isFloatingType()) {
8092 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8093 // in two steps: boolean to signed integral, then to floating.
8094 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
8095 CK_BooleanToSignedIntegral);
8096 SplattedExpr = CastExprRes.get();
8097 CK = CK_IntegralToFloating;
8098 } else {
8099 CK = CK_BooleanToSignedIntegral;
8100 }
8101 } else {
8102 ExprResult CastExprRes = SplattedExpr;
8103 CK = PrepareScalarCast(CastExprRes, DestElemTy);
8104 if (CastExprRes.isInvalid())
8105 return ExprError();
8106 SplattedExpr = CastExprRes.get();
8107 }
8108 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8109}
8110
8112 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8113
8114 if (DestElemTy == SplattedExpr->getType())
8115 return SplattedExpr;
8116
8117 assert(DestElemTy->isFloatingType() ||
8118 DestElemTy->isIntegralOrEnumerationType());
8119
8120 ExprResult CastExprRes = SplattedExpr;
8121 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
8122 if (CastExprRes.isInvalid())
8123 return ExprError();
8124 SplattedExpr = CastExprRes.get();
8125
8126 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8127}
8128
8130 Expr *CastExpr, CastKind &Kind) {
8131 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8132
8133 QualType SrcTy = CastExpr->getType();
8134
8135 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8136 // an ExtVectorType.
8137 // In OpenCL, casts between vectors of different types are not allowed.
8138 // (See OpenCL 6.2).
8139 if (SrcTy->isVectorType()) {
8140 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8141 (getLangOpts().OpenCL &&
8142 !Context.hasSameUnqualifiedType(DestTy, SrcTy) &&
8143 !Context.areCompatibleVectorTypes(DestTy, SrcTy))) {
8144 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8145 << DestTy << SrcTy << R;
8146 return ExprError();
8147 }
8148 Kind = CK_BitCast;
8149 return CastExpr;
8150 }
8151
8152 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8153 // conversion will take place first from scalar to elt type, and then
8154 // splat from elt type to vector.
8155 if (SrcTy->isPointerType())
8156 return Diag(R.getBegin(),
8157 diag::err_invalid_conversion_between_vector_and_scalar)
8158 << DestTy << SrcTy << R;
8159
8160 Kind = CK_VectorSplat;
8161 return prepareVectorSplat(DestTy, CastExpr);
8162}
8163
8164/// Check that a call to alloc_size function specifies sufficient space for the
8165/// destination type.
8166static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8167 const Expr *E) {
8168 QualType SourceType = E->getType();
8169 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8170 DestType == SourceType)
8171 return;
8172
8173 const auto *CE = dyn_cast<CallExpr>(E->IgnoreParenCasts());
8174 if (!CE)
8175 return;
8176
8177 // Find the total size allocated by the function call.
8178 if (!CE->getCalleeAllocSizeAttr())
8179 return;
8180 std::optional<llvm::APInt> AllocSize =
8181 CE->evaluateBytesReturnedByAllocSizeCall(S.Context);
8182 // Allocations of size zero are permitted as a special case. They are usually
8183 // done intentionally.
8184 if (!AllocSize || AllocSize->isZero())
8185 return;
8186 auto Size = CharUnits::fromQuantity(AllocSize->getZExtValue());
8187
8188 QualType TargetType = DestType->getPointeeType();
8189 // Find the destination size. As a special case function types have size of
8190 // one byte to match the sizeof operator behavior.
8191 auto LhsSize = TargetType->isFunctionType()
8192 ? CharUnits::One()
8193 : S.Context.getTypeSizeInCharsIfKnown(TargetType);
8194 if (LhsSize && Size < LhsSize)
8195 S.Diag(E->getExprLoc(), diag::warn_alloc_size)
8196 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8197}
8198
8201 Declarator &D, ParsedType &Ty,
8202 SourceLocation RParenLoc, Expr *CastExpr) {
8203 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8204 "ActOnCastExpr(): missing type or expr");
8205
8207 if (D.isInvalidType())
8208 return ExprError();
8209
8210 if (getLangOpts().CPlusPlus) {
8211 // Check that there are no default arguments (C++ only).
8213 }
8214
8216
8217 QualType castType = castTInfo->getType();
8218 Ty = CreateParsedType(castType, castTInfo);
8219
8220 bool isVectorLiteral = false;
8221
8222 // Check for an altivec or OpenCL literal,
8223 // i.e. all the elements are integer constants.
8224 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8225 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8226 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8227 && castType->isVectorType() && (PE || PLE)) {
8228 if (PLE && PLE->getNumExprs() == 0) {
8229 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8230 return ExprError();
8231 }
8232 if (PE || PLE->getNumExprs() == 1) {
8233 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8234 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8235 isVectorLiteral = true;
8236 }
8237 else
8238 isVectorLiteral = true;
8239 }
8240
8241 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8242 // then handle it as such.
8243 if (isVectorLiteral)
8244 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8245
8246 // If the Expr being casted is a ParenListExpr, handle it specially.
8247 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8248 // sequence of BinOp comma operators.
8251 if (Result.isInvalid()) return ExprError();
8252 CastExpr = Result.get();
8253 }
8254
8255 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8256 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8257
8259
8261
8263
8264 CheckSufficientAllocSize(*this, castType, CastExpr);
8265
8266 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8267}
8268
8270 SourceLocation RParenLoc, Expr *E,
8271 TypeSourceInfo *TInfo) {
8272 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8273 "Expected paren or paren list expression");
8274
8275 Expr **exprs;
8276 unsigned numExprs;
8277 Expr *subExpr;
8278 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8279 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8280 LiteralLParenLoc = PE->getLParenLoc();
8281 LiteralRParenLoc = PE->getRParenLoc();
8282 exprs = PE->getExprs();
8283 numExprs = PE->getNumExprs();
8284 } else { // isa<ParenExpr> by assertion at function entrance
8285 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8286 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8287 subExpr = cast<ParenExpr>(E)->getSubExpr();
8288 exprs = &subExpr;
8289 numExprs = 1;
8290 }
8291
8292 QualType Ty = TInfo->getType();
8293 assert(Ty->isVectorType() && "Expected vector type");
8294
8295 SmallVector<Expr *, 8> initExprs;
8296 const VectorType *VTy = Ty->castAs<VectorType>();
8297 unsigned numElems = VTy->getNumElements();
8298
8299 // '(...)' form of vector initialization in AltiVec: the number of
8300 // initializers must be one or must match the size of the vector.
8301 // If a single value is specified in the initializer then it will be
8302 // replicated to all the components of the vector
8304 VTy->getElementType()))
8305 return ExprError();
8307 // The number of initializers must be one or must match the size of the
8308 // vector. If a single value is specified in the initializer then it will
8309 // be replicated to all the components of the vector
8310 if (numExprs == 1) {
8311 QualType ElemTy = VTy->getElementType();
8312 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8313 if (Literal.isInvalid())
8314 return ExprError();
8315 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8316 PrepareScalarCast(Literal, ElemTy));
8317 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8318 }
8319 else if (numExprs < numElems) {
8320 Diag(E->getExprLoc(),
8321 diag::err_incorrect_number_of_vector_initializers);
8322 return ExprError();
8323 }
8324 else
8325 initExprs.append(exprs, exprs + numExprs);
8326 }
8327 else {
8328 // For OpenCL, when the number of initializers is a single value,
8329 // it will be replicated to all components of the vector.
8331 numExprs == 1) {
8332 QualType SrcTy = exprs[0]->getType();
8333 if (!SrcTy->isArithmeticType()) {
8334 Diag(exprs[0]->getBeginLoc(), diag::err_typecheck_convert_incompatible)
8335 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8336 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8337 return ExprError();
8338 }
8339 QualType ElemTy = VTy->getElementType();
8340 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8341 if (Literal.isInvalid())
8342 return ExprError();
8343 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8344 PrepareScalarCast(Literal, ElemTy));
8345 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8346 }
8347
8348 initExprs.append(exprs, exprs + numExprs);
8349 }
8350 // FIXME: This means that pretty-printing the final AST will produce curly
8351 // braces instead of the original commas.
8352 InitListExpr *initE =
8353 new (Context) InitListExpr(Context, LiteralLParenLoc, initExprs,
8354 LiteralRParenLoc, /*isExplicit=*/false);
8355 initE->setType(Ty);
8356 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8357}
8358
8361 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8362 if (!E)
8363 return OrigExpr;
8364
8365 ExprResult Result(E->getExpr(0));
8366
8367 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8368 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8369 E->getExpr(i));
8370
8371 if (Result.isInvalid()) return ExprError();
8372
8373 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8374}
8375
8381
8383 unsigned NumUserSpecifiedExprs,
8384 SourceLocation InitLoc,
8385 SourceLocation LParenLoc,
8386 SourceLocation RParenLoc) {
8387 return CXXParenListInitExpr::Create(Context, Args, T, NumUserSpecifiedExprs,
8388 InitLoc, LParenLoc, RParenLoc);
8389}
8390
8391bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8392 SourceLocation QuestionLoc) {
8393 const Expr *NullExpr = LHSExpr;
8394 const Expr *NonPointerExpr = RHSExpr;
8398
8399 if (NullKind == Expr::NPCK_NotNull) {
8400 NullExpr = RHSExpr;
8401 NonPointerExpr = LHSExpr;
8402 NullKind =
8405 }
8406
8407 if (NullKind == Expr::NPCK_NotNull)
8408 return false;
8409
8410 if (NullKind == Expr::NPCK_ZeroExpression)
8411 return false;
8412
8413 if (NullKind == Expr::NPCK_ZeroLiteral) {
8414 // In this case, check to make sure that we got here from a "NULL"
8415 // string in the source code.
8416 NullExpr = NullExpr->IgnoreParenImpCasts();
8417 SourceLocation loc = NullExpr->getExprLoc();
8418 if (!findMacroSpelling(loc, "NULL"))
8419 return false;
8420 }
8421
8422 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8423 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8424 << NonPointerExpr->getType() << DiagType
8425 << NonPointerExpr->getSourceRange();
8426 return true;
8427}
8428
8429/// Return false if the condition expression is valid, true otherwise.
8430static bool checkCondition(Sema &S, const Expr *Cond,
8431 SourceLocation QuestionLoc) {
8432 QualType CondTy = Cond->getType();
8433
8434 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8435 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8436 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8437 << CondTy << Cond->getSourceRange();
8438 return true;
8439 }
8440
8441 // C99 6.5.15p2
8442 if (CondTy->isScalarType()) return false;
8443
8444 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8445 << CondTy << Cond->getSourceRange();
8446 return true;
8447}
8448
8449/// Return false if the NullExpr can be promoted to PointerTy,
8450/// true otherwise.
8452 QualType PointerTy) {
8453 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8454 !NullExpr.get()->isNullPointerConstant(S.Context,
8456 return true;
8457
8458 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8459 return false;
8460}
8461
8462/// Checks compatibility between two pointers and return the resulting
8463/// type.
8465 ExprResult &RHS,
8466 SourceLocation Loc) {
8467 QualType LHSTy = LHS.get()->getType();
8468 QualType RHSTy = RHS.get()->getType();
8469
8470 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8471 // Two identical pointers types are always compatible.
8472 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8473 }
8474
8475 QualType lhptee, rhptee;
8476
8477 // Get the pointee types.
8478 bool IsBlockPointer = false;
8479 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8480 lhptee = LHSBTy->getPointeeType();
8481 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8482 IsBlockPointer = true;
8483 } else {
8484 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8485 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8486 }
8487
8488 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8489 // differently qualified versions of compatible types, the result type is
8490 // a pointer to an appropriately qualified version of the composite
8491 // type.
8492
8493 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8494 // clause doesn't make sense for our extensions. E.g. address space 2 should
8495 // be incompatible with address space 3: they may live on different devices or
8496 // anything.
8497 Qualifiers lhQual = lhptee.getQualifiers();
8498 Qualifiers rhQual = rhptee.getQualifiers();
8499
8500 LangAS ResultAddrSpace = LangAS::Default;
8501 LangAS LAddrSpace = lhQual.getAddressSpace();
8502 LangAS RAddrSpace = rhQual.getAddressSpace();
8503
8504 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8505 // spaces is disallowed.
8506 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8507 ResultAddrSpace = LAddrSpace;
8508 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8509 ResultAddrSpace = RAddrSpace;
8510 else {
8511 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8512 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8513 << RHS.get()->getSourceRange();
8514 return QualType();
8515 }
8516
8517 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8518 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8519 lhQual.removeCVRQualifiers();
8520 rhQual.removeCVRQualifiers();
8521
8522 if (!lhQual.getPointerAuth().isEquivalent(rhQual.getPointerAuth())) {
8523 S.Diag(Loc, diag::err_typecheck_cond_incompatible_ptrauth)
8524 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8525 << RHS.get()->getSourceRange();
8526 return QualType();
8527 }
8528
8529 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8530 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8531 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8532 // qual types are compatible iff
8533 // * corresponded types are compatible
8534 // * CVR qualifiers are equal
8535 // * address spaces are equal
8536 // Thus for conditional operator we merge CVR and address space unqualified
8537 // pointees and if there is a composite type we return a pointer to it with
8538 // merged qualifiers.
8539 LHSCastKind =
8540 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8541 RHSCastKind =
8542 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8543 lhQual.removeAddressSpace();
8544 rhQual.removeAddressSpace();
8545
8546 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8547 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8548
8549 QualType CompositeTy = S.Context.mergeTypes(
8550 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8551 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8552
8553 if (CompositeTy.isNull()) {
8554 // In this situation, we assume void* type. No especially good
8555 // reason, but this is what gcc does, and we do have to pick
8556 // to get a consistent AST.
8557 QualType incompatTy;
8558 incompatTy = S.Context.getPointerType(
8559 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8560 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8561 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8562
8563 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8564 // for casts between types with incompatible address space qualifiers.
8565 // For the following code the compiler produces casts between global and
8566 // local address spaces of the corresponded innermost pointees:
8567 // local int *global *a;
8568 // global int *global *b;
8569 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8570 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8571 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8572 << RHS.get()->getSourceRange();
8573
8574 return incompatTy;
8575 }
8576
8577 // The pointer types are compatible.
8578 // In case of OpenCL ResultTy should have the address space qualifier
8579 // which is a superset of address spaces of both the 2nd and the 3rd
8580 // operands of the conditional operator.
8581 QualType ResultTy = [&, ResultAddrSpace]() {
8582 if (S.getLangOpts().OpenCL) {
8583 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8584 CompositeQuals.setAddressSpace(ResultAddrSpace);
8585 return S.Context
8586 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8587 .withCVRQualifiers(MergedCVRQual);
8588 }
8589 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8590 }();
8591 if (IsBlockPointer)
8592 ResultTy = S.Context.getBlockPointerType(ResultTy);
8593 else
8594 ResultTy = S.Context.getPointerType(ResultTy);
8595
8596 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8597 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8598 return ResultTy;
8599}
8600
8601/// Return the resulting type when the operands are both block pointers.
8603 ExprResult &LHS,
8604 ExprResult &RHS,
8605 SourceLocation Loc) {
8606 QualType LHSTy = LHS.get()->getType();
8607 QualType RHSTy = RHS.get()->getType();
8608
8609 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8610 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8612 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8613 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8614 return destType;
8615 }
8616 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8617 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8618 << RHS.get()->getSourceRange();
8619 return QualType();
8620 }
8621
8622 // We have 2 block pointer types.
8623 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8624}
8625
8626/// Return the resulting type when the operands are both pointers.
8627static QualType
8629 ExprResult &RHS,
8630 SourceLocation Loc) {
8631 // get the pointer types
8632 QualType LHSTy = LHS.get()->getType();
8633 QualType RHSTy = RHS.get()->getType();
8634
8635 // get the "pointed to" types
8636 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8637 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8638
8639 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8640 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8641 // Figure out necessary qualifiers (C99 6.5.15p6)
8642 QualType destPointee
8643 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8644 QualType destType = S.Context.getPointerType(destPointee);
8645 // Add qualifiers if necessary.
8646 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8647 // Promote to void*.
8648 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8649 return destType;
8650 }
8651 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8652 QualType destPointee
8653 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8654 QualType destType = S.Context.getPointerType(destPointee);
8655 // Add qualifiers if necessary.
8656 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8657 // Promote to void*.
8658 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8659 return destType;
8660 }
8661
8662 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8663}
8664
8665/// Return false if the first expression is not an integer and the second
8666/// expression is not a pointer, true otherwise.
8668 Expr* PointerExpr, SourceLocation Loc,
8669 bool IsIntFirstExpr) {
8670 if (!PointerExpr->getType()->isPointerType() ||
8671 !Int.get()->getType()->isIntegerType())
8672 return false;
8673
8674 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8675 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8676
8677 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8678 << Expr1->getType() << Expr2->getType()
8679 << Expr1->getSourceRange() << Expr2->getSourceRange();
8680 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8681 CK_IntegralToPointer);
8682 return true;
8683}
8684
8685/// Simple conversion between integer and floating point types.
8686///
8687/// Used when handling the OpenCL conditional operator where the
8688/// condition is a vector while the other operands are scalar.
8689///
8690/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8691/// types are either integer or floating type. Between the two
8692/// operands, the type with the higher rank is defined as the "result
8693/// type". The other operand needs to be promoted to the same type. No
8694/// other type promotion is allowed. We cannot use
8695/// UsualArithmeticConversions() for this purpose, since it always
8696/// promotes promotable types.
8698 ExprResult &RHS,
8699 SourceLocation QuestionLoc) {
8701 if (LHS.isInvalid())
8702 return QualType();
8704 if (RHS.isInvalid())
8705 return QualType();
8706
8707 // For conversion purposes, we ignore any qualifiers.
8708 // For example, "const float" and "float" are equivalent.
8709 QualType LHSType =
8711 QualType RHSType =
8713
8714 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8715 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8716 << LHSType << LHS.get()->getSourceRange();
8717 return QualType();
8718 }
8719
8720 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8721 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8722 << RHSType << RHS.get()->getSourceRange();
8723 return QualType();
8724 }
8725
8726 // If both types are identical, no conversion is needed.
8727 if (LHSType == RHSType)
8728 return LHSType;
8729
8730 // Now handle "real" floating types (i.e. float, double, long double).
8731 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8732 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8733 /*IsCompAssign = */ false);
8734
8735 // Finally, we have two differing integer types.
8737 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8738}
8739
8740/// Convert scalar operands to a vector that matches the
8741/// condition in length.
8742///
8743/// Used when handling the OpenCL conditional operator where the
8744/// condition is a vector while the other operands are scalar.
8745///
8746/// We first compute the "result type" for the scalar operands
8747/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8748/// into a vector of that type where the length matches the condition
8749/// vector type. s6.11.6 requires that the element types of the result
8750/// and the condition must have the same number of bits.
8751static QualType
8753 QualType CondTy, SourceLocation QuestionLoc) {
8754 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8755 if (ResTy.isNull()) return QualType();
8756
8757 const VectorType *CV = CondTy->getAs<VectorType>();
8758 assert(CV);
8759
8760 // Determine the vector result type
8761 unsigned NumElements = CV->getNumElements();
8762 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8763
8764 // Ensure that all types have the same number of bits
8766 != S.Context.getTypeSize(ResTy)) {
8767 // Since VectorTy is created internally, it does not pretty print
8768 // with an OpenCL name. Instead, we just print a description.
8769 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8770 SmallString<64> Str;
8771 llvm::raw_svector_ostream OS(Str);
8772 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8773 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8774 << CondTy << OS.str();
8775 return QualType();
8776 }
8777
8778 // Convert operands to the vector result type
8779 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8780 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8781
8782 return VectorTy;
8783}
8784
8785/// Return false if this is a valid OpenCL condition vector
8787 SourceLocation QuestionLoc) {
8788 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8789 // integral type.
8790 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8791 assert(CondTy);
8792 QualType EleTy = CondTy->getElementType();
8793 if (EleTy->isIntegerType()) return false;
8794
8795 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8796 << Cond->getType() << Cond->getSourceRange();
8797 return true;
8798}
8799
8800/// Return false if the vector condition type and the vector
8801/// result type are compatible.
8802///
8803/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8804/// number of elements, and their element types have the same number
8805/// of bits.
8806static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8807 SourceLocation QuestionLoc) {
8808 const VectorType *CV = CondTy->getAs<VectorType>();
8809 const VectorType *RV = VecResTy->getAs<VectorType>();
8810 assert(CV && RV);
8811
8812 if (CV->getNumElements() != RV->getNumElements()) {
8813 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8814 << CondTy << VecResTy;
8815 return true;
8816 }
8817
8818 QualType CVE = CV->getElementType();
8819 QualType RVE = RV->getElementType();
8820
8821 // Boolean vectors are permitted outside of OpenCL mode.
8822 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE) &&
8823 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8824 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8825 << CondTy << VecResTy;
8826 return true;
8827 }
8828
8829 return false;
8830}
8831
8832/// Return the resulting type for the conditional operator in
8833/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8834/// s6.3.i) when the condition is a vector type.
8835static QualType
8837 ExprResult &LHS, ExprResult &RHS,
8838 SourceLocation QuestionLoc) {
8840 if (Cond.isInvalid())
8841 return QualType();
8842 QualType CondTy = Cond.get()->getType();
8843
8844 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8845 return QualType();
8846
8847 // If either operand is a vector then find the vector type of the
8848 // result as specified in OpenCL v1.1 s6.3.i.
8849 if (LHS.get()->getType()->isVectorType() ||
8850 RHS.get()->getType()->isVectorType()) {
8851 bool IsBoolVecLang =
8852 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8853 QualType VecResTy =
8854 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8855 /*isCompAssign*/ false,
8856 /*AllowBothBool*/ true,
8857 /*AllowBoolConversions*/ false,
8858 /*AllowBooleanOperation*/ IsBoolVecLang,
8859 /*ReportInvalid*/ true);
8860 if (VecResTy.isNull())
8861 return QualType();
8862 // The result type must match the condition type as specified in
8863 // OpenCL v1.1 s6.11.6.
8864 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8865 return QualType();
8866 return VecResTy;
8867 }
8868
8869 // Both operands are scalar.
8870 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8871}
8872
8873/// Return true if the Expr is block type
8874static bool checkBlockType(Sema &S, const Expr *E) {
8875 if (E->getType()->isBlockPointerType()) {
8876 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8877 return true;
8878 }
8879
8880 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8881 QualType Ty = CE->getCallee()->getType();
8882 if (Ty->isBlockPointerType()) {
8883 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8884 return true;
8885 }
8886 }
8887 return false;
8888}
8889
8890/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8891/// In that case, LHS = cond.
8892/// C99 6.5.15
8895 ExprObjectKind &OK,
8896 SourceLocation QuestionLoc) {
8897
8898 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8899 if (!LHSResult.isUsable()) return QualType();
8900 LHS = LHSResult;
8901
8902 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8903 if (!RHSResult.isUsable()) return QualType();
8904 RHS = RHSResult;
8905
8906 // C++ is sufficiently different to merit its own checker.
8907 if (getLangOpts().CPlusPlus)
8908 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8909
8910 VK = VK_PRValue;
8911 OK = OK_Ordinary;
8912
8913 if (Context.isDependenceAllowed() &&
8914 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8915 RHS.get()->isTypeDependent())) {
8916 assert(!getLangOpts().CPlusPlus);
8917 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8918 RHS.get()->containsErrors()) &&
8919 "should only occur in error-recovery path.");
8920 return Context.DependentTy;
8921 }
8922
8923 // The OpenCL operator with a vector condition is sufficiently
8924 // different to merit its own checker.
8925 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8926 Cond.get()->getType()->isExtVectorType())
8927 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8928
8929 // First, check the condition.
8931 if (Cond.isInvalid())
8932 return QualType();
8933 if (checkCondition(*this, Cond.get(), QuestionLoc))
8934 return QualType();
8935
8936 // Handle vectors.
8937 if (LHS.get()->getType()->isVectorType() ||
8938 RHS.get()->getType()->isVectorType())
8939 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8940 /*AllowBothBool*/ true,
8941 /*AllowBoolConversions*/ false,
8942 /*AllowBooleanOperation*/ false,
8943 /*ReportInvalid*/ true);
8944
8945 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
8947 if (LHS.isInvalid() || RHS.isInvalid())
8948 return QualType();
8949
8950 // WebAssembly tables are not allowed as conditional LHS or RHS.
8951 QualType LHSTy = LHS.get()->getType();
8952 QualType RHSTy = RHS.get()->getType();
8953 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8954 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8955 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8956 return QualType();
8957 }
8958
8959 // Diagnose attempts to convert between __ibm128, __float128 and long double
8960 // where such conversions currently can't be handled.
8961 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8962 Diag(QuestionLoc,
8963 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8964 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8965 return QualType();
8966 }
8967
8968 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8969 // selection operator (?:).
8970 if (getLangOpts().OpenCL &&
8971 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8972 return QualType();
8973 }
8974
8975 // If both operands have arithmetic type, do the usual arithmetic conversions
8976 // to find a common type: C99 6.5.15p3,5.
8977 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8978 // Disallow invalid arithmetic conversions, such as those between bit-
8979 // precise integers types of different sizes, or between a bit-precise
8980 // integer and another type.
8981 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8982 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8983 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8984 << RHS.get()->getSourceRange();
8985 return QualType();
8986 }
8987
8988 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8989 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8990
8991 return ResTy;
8992 }
8993
8994 // If both operands are the same structure or union type, the result is that
8995 // type.
8996 // FIXME: Type of conditional expression must be complete in C mode.
8997 if (LHSTy->isRecordType() &&
8998 Context.hasSameUnqualifiedType(LHSTy, RHSTy)) // C99 6.5.15p3
8999 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
9000 RHSTy.getUnqualifiedType());
9001
9002 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9003 // The following || allows only one side to be void (a GCC-ism).
9004 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9005 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9006 // UsualArithmeticConversions already handled the case where both sides
9007 // are the same type.
9008 } else if (RHSTy->isVoidType()) {
9009 ResTy = RHSTy;
9010 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9011 << RHS.get()->getSourceRange();
9012 } else {
9013 ResTy = LHSTy;
9014 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9015 << LHS.get()->getSourceRange();
9016 }
9017 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
9018 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
9019 return ResTy;
9020 }
9021
9022 // C23 6.5.15p7:
9023 // ... if both the second and third operands have nullptr_t type, the
9024 // result also has that type.
9025 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
9026 return ResTy;
9027
9028 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9029 // the type of the other operand."
9030 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
9031 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
9032
9033 // All objective-c pointer type analysis is done here.
9034 QualType compositeType =
9035 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
9036 if (LHS.isInvalid() || RHS.isInvalid())
9037 return QualType();
9038 if (!compositeType.isNull())
9039 return compositeType;
9040
9041
9042 // Handle block pointer types.
9043 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9044 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
9045 QuestionLoc);
9046
9047 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9048 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9049 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
9050 QuestionLoc);
9051
9052 // GCC compatibility: soften pointer/integer mismatch. Note that
9053 // null pointers have been filtered out by this point.
9054 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
9055 /*IsIntFirstExpr=*/true))
9056 return RHSTy;
9057 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
9058 /*IsIntFirstExpr=*/false))
9059 return LHSTy;
9060
9061 // Emit a better diagnostic if one of the expressions is a null pointer
9062 // constant and the other is not a pointer type. In this case, the user most
9063 // likely forgot to take the address of the other expression.
9064 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
9065 return QualType();
9066
9067 // Finally, if the LHS and RHS types are canonically the same type, we can
9068 // use the common sugared type.
9069 if (Context.hasSameType(LHSTy, RHSTy))
9070 return Context.getCommonSugaredType(LHSTy, RHSTy);
9071
9072 // Otherwise, the operands are not compatible.
9073 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9074 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9075 << RHS.get()->getSourceRange();
9076 return QualType();
9077}
9078
9079/// SuggestParentheses - Emit a note with a fixit hint that wraps
9080/// ParenRange in parentheses.
9082 const PartialDiagnostic &Note,
9083 SourceRange ParenRange) {
9084 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
9085 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9086 EndLoc.isValid()) {
9087 Self.Diag(Loc, Note)
9088 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
9089 << FixItHint::CreateInsertion(EndLoc, ")");
9090 } else {
9091 // We can't display the parentheses, so just show the bare note.
9092 Self.Diag(Loc, Note) << ParenRange;
9093 }
9094}
9095
9097 return BinaryOperator::isAdditiveOp(Opc) ||
9099 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9100 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9101 // not any of the logical operators. Bitwise-xor is commonly used as a
9102 // logical-xor because there is no logical-xor operator. The logical
9103 // operators, including uses of xor, have a high false positive rate for
9104 // precedence warnings.
9105}
9106
9107/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9108/// expression, either using a built-in or overloaded operator,
9109/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9110/// expression.
9111static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9112 const Expr **RHSExprs) {
9113 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9114 E = E->IgnoreImpCasts();
9116 E = E->IgnoreImpCasts();
9117 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9118 E = MTE->getSubExpr();
9119 E = E->IgnoreImpCasts();
9120 }
9121
9122 // Built-in binary operator.
9123 if (const auto *OP = dyn_cast<BinaryOperator>(E);
9124 OP && IsArithmeticOp(OP->getOpcode())) {
9125 *Opcode = OP->getOpcode();
9126 *RHSExprs = OP->getRHS();
9127 return true;
9128 }
9129
9130 // Overloaded operator.
9131 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9132 if (Call->getNumArgs() != 2)
9133 return false;
9134
9135 // Make sure this is really a binary operator that is safe to pass into
9136 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9137 OverloadedOperatorKind OO = Call->getOperator();
9138 if (OO < OO_Plus || OO > OO_Arrow ||
9139 OO == OO_PlusPlus || OO == OO_MinusMinus)
9140 return false;
9141
9143 if (IsArithmeticOp(OpKind)) {
9144 *Opcode = OpKind;
9145 *RHSExprs = Call->getArg(1);
9146 return true;
9147 }
9148 }
9149
9150 return false;
9151}
9152
9153/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9154/// or is a logical expression such as (x==y) which has int type, but is
9155/// commonly interpreted as boolean.
9156static bool ExprLooksBoolean(const Expr *E) {
9157 E = E->IgnoreParenImpCasts();
9158
9159 if (E->getType()->isBooleanType())
9160 return true;
9161 if (const auto *OP = dyn_cast<BinaryOperator>(E))
9162 return OP->isComparisonOp() || OP->isLogicalOp();
9163 if (const auto *OP = dyn_cast<UnaryOperator>(E))
9164 return OP->getOpcode() == UO_LNot;
9165 if (E->getType()->isPointerType())
9166 return true;
9167 // FIXME: What about overloaded operator calls returning "unspecified boolean
9168 // type"s (commonly pointer-to-members)?
9169
9170 return false;
9171}
9172
9173/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9174/// and binary operator are mixed in a way that suggests the programmer assumed
9175/// the conditional operator has higher precedence, for example:
9176/// "int x = a + someBinaryCondition ? 1 : 2".
9178 Expr *Condition, const Expr *LHSExpr,
9179 const Expr *RHSExpr) {
9180 BinaryOperatorKind CondOpcode;
9181 const Expr *CondRHS;
9182
9183 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9184 return;
9185 if (!ExprLooksBoolean(CondRHS))
9186 return;
9187
9188 // The condition is an arithmetic binary expression, with a right-
9189 // hand side that looks boolean, so warn.
9190
9191 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9192 ? diag::warn_precedence_bitwise_conditional
9193 : diag::warn_precedence_conditional;
9194
9195 Self.Diag(OpLoc, DiagID)
9196 << Condition->getSourceRange()
9197 << BinaryOperator::getOpcodeStr(CondOpcode);
9198
9200 Self, OpLoc,
9201 Self.PDiag(diag::note_precedence_silence)
9202 << BinaryOperator::getOpcodeStr(CondOpcode),
9203 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9204
9205 SuggestParentheses(Self, OpLoc,
9206 Self.PDiag(diag::note_precedence_conditional_first),
9207 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9208}
9209
9210/// Compute the nullability of a conditional expression.
9212 QualType LHSTy, QualType RHSTy,
9213 ASTContext &Ctx) {
9214 if (!ResTy->isAnyPointerType())
9215 return ResTy;
9216
9217 auto GetNullability = [](QualType Ty) {
9218 NullabilityKindOrNone Kind = Ty->getNullability();
9219 if (Kind) {
9220 // For our purposes, treat _Nullable_result as _Nullable.
9223 return *Kind;
9224 }
9226 };
9227
9228 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9229 NullabilityKind MergedKind;
9230
9231 // Compute nullability of a binary conditional expression.
9232 if (IsBin) {
9233 if (LHSKind == NullabilityKind::NonNull)
9234 MergedKind = NullabilityKind::NonNull;
9235 else
9236 MergedKind = RHSKind;
9237 // Compute nullability of a normal conditional expression.
9238 } else {
9239 if (LHSKind == NullabilityKind::Nullable ||
9240 RHSKind == NullabilityKind::Nullable)
9241 MergedKind = NullabilityKind::Nullable;
9242 else if (LHSKind == NullabilityKind::NonNull)
9243 MergedKind = RHSKind;
9244 else if (RHSKind == NullabilityKind::NonNull)
9245 MergedKind = LHSKind;
9246 else
9247 MergedKind = NullabilityKind::Unspecified;
9248 }
9249
9250 // Return if ResTy already has the correct nullability.
9251 if (GetNullability(ResTy) == MergedKind)
9252 return ResTy;
9253
9254 // Strip all nullability from ResTy.
9255 while (ResTy->getNullability())
9256 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9257
9258 // Create a new AttributedType with the new nullability kind.
9259 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
9260}
9261
9263 SourceLocation ColonLoc,
9264 Expr *CondExpr, Expr *LHSExpr,
9265 Expr *RHSExpr) {
9266 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9267 // was the condition.
9268 OpaqueValueExpr *opaqueValue = nullptr;
9269 Expr *commonExpr = nullptr;
9270 if (!LHSExpr) {
9271 commonExpr = CondExpr;
9272 // Lower out placeholder types first. This is important so that we don't
9273 // try to capture a placeholder. This happens in few cases in C++; such
9274 // as Objective-C++'s dictionary subscripting syntax.
9275 if (commonExpr->hasPlaceholderType()) {
9276 ExprResult result = CheckPlaceholderExpr(commonExpr);
9277 if (!result.isUsable()) return ExprError();
9278 commonExpr = result.get();
9279 }
9280 // We usually want to apply unary conversions *before* saving, except
9281 // in the special case of a C++ l-value conditional.
9282 if (!(getLangOpts().CPlusPlus
9283 && !commonExpr->isTypeDependent()
9284 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9285 && commonExpr->isGLValue()
9286 && commonExpr->isOrdinaryOrBitFieldObject()
9287 && RHSExpr->isOrdinaryOrBitFieldObject()
9288 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9289 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9290 if (commonRes.isInvalid())
9291 return ExprError();
9292 commonExpr = commonRes.get();
9293 }
9294
9295 // If the common expression is a class or array prvalue, materialize it
9296 // so that we can safely refer to it multiple times.
9297 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9298 commonExpr->getType()->isArrayType())) {
9299 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9300 if (MatExpr.isInvalid())
9301 return ExprError();
9302 commonExpr = MatExpr.get();
9303 }
9304
9305 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9306 commonExpr->getType(),
9307 commonExpr->getValueKind(),
9308 commonExpr->getObjectKind(),
9309 commonExpr);
9310 LHSExpr = CondExpr = opaqueValue;
9311 }
9312
9313 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9316 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9317 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9318 VK, OK, QuestionLoc);
9319 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9320 RHS.isInvalid())
9321 return ExprError();
9322
9323 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9324 RHS.get());
9325
9326 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9327
9328 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9329 Context);
9330
9331 if (!commonExpr)
9332 return new (Context)
9333 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9334 RHS.get(), result, VK, OK);
9335
9337 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9338 ColonLoc, result, VK, OK);
9339}
9340
9342 unsigned FromAttributes = 0, ToAttributes = 0;
9343 if (const auto *FromFn =
9344 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9345 FromAttributes =
9346 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9347 if (const auto *ToFn =
9348 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9349 ToAttributes =
9350 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9351
9352 return FromAttributes != ToAttributes;
9353}
9354
9355// checkPointerTypesForAssignment - This is a very tricky routine (despite
9356// being closely modeled after the C99 spec:-). The odd characteristic of this
9357// routine is it effectively iqnores the qualifiers on the top level pointee.
9358// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9359// FIXME: add a couple examples in this comment.
9361 QualType LHSType,
9362 QualType RHSType,
9363 SourceLocation Loc) {
9364 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9365 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9366
9367 // get the "pointed to" type (ignoring qualifiers at the top level)
9368 const Type *lhptee, *rhptee;
9369 Qualifiers lhq, rhq;
9370 std::tie(lhptee, lhq) =
9371 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9372 std::tie(rhptee, rhq) =
9373 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9374
9376
9377 // C99 6.5.16.1p1: This following citation is common to constraints
9378 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9379 // qualifiers of the type *pointed to* by the right;
9380
9381 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9382 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9384 // Ignore lifetime for further calculation.
9385 lhq.removeObjCLifetime();
9386 rhq.removeObjCLifetime();
9387 }
9388
9389 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
9390 // Treat address-space mismatches as fatal.
9391 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
9393
9394 // It's okay to add or remove GC or lifetime qualifiers when converting to
9395 // and from void*.
9398 S.getASTContext()) &&
9399 (lhptee->isVoidType() || rhptee->isVoidType()))
9400 ; // keep old
9401
9402 // Treat lifetime mismatches as fatal.
9403 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9405
9406 // Treat pointer-auth mismatches as fatal.
9407 else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth()))
9409
9410 // For GCC/MS compatibility, other qualifier mismatches are treated
9411 // as still compatible in C.
9412 else
9414 }
9415
9416 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9417 // incomplete type and the other is a pointer to a qualified or unqualified
9418 // version of void...
9419 if (lhptee->isVoidType()) {
9420 if (rhptee->isIncompleteOrObjectType())
9421 return ConvTy;
9422
9423 // As an extension, we allow cast to/from void* to function pointer.
9424 assert(rhptee->isFunctionType());
9426 }
9427
9428 if (rhptee->isVoidType()) {
9429 // In C, void * to another pointer type is compatible, but we want to note
9430 // that there will be an implicit conversion happening here.
9431 if (lhptee->isIncompleteOrObjectType())
9432 return ConvTy == AssignConvertType::Compatible &&
9433 !S.getLangOpts().CPlusPlus
9435 : ConvTy;
9436
9437 // As an extension, we allow cast to/from void* to function pointer.
9438 assert(lhptee->isFunctionType());
9440 }
9441
9442 if (!S.Diags.isIgnored(
9443 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9444 Loc) &&
9445 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9446 !S.TryFunctionConversion(RHSType, LHSType, RHSType))
9448
9449 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9450 // unqualified versions of compatible types, ...
9451 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9452
9453 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9454 if (!S.Context.hasSameType(ltrans, rtrans)) {
9455 QualType LUnderlying =
9456 ltrans->isOverflowBehaviorType()
9457 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9458 : ltrans;
9459 QualType RUnderlying =
9460 rtrans->isOverflowBehaviorType()
9461 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9462 : rtrans;
9463
9464 if (S.Context.hasSameType(LUnderlying, RUnderlying))
9466
9467 ltrans = LUnderlying;
9468 rtrans = RUnderlying;
9469 }
9470 }
9471
9472 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9473 // Check if the pointee types are compatible ignoring the sign.
9474 // We explicitly check for char so that we catch "char" vs
9475 // "unsigned char" on systems where "char" is unsigned.
9476 if (lhptee->isCharType())
9477 ltrans = S.Context.UnsignedCharTy;
9478 else if (lhptee->hasSignedIntegerRepresentation())
9479 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9480
9481 if (rhptee->isCharType())
9482 rtrans = S.Context.UnsignedCharTy;
9483 else if (rhptee->hasSignedIntegerRepresentation())
9484 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9485
9486 if (ltrans == rtrans) {
9487 // Types are compatible ignoring the sign. Qualifier incompatibility
9488 // takes priority over sign incompatibility because the sign
9489 // warning can be disabled.
9490 if (!S.IsAssignConvertCompatible(ConvTy))
9491 return ConvTy;
9492
9494 }
9495
9496 // If we are a multi-level pointer, it's possible that our issue is simply
9497 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9498 // the eventual target type is the same and the pointers have the same
9499 // level of indirection, this must be the issue.
9500 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9501 do {
9502 std::tie(lhptee, lhq) =
9503 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9504 std::tie(rhptee, rhq) =
9505 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9506
9507 // Inconsistent address spaces at this point is invalid, even if the
9508 // address spaces would be compatible.
9509 // FIXME: This doesn't catch address space mismatches for pointers of
9510 // different nesting levels, like:
9511 // __local int *** a;
9512 // int ** b = a;
9513 // It's not clear how to actually determine when such pointers are
9514 // invalidly incompatible.
9515 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9516 return AssignConvertType::
9517 IncompatibleNestedPointerAddressSpaceMismatch;
9518
9519 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9520
9521 if (lhptee == rhptee)
9523 }
9524
9525 // General pointer incompatibility takes priority over qualifiers.
9526 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9529 }
9530 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9531 // hasSameType, so we can skip further checks.
9532 const auto *LFT = ltrans->getAs<FunctionType>();
9533 const auto *RFT = rtrans->getAs<FunctionType>();
9534 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9535 // The invocation of IsFunctionConversion below will try to transform rtrans
9536 // to obtain an exact match for ltrans. This should not fail because of
9537 // mismatches in result type and parameter types, they were already checked
9538 // by typesAreCompatible above. So we will recreate rtrans (or where
9539 // appropriate ltrans) using the result type and parameter types from ltrans
9540 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9541 const auto *LFPT = dyn_cast<FunctionProtoType>(LFT);
9542 const auto *RFPT = dyn_cast<FunctionProtoType>(RFT);
9543 if (LFPT && RFPT) {
9544 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9545 LFPT->getParamTypes(),
9546 RFPT->getExtProtoInfo());
9547 } else if (LFPT) {
9549 EPI.ExtInfo = RFT->getExtInfo();
9550 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9551 LFPT->getParamTypes(), EPI);
9552 } else if (RFPT) {
9553 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9554 // all of its ExtProtoInfo. Transform ltrans instead.
9556 EPI.ExtInfo = LFT->getExtInfo();
9557 ltrans = S.Context.getFunctionType(RFPT->getReturnType(),
9558 RFPT->getParamTypes(), EPI);
9559 } else {
9560 rtrans = S.Context.getFunctionNoProtoType(LFT->getReturnType(),
9561 RFT->getExtInfo());
9562 }
9563 if (!S.Context.hasSameUnqualifiedType(rtrans, ltrans) &&
9564 !S.IsFunctionConversion(rtrans, ltrans))
9566 }
9567 return ConvTy;
9568}
9569
9570/// checkBlockPointerTypesForAssignment - This routine determines whether two
9571/// block pointer types are compatible or whether a block and normal pointer
9572/// are compatible. It is more restrict than comparing two function pointer
9573// types.
9575 QualType LHSType,
9576 QualType RHSType) {
9577 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9578 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9579
9580 QualType lhptee, rhptee;
9581
9582 // get the "pointed to" type (ignoring qualifiers at the top level)
9583 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9584 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9585
9586 // In C++, the types have to match exactly.
9587 if (S.getLangOpts().CPlusPlus)
9589
9591
9592 // For blocks we enforce that qualifiers are identical.
9593 Qualifiers LQuals = lhptee.getLocalQualifiers();
9594 Qualifiers RQuals = rhptee.getLocalQualifiers();
9595 if (S.getLangOpts().OpenCL) {
9596 LQuals.removeAddressSpace();
9597 RQuals.removeAddressSpace();
9598 }
9599 if (LQuals != RQuals)
9601
9602 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9603 // assignment.
9604 // The current behavior is similar to C++ lambdas. A block might be
9605 // assigned to a variable iff its return type and parameters are compatible
9606 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9607 // an assignment. Presumably it should behave in way that a function pointer
9608 // assignment does in C, so for each parameter and return type:
9609 // * CVR and address space of LHS should be a superset of CVR and address
9610 // space of RHS.
9611 // * unqualified types should be compatible.
9612 if (S.getLangOpts().OpenCL) {
9614 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9615 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9617 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9619
9620 return ConvTy;
9621}
9622
9623/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9624/// for assignment compatibility.
9626 QualType LHSType,
9627 QualType RHSType) {
9628 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9629 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9630
9631 if (LHSType->isObjCBuiltinType()) {
9632 // Class is not compatible with ObjC object pointers.
9633 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9634 !RHSType->isObjCQualifiedClassType())
9637 }
9638 if (RHSType->isObjCBuiltinType()) {
9639 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9640 !LHSType->isObjCQualifiedClassType())
9643 }
9644 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9645 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9646
9647 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9648 // make an exception for id<P>
9649 !LHSType->isObjCQualifiedIdType())
9651
9652 if (S.Context.typesAreCompatible(LHSType, RHSType))
9654 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9657}
9658
9660 QualType LHSType,
9661 QualType RHSType) {
9662 // Fake up an opaque expression. We don't actually care about what
9663 // cast operations are required, so if CheckAssignmentConstraints
9664 // adds casts to this they'll be wasted, but fortunately that doesn't
9665 // usually happen on valid code.
9666 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9667 ExprResult RHSPtr = &RHSExpr;
9668 CastKind K;
9669
9670 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9671}
9672
9673/// This helper function returns true if QT is a vector type that has element
9674/// type ElementType.
9675static bool isVector(QualType QT, QualType ElementType) {
9676 if (const VectorType *VT = QT->getAs<VectorType>())
9677 return VT->getElementType().getCanonicalType() == ElementType;
9678 return false;
9679}
9680
9681/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9682/// has code to accommodate several GCC extensions when type checking
9683/// pointers. Here are some objectionable examples that GCC considers warnings:
9684///
9685/// int a, *pint;
9686/// short *pshort;
9687/// struct foo *pfoo;
9688///
9689/// pint = pshort; // warning: assignment from incompatible pointer type
9690/// a = pint; // warning: assignment makes integer from pointer without a cast
9691/// pint = a; // warning: assignment makes pointer from integer without a cast
9692/// pint = pfoo; // warning: assignment from incompatible pointer type
9693///
9694/// As a result, the code for dealing with pointers is more complex than the
9695/// C99 spec dictates.
9696///
9697/// Sets 'Kind' for any result kind except Incompatible.
9699 ExprResult &RHS,
9700 CastKind &Kind,
9701 bool ConvertRHS) {
9702 QualType RHSType = RHS.get()->getType();
9703 QualType OrigLHSType = LHSType;
9704
9705 // Get canonical types. We're not formatting these types, just comparing
9706 // them.
9707 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9708 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9709
9710 // Common case: no conversion required.
9711 if (LHSType == RHSType) {
9712 Kind = CK_NoOp;
9714 }
9715
9716 // If the LHS has an __auto_type, there are no additional type constraints
9717 // to be worried about.
9718 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9719 if (AT->isGNUAutoType()) {
9720 Kind = CK_NoOp;
9722 }
9723 }
9724
9725 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHSType, RHSType);
9726 switch (OBTResult) {
9728 Kind = CK_NoOp;
9731 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9735 break;
9736 }
9737
9738 // Check for incompatible OBT types in pointer pointee types
9739 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9740 QualType LHSPointee = LHSType->getPointeeType();
9741 QualType RHSPointee = RHSType->getPointeeType();
9742 if ((LHSPointee->isOverflowBehaviorType() ||
9743 RHSPointee->isOverflowBehaviorType()) &&
9744 !Context.areCompatibleOverflowBehaviorTypes(LHSPointee, RHSPointee)) {
9745 Kind = CK_NoOp;
9747 }
9748 }
9749
9750 // If we have an atomic type, try a non-atomic assignment, then just add an
9751 // atomic qualification step.
9752 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9754 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9756 return Result;
9757 if (Kind != CK_NoOp && ConvertRHS)
9758 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9759 Kind = CK_NonAtomicToAtomic;
9760 return Result;
9761 }
9762
9763 // If the left-hand side is a reference type, then we are in a
9764 // (rare!) case where we've allowed the use of references in C,
9765 // e.g., as a parameter type in a built-in function. In this case,
9766 // just make sure that the type referenced is compatible with the
9767 // right-hand side type. The caller is responsible for adjusting
9768 // LHSType so that the resulting expression does not have reference
9769 // type.
9770 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9771 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9772 Kind = CK_LValueBitCast;
9774 }
9776 }
9777
9778 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9779 // of an ExtVector type to the same ExtVector type.
9780 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9781 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9782 // Implicit conversions require the same number of elements.
9783 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9785
9786 if (LHSType->isExtVectorBoolType() &&
9787 RHSExtType->getElementType()->isIntegerType()) {
9788 Kind = CK_IntegralToBoolean;
9790 }
9791 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9792 if (Context.getLangOpts().OpenCL &&
9793 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9794 Kind = CK_BitCast;
9796 }
9798 }
9799 if (RHSType->isArithmeticType()) {
9800 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9801 if (ConvertRHS)
9802 RHS = prepareVectorSplat(LHSType, RHS.get());
9803 Kind = CK_VectorSplat;
9805 }
9806 }
9807
9808 // Conversions to or from vector type.
9809 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9810 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9811 // Allow assignments of an AltiVec vector type to an equivalent GCC
9812 // vector type and vice versa
9813 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9814 Kind = CK_BitCast;
9816 }
9817
9818 // If we are allowing lax vector conversions, and LHS and RHS are both
9819 // vectors, the total size only needs to be the same. This is a bitcast;
9820 // no bits are changed but the result type is different.
9821 if (isLaxVectorConversion(RHSType, LHSType)) {
9822 // The default for lax vector conversions with Altivec vectors will
9823 // change, so if we are converting between vector types where
9824 // at least one is an Altivec vector, emit a warning.
9825 if (Context.getTargetInfo().getTriple().isPPC() &&
9826 anyAltivecTypes(RHSType, LHSType) &&
9827 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9828 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9829 << RHSType << LHSType;
9830 Kind = CK_BitCast;
9832 }
9833 }
9834
9835 // When the RHS comes from another lax conversion (e.g. binops between
9836 // scalars and vectors) the result is canonicalized as a vector. When the
9837 // LHS is also a vector, the lax is allowed by the condition above. Handle
9838 // the case where LHS is a scalar.
9839 if (LHSType->isScalarType()) {
9840 const VectorType *VecType = RHSType->getAs<VectorType>();
9841 if (VecType && VecType->getNumElements() == 1 &&
9842 isLaxVectorConversion(RHSType, LHSType)) {
9843 if (Context.getTargetInfo().getTriple().isPPC() &&
9845 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9847 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9848 << RHSType << LHSType;
9849 ExprResult *VecExpr = &RHS;
9850 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9851 Kind = CK_BitCast;
9853 }
9854 }
9855
9856 // Allow assignments between fixed-length and sizeless SVE vectors.
9857 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9858 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9859 if (ARM().areCompatibleSveTypes(LHSType, RHSType) ||
9860 ARM().areLaxCompatibleSveTypes(LHSType, RHSType)) {
9861 Kind = CK_BitCast;
9863 }
9864
9865 // Allow assignments between fixed-length and sizeless RVV vectors.
9866 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9867 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9868 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9869 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9870 Kind = CK_BitCast;
9872 }
9873 }
9874
9876 }
9877
9878 // Diagnose attempts to convert between __ibm128, __float128 and long double
9879 // where such conversions currently can't be handled.
9880 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9882
9883 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9884 // discards the imaginary part.
9885 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9886 !LHSType->getAs<ComplexType>())
9888
9889 // Arithmetic conversions.
9890 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9891 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9892 if (ConvertRHS)
9893 Kind = PrepareScalarCast(RHS, LHSType);
9895 }
9896
9897 // Conversions to normal pointers.
9898 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9899 // U* -> T*
9900 if (isa<PointerType>(RHSType)) {
9901 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9902 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9903 if (AddrSpaceL != AddrSpaceR)
9904 Kind = CK_AddressSpaceConversion;
9905 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9906 Kind = CK_NoOp;
9907 else
9908 Kind = CK_BitCast;
9909 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9910 RHS.get()->getBeginLoc());
9911 }
9912
9913 // int -> T*
9914 if (RHSType->isIntegerType()) {
9915 Kind = CK_IntegralToPointer; // FIXME: null?
9917 }
9918
9919 // C pointers are not compatible with ObjC object pointers,
9920 // with two exceptions:
9921 if (isa<ObjCObjectPointerType>(RHSType)) {
9922 // - conversions to void*
9923 if (LHSPointer->getPointeeType()->isVoidType()) {
9924 Kind = CK_BitCast;
9926 }
9927
9928 // - conversions from 'Class' to the redefinition type
9929 if (RHSType->isObjCClassType() &&
9930 Context.hasSameType(LHSType,
9931 Context.getObjCClassRedefinitionType())) {
9932 Kind = CK_BitCast;
9934 }
9935
9936 Kind = CK_BitCast;
9938 }
9939
9940 // U^ -> void*
9941 if (RHSType->getAs<BlockPointerType>()) {
9942 if (LHSPointer->getPointeeType()->isVoidType()) {
9943 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9944 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9945 ->getPointeeType()
9946 .getAddressSpace();
9947 Kind =
9948 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9950 }
9951 }
9952
9954 }
9955
9956 // Conversions to block pointers.
9957 if (isa<BlockPointerType>(LHSType)) {
9958 // U^ -> T^
9959 if (RHSType->isBlockPointerType()) {
9960 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9961 ->getPointeeType()
9962 .getAddressSpace();
9963 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9964 ->getPointeeType()
9965 .getAddressSpace();
9966 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9967 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9968 }
9969
9970 // int or null -> T^
9971 if (RHSType->isIntegerType()) {
9972 Kind = CK_IntegralToPointer; // FIXME: null
9974 }
9975
9976 // id -> T^
9977 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9978 Kind = CK_AnyPointerToBlockPointerCast;
9980 }
9981
9982 // void* -> T^
9983 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9984 if (RHSPT->getPointeeType()->isVoidType()) {
9985 Kind = CK_AnyPointerToBlockPointerCast;
9987 }
9988
9990 }
9991
9992 // Conversions to Objective-C pointers.
9993 if (isa<ObjCObjectPointerType>(LHSType)) {
9994 // A* -> B*
9995 if (RHSType->isObjCObjectPointerType()) {
9996 Kind = CK_BitCast;
9997 AssignConvertType result =
9998 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9999 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10001 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
10003 return result;
10004 }
10005
10006 // int or null -> A*
10007 if (RHSType->isIntegerType()) {
10008 Kind = CK_IntegralToPointer; // FIXME: null
10010 }
10011
10012 // In general, C pointers are not compatible with ObjC object pointers,
10013 // with two exceptions:
10014 if (isa<PointerType>(RHSType)) {
10015 Kind = CK_CPointerToObjCPointerCast;
10016
10017 // - conversions from 'void*'
10018 if (RHSType->isVoidPointerType()) {
10020 }
10021
10022 // - conversions to 'Class' from its redefinition type
10023 if (LHSType->isObjCClassType() &&
10024 Context.hasSameType(RHSType,
10025 Context.getObjCClassRedefinitionType())) {
10027 }
10028
10030 }
10031
10032 // Only under strict condition T^ is compatible with an Objective-C pointer.
10033 if (RHSType->isBlockPointerType() &&
10035 if (ConvertRHS)
10037 Kind = CK_BlockPointerToObjCPointerCast;
10039 }
10040
10042 }
10043
10044 // Conversion to nullptr_t (C23 only)
10045 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10048 // null -> nullptr_t
10049 Kind = CK_NullToPointer;
10051 }
10052
10053 // Conversions from pointers that are not covered by the above.
10054 if (isa<PointerType>(RHSType)) {
10055 // T* -> _Bool
10056 if (LHSType == Context.BoolTy) {
10057 Kind = CK_PointerToBoolean;
10059 }
10060
10061 // T* -> int
10062 if (LHSType->isIntegerType()) {
10063 Kind = CK_PointerToIntegral;
10065 }
10066
10068 }
10069
10070 // Conversions from Objective-C pointers that are not covered by the above.
10071 if (isa<ObjCObjectPointerType>(RHSType)) {
10072 // T* -> _Bool
10073 if (LHSType == Context.BoolTy) {
10074 Kind = CK_PointerToBoolean;
10076 }
10077
10078 // T* -> int
10079 if (LHSType->isIntegerType()) {
10080 Kind = CK_PointerToIntegral;
10082 }
10083
10085 }
10086
10087 // struct A -> struct B
10088 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
10089 if (Context.typesAreCompatible(LHSType, RHSType)) {
10090 Kind = CK_NoOp;
10092 }
10093 }
10094
10095 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10096 Kind = CK_IntToOCLSampler;
10098 }
10099
10101}
10102
10103/// Constructs a transparent union from an expression that is
10104/// used to initialize the transparent union.
10106 ExprResult &EResult, QualType UnionType,
10107 FieldDecl *Field) {
10108 // Build an initializer list that designates the appropriate member
10109 // of the transparent union.
10110 Expr *E = EResult.get();
10112 C, SourceLocation(), E, SourceLocation(), /*isExplicit=*/false);
10113 Initializer->setType(UnionType);
10114 Initializer->setInitializedFieldInUnion(Field);
10115
10116 // Build a compound literal constructing a value of the transparent
10117 // union type from this initializer list.
10118 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10119 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10120 VK_PRValue, Initializer, false);
10121}
10122
10125 ExprResult &RHS) {
10126 QualType RHSType = RHS.get()->getType();
10127
10128 // If the ArgType is a Union type, we want to handle a potential
10129 // transparent_union GCC extension.
10130 const RecordType *UT = ArgType->getAsUnionType();
10131 if (!UT)
10133
10134 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10135 if (!UD->hasAttr<TransparentUnionAttr>())
10137
10138 // The field to initialize within the transparent union.
10139 FieldDecl *InitField = nullptr;
10140 // It's compatible if the expression matches any of the fields.
10141 for (auto *it : UD->fields()) {
10142 if (it->getType()->isPointerType()) {
10143 // If the transparent union contains a pointer type, we allow:
10144 // 1) void pointer
10145 // 2) null pointer constant
10146 if (RHSType->isPointerType())
10147 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10148 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10149 InitField = it;
10150 break;
10151 }
10152
10155 RHS = ImpCastExprToType(RHS.get(), it->getType(),
10156 CK_NullToPointer);
10157 InitField = it;
10158 break;
10159 }
10160 }
10161
10162 CastKind Kind;
10163 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) ==
10165 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10166 InitField = it;
10167 break;
10168 }
10169 }
10170
10171 if (!InitField)
10173
10174 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10176}
10177
10179 ExprResult &CallerRHS,
10180 bool Diagnose,
10181 bool DiagnoseCFAudited,
10182 bool ConvertRHS) {
10183 // We need to be able to tell the caller whether we diagnosed a problem, if
10184 // they ask us to issue diagnostics.
10185 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10186
10187 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10188 // we can't avoid *all* modifications at the moment, so we need some somewhere
10189 // to put the updated value.
10190 ExprResult LocalRHS = CallerRHS;
10191 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10192
10193 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10194 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10195 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10196 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10197 Diag(RHS.get()->getExprLoc(),
10198 diag::warn_noderef_to_dereferenceable_pointer)
10199 << RHS.get()->getSourceRange();
10200 }
10201 }
10202 }
10203
10204 if (getLangOpts().CPlusPlus) {
10205 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10206 // C++ 5.17p3: If the left operand is not of class type, the
10207 // expression is implicitly converted (C++ 4) to the
10208 // cv-unqualified type of the left operand.
10209 QualType RHSType = RHS.get()->getType();
10210 if (Diagnose) {
10211 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10213 } else {
10216 /*SuppressUserConversions=*/false,
10217 AllowedExplicit::None,
10218 /*InOverloadResolution=*/false,
10219 /*CStyle=*/false,
10220 /*AllowObjCWritebackConversion=*/false);
10221 if (ICS.isFailure())
10223 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10225 }
10226 if (RHS.isInvalid())
10229 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10230 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10232
10233 // Check if OBT is being discarded during assignment
10234 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10235 if (RHSType->isOverflowBehaviorType() &&
10236 !LHSType->isOverflowBehaviorType()) {
10238 }
10239
10240 return result;
10241 }
10242
10243 // FIXME: Currently, we fall through and treat C++ classes like C
10244 // structures.
10245 // FIXME: We also fall through for atomics; not sure what should
10246 // happen there, though.
10247 } else if (RHS.get()->getType() == Context.OverloadTy) {
10248 // As a set of extensions to C, we support overloading on functions. These
10249 // functions need to be resolved here.
10250 DeclAccessPair DAP;
10252 RHS.get(), LHSType, /*Complain=*/false, DAP))
10253 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10254 else
10256 }
10257
10258 // For HLSL records, insert derived-to-base conversion if needed.
10259 if (getLangOpts().HLSL && LHSType->isRecordType()) {
10260 QualType RHSType = RHS.get()->getType();
10261 if (!Context.hasSameUnqualifiedType(RHSType, LHSType)) {
10262 CXXBasePaths Paths;
10263 if (IsDerivedFrom(RHS.get()->getBeginLoc(), RHSType, LHSType, Paths)) {
10264 CXXCastPath CastPath;
10265 BuildBasePathArray(Paths, CastPath);
10266 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_DerivedToBase, VK_LValue,
10267 &CastPath);
10268 }
10269 }
10270 }
10271
10272 // This check seems unnatural, however it is necessary to ensure the proper
10273 // conversion of functions/arrays. If the conversion were done for all
10274 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10275 // expressions that suppress this implicit conversion (&, sizeof). This needs
10276 // to happen before we check for null pointer conversions because C does not
10277 // undergo the same implicit conversions as C++ does above (by the calls to
10278 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10279 // lvalue to rvalue cast before checking for null pointer constraints. This
10280 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10281 //
10282 // Suppress this for references: C++ 8.5.3p5.
10283 if (!LHSType->isReferenceType()) {
10284 // FIXME: We potentially allocate here even if ConvertRHS is false.
10286 if (RHS.isInvalid())
10288 }
10289
10290 // The constraints are expressed in terms of the atomic, qualified, or
10291 // unqualified type of the LHS.
10292 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10293
10294 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10295 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10296 if ((LHSTypeAfterConversion->isPointerType() ||
10297 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10298 LHSTypeAfterConversion->isBlockPointerType()) &&
10299 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10303 if (Diagnose || ConvertRHS) {
10304 CastKind Kind;
10305 CXXCastPath Path;
10306 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10307 /*IgnoreBaseAccess=*/false, Diagnose);
10308
10309 // If there is a conversion of some kind, check to see what kind of
10310 // pointer conversion happened so we can diagnose a C++ compatibility
10311 // diagnostic if the conversion is invalid. This only matters if the RHS
10312 // is some kind of void pointer. We have a carve-out when the RHS is from
10313 // a macro expansion because the use of a macro may indicate different
10314 // code between C and C++. Consider: char *s = NULL; where NULL is
10315 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10316 // C++, which is valid in C++.
10317 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10318 !RHS.get()->getBeginLoc().isMacroID()) {
10319 QualType CanRHS =
10321 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10322 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10323 Ret = checkPointerTypesForAssignment(*this, CanLHS, CanRHS,
10324 RHS.get()->getExprLoc());
10325 // Anything that's not considered perfectly compatible would be
10326 // incompatible in C++.
10329 }
10330 }
10331
10332 if (ConvertRHS)
10333 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10334 }
10335 return Ret;
10336 }
10337 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10338 // unqualified bool, and the right operand is a pointer or its type is
10339 // nullptr_t.
10340 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10341 RHS.get()->getType()->isNullPtrType()) {
10342 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10343 // only handles nullptr -> _Bool due to needing an extra conversion
10344 // step.
10345 // We model this by converting from nullptr -> void * and then let the
10346 // conversion from void * -> _Bool happen naturally.
10347 if (Diagnose || ConvertRHS) {
10348 CastKind Kind;
10349 CXXCastPath Path;
10350 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10351 /*IgnoreBaseAccess=*/false, Diagnose);
10352 if (ConvertRHS)
10353 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10354 &Path);
10355 }
10356 }
10357
10358 // OpenCL queue_t type assignment.
10359 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10361 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10363 }
10364
10365 CastKind Kind;
10366 AssignConvertType result =
10367 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10368
10369 // If assigning a void * created by an allocation function call to some other
10370 // type, check that the allocated size is sufficient for that type.
10371 if (result != AssignConvertType::Incompatible &&
10372 RHS.get()->getType()->isVoidPointerType())
10373 CheckSufficientAllocSize(*this, LHSType, RHS.get());
10374
10375 // C99 6.5.16.1p2: The value of the right operand is converted to the
10376 // type of the assignment expression.
10377 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10378 // so that we can use references in built-in functions even in C.
10379 // The getNonReferenceType() call makes sure that the resulting expression
10380 // does not have reference type.
10381 if (result != AssignConvertType::Incompatible &&
10382 RHS.get()->getType() != LHSType) {
10384 Expr *E = RHS.get();
10385
10386 // Check for various Objective-C errors. If we are not reporting
10387 // diagnostics and just checking for errors, e.g., during overload
10388 // resolution, return Incompatible to indicate the failure.
10389 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10390 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
10392 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10393 if (!Diagnose)
10395 }
10396 if (getLangOpts().ObjC &&
10397 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10398 E->getType(), E, Diagnose) ||
10399 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10400 if (!Diagnose)
10402 // Replace the expression with a corrected version and continue so we
10403 // can find further errors.
10404 RHS = E;
10406 }
10407
10408 if (ConvertRHS)
10409 RHS = ImpCastExprToType(E, Ty, Kind);
10410 }
10411
10412 return result;
10413}
10414
10415namespace {
10416/// The original operand to an operator, prior to the application of the usual
10417/// arithmetic conversions and converting the arguments of a builtin operator
10418/// candidate.
10419struct OriginalOperand {
10420 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10421 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10422 Op = MTE->getSubExpr();
10423 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10424 Op = BTE->getSubExpr();
10425 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10426 Orig = ICE->getSubExprAsWritten();
10427 Conversion = ICE->getConversionFunction();
10428 }
10429 }
10430
10431 QualType getType() const { return Orig->getType(); }
10432
10433 Expr *Orig;
10434 NamedDecl *Conversion;
10435};
10436}
10437
10439 ExprResult &RHS) {
10440 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10441
10442 Diag(Loc, diag::err_typecheck_invalid_operands)
10443 << OrigLHS.getType() << OrigRHS.getType()
10444 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10445
10446 // If a user-defined conversion was applied to either of the operands prior
10447 // to applying the built-in operator rules, tell the user about it.
10448 if (OrigLHS.Conversion) {
10449 Diag(OrigLHS.Conversion->getLocation(),
10450 diag::note_typecheck_invalid_operands_converted)
10451 << 0 << LHS.get()->getType();
10452 }
10453 if (OrigRHS.Conversion) {
10454 Diag(OrigRHS.Conversion->getLocation(),
10455 diag::note_typecheck_invalid_operands_converted)
10456 << 1 << RHS.get()->getType();
10457 }
10458
10459 return QualType();
10460}
10461
10463 ExprResult &RHS) {
10464 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10465 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10466
10467 bool LHSNatVec = LHSType->isVectorType();
10468 bool RHSNatVec = RHSType->isVectorType();
10469
10470 if (!(LHSNatVec && RHSNatVec)) {
10471 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10472 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10473 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10474 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10475 << Vector->getSourceRange();
10476 return QualType();
10477 }
10478
10479 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10480 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10481 << RHS.get()->getSourceRange();
10482
10483 return QualType();
10484}
10485
10486/// Try to convert a value of non-vector type to a vector type by converting
10487/// the type to the element type of the vector and then performing a splat.
10488/// If the language is OpenCL, we only use conversions that promote scalar
10489/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10490/// for float->int.
10491///
10492/// OpenCL V2.0 6.2.6.p2:
10493/// An error shall occur if any scalar operand type has greater rank
10494/// than the type of the vector element.
10495///
10496/// \param scalar - if non-null, actually perform the conversions
10497/// \return true if the operation fails (but without diagnosing the failure)
10499 QualType scalarTy,
10500 QualType vectorEltTy,
10501 QualType vectorTy,
10502 unsigned &DiagID) {
10503 // The conversion to apply to the scalar before splatting it,
10504 // if necessary.
10505 CastKind scalarCast = CK_NoOp;
10506
10507 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
10508 scalarCast = CK_IntegralToBoolean;
10509 } else if (vectorEltTy->isIntegralType(S.Context)) {
10510 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10511 (scalarTy->isIntegerType() &&
10512 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10513 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10514 return true;
10515 }
10516 if (!scalarTy->isIntegralType(S.Context))
10517 return true;
10518 scalarCast = CK_IntegralCast;
10519 } else if (vectorEltTy->isRealFloatingType()) {
10520 if (scalarTy->isRealFloatingType()) {
10521 if (S.getLangOpts().OpenCL &&
10522 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10523 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10524 return true;
10525 }
10526 scalarCast = CK_FloatingCast;
10527 }
10528 else if (scalarTy->isIntegralType(S.Context))
10529 scalarCast = CK_IntegralToFloating;
10530 else
10531 return true;
10532 } else {
10533 return true;
10534 }
10535
10536 // Adjust scalar if desired.
10537 if (scalar) {
10538 if (scalarCast != CK_NoOp)
10539 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10540 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10541 }
10542 return false;
10543}
10544
10545/// Convert vector E to a vector with the same number of elements but different
10546/// element type.
10547static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10548 const auto *VecTy = E->getType()->getAs<VectorType>();
10549 assert(VecTy && "Expression E must be a vector");
10550 QualType NewVecTy =
10551 VecTy->isExtVectorType()
10552 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10553 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10554 VecTy->getVectorKind());
10555
10556 // Look through the implicit cast. Return the subexpression if its type is
10557 // NewVecTy.
10558 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10559 if (ICE->getSubExpr()->getType() == NewVecTy)
10560 return ICE->getSubExpr();
10561
10562 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10563 return S.ImpCastExprToType(E, NewVecTy, Cast);
10564}
10565
10566/// Test if a (constant) integer Int can be casted to another integer type
10567/// IntTy without losing precision.
10569 QualType OtherIntTy) {
10570 Expr *E = Int->get();
10572 return false;
10573
10574 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10575
10576 // Reject cases where the value of the Int is unknown as that would
10577 // possibly cause truncation, but accept cases where the scalar can be
10578 // demoted without loss of precision.
10579 Expr::EvalResult EVResult;
10580 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10581 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10582 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10583 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10584
10585 if (CstInt) {
10586 // If the scalar is constant and is of a higher order and has more active
10587 // bits that the vector element type, reject it.
10588 llvm::APSInt Result = EVResult.Val.getInt();
10589 unsigned NumBits = IntSigned
10590 ? (Result.isNegative() ? Result.getSignificantBits()
10591 : Result.getActiveBits())
10592 : Result.getActiveBits();
10593 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10594 return true;
10595
10596 // If the signedness of the scalar type and the vector element type
10597 // differs and the number of bits is greater than that of the vector
10598 // element reject it.
10599 return (IntSigned != OtherIntSigned &&
10600 NumBits > S.Context.getIntWidth(OtherIntTy));
10601 }
10602
10603 // Reject cases where the value of the scalar is not constant and it's
10604 // order is greater than that of the vector element type.
10605 return (Order < 0);
10606}
10607
10608/// Test if a (constant) integer Int can be casted to floating point type
10609/// FloatTy without losing precision.
10611 QualType FloatTy) {
10612 if (Int->get()->containsErrors())
10613 return false;
10614
10615 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10616
10617 // Determine if the integer constant can be expressed as a floating point
10618 // number of the appropriate type.
10619 Expr::EvalResult EVResult;
10620 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10621
10622 uint64_t Bits = 0;
10623 if (CstInt) {
10624 // Reject constants that would be truncated if they were converted to
10625 // the floating point type. Test by simple to/from conversion.
10626 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10627 // could be avoided if there was a convertFromAPInt method
10628 // which could signal back if implicit truncation occurred.
10629 llvm::APSInt Result = EVResult.Val.getInt();
10630 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10631 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10632 llvm::APFloat::rmTowardZero);
10633 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10635 bool Ignored = false;
10636 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10637 &Ignored);
10638 if (Result != ConvertBack)
10639 return true;
10640 } else {
10641 // Reject types that cannot be fully encoded into the mantissa of
10642 // the float.
10643 Bits = S.Context.getTypeSize(IntTy);
10644 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10645 S.Context.getFloatTypeSemantics(FloatTy));
10646 if (Bits > FloatPrec)
10647 return true;
10648 }
10649
10650 return false;
10651}
10652
10653/// Attempt to convert and splat Scalar into a vector whose types matches
10654/// Vector following GCC conversion rules. The rule is that implicit
10655/// conversion can occur when Scalar can be casted to match Vector's element
10656/// type without causing truncation of Scalar.
10658 ExprResult *Vector) {
10659 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10660 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10661 QualType VectorEltTy;
10662
10663 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10664 assert(!isa<ExtVectorType>(VT) &&
10665 "ExtVectorTypes should not be handled here!");
10666 VectorEltTy = VT->getElementType();
10667 } else if (VectorTy->isSveVLSBuiltinType()) {
10668 VectorEltTy =
10669 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10670 } else {
10671 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10672 }
10673
10674 // Reject cases where the vector element type or the scalar element type are
10675 // not integral or floating point types.
10676 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10677 return true;
10678
10679 // The conversion to apply to the scalar before splatting it,
10680 // if necessary.
10681 CastKind ScalarCast = CK_NoOp;
10682
10683 // Accept cases where the vector elements are integers and the scalar is
10684 // an integer.
10685 // FIXME: Notionally if the scalar was a floating point value with a precise
10686 // integral representation, we could cast it to an appropriate integer
10687 // type and then perform the rest of the checks here. GCC will perform
10688 // this conversion in some cases as determined by the input language.
10689 // We should accept it on a language independent basis.
10690 if (VectorEltTy->isIntegralType(S.Context) &&
10691 ScalarTy->isIntegralType(S.Context) &&
10692 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10693
10694 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10695 return true;
10696
10697 ScalarCast = CK_IntegralCast;
10698 } else if (VectorEltTy->isIntegralType(S.Context) &&
10699 ScalarTy->isRealFloatingType()) {
10700 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10701 ScalarCast = CK_FloatingToIntegral;
10702 else
10703 return true;
10704 } else if (VectorEltTy->isRealFloatingType()) {
10705 if (ScalarTy->isRealFloatingType()) {
10706
10707 // Reject cases where the scalar type is not a constant and has a higher
10708 // Order than the vector element type.
10709 llvm::APFloat Result(0.0);
10710
10711 // Determine whether this is a constant scalar. In the event that the
10712 // value is dependent (and thus cannot be evaluated by the constant
10713 // evaluator), skip the evaluation. This will then diagnose once the
10714 // expression is instantiated.
10715 bool CstScalar = Scalar->get()->isValueDependent() ||
10716 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10717 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10718 if (!CstScalar && Order < 0)
10719 return true;
10720
10721 // If the scalar cannot be safely casted to the vector element type,
10722 // reject it.
10723 if (CstScalar) {
10724 bool Truncated = false;
10725 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10726 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10727 if (Truncated)
10728 return true;
10729 }
10730
10731 ScalarCast = CK_FloatingCast;
10732 } else if (ScalarTy->isIntegralType(S.Context)) {
10733 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10734 return true;
10735
10736 ScalarCast = CK_IntegralToFloating;
10737 } else
10738 return true;
10739 } else if (ScalarTy->isEnumeralType())
10740 return true;
10741
10742 // Adjust scalar if desired.
10743 if (ScalarCast != CK_NoOp)
10744 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10745 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10746 return false;
10747}
10748
10750 SourceLocation Loc, bool IsCompAssign,
10751 bool AllowBothBool,
10752 bool AllowBoolConversions,
10753 bool AllowBoolOperation,
10754 bool ReportInvalid) {
10755 if (!IsCompAssign) {
10757 if (LHS.isInvalid())
10758 return QualType();
10759 }
10761 if (RHS.isInvalid())
10762 return QualType();
10763
10764 // For conversion purposes, we ignore any qualifiers.
10765 // For example, "const float" and "float" are equivalent.
10766 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10767 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10768
10769 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10770 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10771 assert(LHSVecType || RHSVecType);
10772
10773 if (getLangOpts().HLSL)
10774 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10775 IsCompAssign);
10776
10777 // Any operation with MFloat8 type is only possible with C intrinsics
10778 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10779 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10780 return InvalidOperands(Loc, LHS, RHS);
10781
10782 // AltiVec-style "vector bool op vector bool" combinations are allowed
10783 // for some operators but not others.
10784 if (!AllowBothBool && LHSVecType &&
10785 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10786 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10787 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10788
10789 // This operation may not be performed on boolean vectors.
10790 if (!AllowBoolOperation &&
10791 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10792 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10793
10794 // If the vector types are identical, return.
10795 if (Context.hasSameType(LHSType, RHSType))
10796 return Context.getCommonSugaredType(LHSType, RHSType);
10797
10798 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10799 if (LHSVecType && RHSVecType &&
10800 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10801 if (isa<ExtVectorType>(LHSVecType)) {
10802 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10803 return LHSType;
10804 }
10805
10806 if (!IsCompAssign)
10807 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10808 return RHSType;
10809 }
10810
10811 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10812 // can be mixed, with the result being the non-bool type. The non-bool
10813 // operand must have integer element type.
10814 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10815 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10816 (Context.getTypeSize(LHSVecType->getElementType()) ==
10817 Context.getTypeSize(RHSVecType->getElementType()))) {
10818 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10819 LHSVecType->getElementType()->isIntegerType() &&
10820 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10821 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10822 return LHSType;
10823 }
10824 if (!IsCompAssign &&
10825 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10826 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10827 RHSVecType->getElementType()->isIntegerType()) {
10828 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10829 return RHSType;
10830 }
10831 }
10832
10833 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10834 // invalid since the ambiguity can affect the ABI.
10835 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10836 unsigned &SVEorRVV) {
10837 const VectorType *VecType = SecondType->getAs<VectorType>();
10838 SVEorRVV = 0;
10839 if (FirstType->isSizelessBuiltinType() && VecType) {
10842 return true;
10848 SVEorRVV = 1;
10849 return true;
10850 }
10851 }
10852
10853 return false;
10854 };
10855
10856 unsigned SVEorRVV;
10857 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10858 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10859 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10860 << SVEorRVV << LHSType << RHSType;
10861 return QualType();
10862 }
10863
10864 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10865 // invalid since the ambiguity can affect the ABI.
10866 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10867 unsigned &SVEorRVV) {
10868 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10869 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10870
10871 SVEorRVV = 0;
10872 if (FirstVecType && SecondVecType) {
10873 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10874 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10875 SecondVecType->getVectorKind() ==
10877 return true;
10878 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10879 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10880 SecondVecType->getVectorKind() ==
10882 SecondVecType->getVectorKind() ==
10884 SecondVecType->getVectorKind() ==
10886 SVEorRVV = 1;
10887 return true;
10888 }
10889 }
10890 return false;
10891 }
10892
10893 if (SecondVecType &&
10894 SecondVecType->getVectorKind() == VectorKind::Generic) {
10895 if (FirstType->isSVESizelessBuiltinType())
10896 return true;
10897 if (FirstType->isRVVSizelessBuiltinType()) {
10898 SVEorRVV = 1;
10899 return true;
10900 }
10901 }
10902
10903 return false;
10904 };
10905
10906 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10907 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10908 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10909 << SVEorRVV << LHSType << RHSType;
10910 return QualType();
10911 }
10912
10913 // If there's a vector type and a scalar, try to convert the scalar to
10914 // the vector element type and splat.
10915 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10916 if (!RHSVecType) {
10917 if (isa<ExtVectorType>(LHSVecType)) {
10918 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10919 LHSVecType->getElementType(), LHSType,
10920 DiagID))
10921 return LHSType;
10922 } else {
10923 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10924 return LHSType;
10925 }
10926 }
10927 if (!LHSVecType) {
10928 if (isa<ExtVectorType>(RHSVecType)) {
10929 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10930 LHSType, RHSVecType->getElementType(),
10931 RHSType, DiagID))
10932 return RHSType;
10933 } else {
10934 if (LHS.get()->isLValue() ||
10935 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10936 return RHSType;
10937 }
10938 }
10939
10940 // FIXME: The code below also handles conversion between vectors and
10941 // non-scalars, we should break this down into fine grained specific checks
10942 // and emit proper diagnostics.
10943 QualType VecType = LHSVecType ? LHSType : RHSType;
10944 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10945 QualType OtherType = LHSVecType ? RHSType : LHSType;
10946 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10947 if (isLaxVectorConversion(OtherType, VecType)) {
10948 if (Context.getTargetInfo().getTriple().isPPC() &&
10949 anyAltivecTypes(RHSType, LHSType) &&
10950 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10951 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10952 // If we're allowing lax vector conversions, only the total (data) size
10953 // needs to be the same. For non compound assignment, if one of the types is
10954 // scalar, the result is always the vector type.
10955 if (!IsCompAssign) {
10956 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10957 return VecType;
10958 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10959 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10960 // type. Note that this is already done by non-compound assignments in
10961 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10962 // <1 x T> -> T. The result is also a vector type.
10963 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10964 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10965 ExprResult *RHSExpr = &RHS;
10966 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10967 return VecType;
10968 }
10969 }
10970
10971 // Okay, the expression is invalid.
10972
10973 // If there's a non-vector, non-real operand, diagnose that.
10974 if ((!RHSVecType && !RHSType->isRealType()) ||
10975 (!LHSVecType && !LHSType->isRealType())) {
10976 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10977 << LHSType << RHSType
10978 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10979 return QualType();
10980 }
10981
10982 // OpenCL V1.1 6.2.6.p1:
10983 // If the operands are of more than one vector type, then an error shall
10984 // occur. Implicit conversions between vector types are not permitted, per
10985 // section 6.2.1.
10986 if (getLangOpts().OpenCL &&
10987 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10988 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10989 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10990 << RHSType;
10991 return QualType();
10992 }
10993
10994
10995 // If there is a vector type that is not a ExtVector and a scalar, we reach
10996 // this point if scalar could not be converted to the vector's element type
10997 // without truncation.
10998 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10999 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
11000 QualType Scalar = LHSVecType ? RHSType : LHSType;
11001 QualType Vector = LHSVecType ? LHSType : RHSType;
11002 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11003 Diag(Loc,
11004 diag::err_typecheck_vector_not_convertable_implict_truncation)
11005 << ScalarOrVector << Scalar << Vector;
11006
11007 return QualType();
11008 }
11009
11010 // Otherwise, use the generic diagnostic.
11011 Diag(Loc, DiagID)
11012 << LHSType << RHSType
11013 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11014 return QualType();
11015}
11016
11018 SourceLocation Loc,
11019 bool IsCompAssign,
11020 ArithConvKind OperationKind) {
11021 if (!IsCompAssign) {
11023 if (LHS.isInvalid())
11024 return QualType();
11025 }
11027 if (RHS.isInvalid())
11028 return QualType();
11029
11030 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11031 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11032
11033 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11034 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11035
11036 unsigned DiagID = diag::err_typecheck_invalid_operands;
11037 if ((OperationKind == ArithConvKind::Arithmetic) &&
11038 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11039 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11040 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11041 << RHS.get()->getSourceRange();
11042 return QualType();
11043 }
11044
11045 if (Context.hasSameType(LHSType, RHSType))
11046 return LHSType;
11047
11048 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11049 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11050 return LHSType;
11051 }
11052 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11053 if (LHS.get()->isLValue() ||
11054 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11055 return RHSType;
11056 }
11057
11058 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11059 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11060 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11061 << LHSType << RHSType << LHS.get()->getSourceRange()
11062 << RHS.get()->getSourceRange();
11063 return QualType();
11064 }
11065
11066 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11067 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11068 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
11069 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11070 << LHSType << RHSType << LHS.get()->getSourceRange()
11071 << RHS.get()->getSourceRange();
11072 return QualType();
11073 }
11074
11075 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11076 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11077 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11078 bool ScalarOrVector =
11079 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11080
11081 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
11082 << ScalarOrVector << Scalar << Vector;
11083
11084 return QualType();
11085 }
11086
11087 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11088 << RHS.get()->getSourceRange();
11089 return QualType();
11090}
11091
11092// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11093// expression. These are mainly cases where the null pointer is used as an
11094// integer instead of a pointer.
11096 SourceLocation Loc, bool IsCompare) {
11097 // The canonical way to check for a GNU null is with isNullPointerConstant,
11098 // but we use a bit of a hack here for speed; this is a relatively
11099 // hot path, and isNullPointerConstant is slow.
11100 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
11101 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
11102
11103 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11104
11105 // Avoid analyzing cases where the result will either be invalid (and
11106 // diagnosed as such) or entirely valid and not something to warn about.
11107 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11108 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11109 return;
11110
11111 // Comparison operations would not make sense with a null pointer no matter
11112 // what the other expression is.
11113 if (!IsCompare) {
11114 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
11115 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11116 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11117 return;
11118 }
11119
11120 // The rest of the operations only make sense with a null pointer
11121 // if the other expression is a pointer.
11122 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11123 NonNullType->canDecayToPointerType())
11124 return;
11125
11126 S.Diag(Loc, diag::warn_null_in_comparison_operation)
11127 << LHSNull /* LHS is NULL */ << NonNullType
11128 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11129}
11130
11132 SourceLocation OpLoc) {
11133 // If the divisor is real, then this is real/real or complex/real division.
11134 // Either way there can be no precision loss.
11135 auto *CT = DivisorTy->getAs<ComplexType>();
11136 if (!CT)
11137 return;
11138
11139 QualType ElementType = CT->getElementType().getCanonicalType();
11140 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11142 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11143 return;
11144
11145 ASTContext &Ctx = S.getASTContext();
11146 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11147 const llvm::fltSemantics &ElementTypeSemantics =
11148 Ctx.getFloatTypeSemantics(ElementType);
11149 const llvm::fltSemantics &HigherElementTypeSemantics =
11150 Ctx.getFloatTypeSemantics(HigherElementType);
11151
11152 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11153 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11154 (HigherElementType == Ctx.LongDoubleTy &&
11155 !Ctx.getTargetInfo().hasLongDoubleType())) {
11156 // Retain the location of the first use of higher precision type.
11159 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11160 if (Type == HigherElementType) {
11161 Num++;
11162 return;
11163 }
11164 }
11165 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
11166 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
11167 }
11168}
11169
11171 SourceLocation Loc) {
11172 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
11173 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
11174 if (!LUE || !RUE)
11175 return;
11176 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11177 RUE->getKind() != UETT_SizeOf)
11178 return;
11179
11180 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11181 QualType LHSTy = LHSArg->getType();
11182 QualType RHSTy;
11183
11184 if (RUE->isArgumentType())
11185 RHSTy = RUE->getArgumentType().getNonReferenceType();
11186 else
11187 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11188
11189 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11190 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11191 return;
11192
11193 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11194 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11195 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11196 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11197 << LHSArgDecl;
11198 }
11199 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11200 QualType ArrayElemTy = ArrayTy->getElementType();
11201 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11202 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11203 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11204 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11205 return;
11206 S.Diag(Loc, diag::warn_division_sizeof_array)
11207 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11208 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11209 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11210 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11211 << LHSArgDecl;
11212 }
11213
11214 S.Diag(Loc, diag::note_precedence_silence) << RHS;
11215 }
11216}
11217
11219 ExprResult &RHS,
11220 SourceLocation Loc, bool IsDiv) {
11221 // Check for division/remainder by zero.
11222 Expr::EvalResult RHSValue;
11223 if (!RHS.get()->isValueDependent() &&
11224 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11225 RHSValue.Val.getInt() == 0)
11226 S.DiagRuntimeBehavior(Loc, RHS.get(),
11227 S.PDiag(diag::warn_remainder_division_by_zero)
11228 << IsDiv << RHS.get()->getSourceRange());
11229}
11230
11231static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11232 const ExprResult &LHS, const ExprResult &RHS,
11233 BinaryOperatorKind Opc) {
11234 if (!LHS.isUsable() || !RHS.isUsable())
11235 return;
11236 const Expr *LHSExpr = LHS.get();
11237 const Expr *RHSExpr = RHS.get();
11238 const QualType LHSType = LHSExpr->getType();
11239 const QualType RHSType = RHSExpr->getType();
11240 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11241 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11242 if (!LHSIsScoped && !RHSIsScoped)
11243 return;
11244 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11245 return;
11246 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11247 return;
11248 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11249 return;
11250 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11251 SourceLocation BeginLoc = expr->getBeginLoc();
11252 QualType IntType = type->castAs<EnumType>()
11253 ->getDecl()
11254 ->getDefinitionOrSelf()
11255 ->getIntegerType();
11256 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11257 S.Diag(BeginLoc, diag::note_no_implicit_conversion_for_scoped_enum)
11258 << FixItHint::CreateInsertion(BeginLoc, InsertionString)
11259 << FixItHint::CreateInsertion(expr->getEndLoc(), ")");
11260 };
11261 if (LHSIsScoped) {
11262 DiagnosticHelper(LHSExpr, LHSType);
11263 }
11264 if (RHSIsScoped) {
11265 DiagnosticHelper(RHSExpr, RHSType);
11266 }
11267}
11268
11270 SourceLocation Loc,
11271 BinaryOperatorKind Opc) {
11272 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11273 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11274
11275 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11276
11277 QualType LHSTy = LHS.get()->getType();
11278 QualType RHSTy = RHS.get()->getType();
11279 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11280 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11281 /*AllowBothBool*/ getLangOpts().AltiVec,
11282 /*AllowBoolConversions*/ false,
11283 /*AllowBooleanOperation*/ false,
11284 /*ReportInvalid*/ true);
11285 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11286 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11288 if (!IsDiv &&
11289 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11290 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11291 // For division, only matrix-by-scalar is supported. Other combinations with
11292 // matrix types are invalid.
11293 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11294 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11295
11297 LHS, RHS, Loc,
11299 if (LHS.isInvalid() || RHS.isInvalid())
11300 return QualType();
11301
11302 if (compType.isNull() || !compType->isArithmeticType()) {
11303 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11304 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11305 return ResultTy;
11306 }
11307 if (IsDiv) {
11308 DetectPrecisionLossInComplexDivision(*this, RHS.get()->getType(), Loc);
11309 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11310 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11311 }
11312 return compType;
11313}
11314
11316 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11317 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11318
11319 // Note: This check is here to simplify the double exclusions of
11320 // scalar and vector HLSL checks. No getLangOpts().HLSL
11321 // is needed since all languages exlcude doubles.
11322 if (LHS.get()->getType()->isDoubleType() ||
11323 RHS.get()->getType()->isDoubleType() ||
11324 (LHS.get()->getType()->isVectorType() && LHS.get()
11325 ->getType()
11326 ->getAs<VectorType>()
11327 ->getElementType()
11328 ->isDoubleType()) ||
11329 (RHS.get()->getType()->isVectorType() && RHS.get()
11330 ->getType()
11331 ->getAs<VectorType>()
11332 ->getElementType()
11333 ->isDoubleType()))
11334 return InvalidOperands(Loc, LHS, RHS);
11335
11336 if (LHS.get()->getType()->isVectorType() ||
11337 RHS.get()->getType()->isVectorType()) {
11338 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11339 RHS.get()->getType()->hasIntegerRepresentation()) ||
11340 (getLangOpts().HLSL &&
11341 (LHS.get()->getType()->hasFloatingRepresentation() ||
11343 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11344 /*AllowBothBool*/ getLangOpts().AltiVec,
11345 /*AllowBoolConversions*/ false,
11346 /*AllowBooleanOperation*/ false,
11347 /*ReportInvalid*/ true);
11348 return InvalidOperands(Loc, LHS, RHS);
11349 }
11350
11351 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11352 RHS.get()->getType()->isSveVLSBuiltinType()) {
11353 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11355 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11357
11358 return InvalidOperands(Loc, LHS, RHS);
11359 }
11360
11362 LHS, RHS, Loc,
11364 if (LHS.isInvalid() || RHS.isInvalid())
11365 return QualType();
11366
11367 if (compType.isNull() ||
11368 (!compType->isIntegerType() &&
11369 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11370 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11371 diagnoseScopedEnums(*this, Loc, LHS, RHS,
11372 IsCompAssign ? BO_RemAssign : BO_Rem);
11373 return ResultTy;
11374 }
11375 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11376 return compType;
11377}
11378
11379/// Diagnose invalid arithmetic on two void pointers.
11381 Expr *LHSExpr, Expr *RHSExpr) {
11382 S.Diag(Loc, S.getLangOpts().CPlusPlus
11383 ? diag::err_typecheck_pointer_arith_void_type
11384 : diag::ext_gnu_void_ptr)
11385 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11386 << RHSExpr->getSourceRange();
11387}
11388
11389/// Diagnose invalid arithmetic on a void pointer.
11391 Expr *Pointer) {
11392 S.Diag(Loc, S.getLangOpts().CPlusPlus
11393 ? diag::err_typecheck_pointer_arith_void_type
11394 : diag::ext_gnu_void_ptr)
11395 << 0 /* one pointer */ << Pointer->getSourceRange();
11396}
11397
11398/// Diagnose invalid arithmetic on a null pointer.
11399///
11400/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11401/// idiom, which we recognize as a GNU extension.
11402///
11404 Expr *Pointer, bool IsGNUIdiom) {
11405 if (IsGNUIdiom)
11406 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11407 << Pointer->getSourceRange();
11408 else
11409 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11410 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11411}
11412
11413/// Diagnose invalid subraction on a null pointer.
11414///
11416 Expr *Pointer, bool BothNull) {
11417 // Null - null is valid in C++ [expr.add]p7
11418 if (BothNull && S.getLangOpts().CPlusPlus)
11419 return;
11420
11421 // Is this s a macro from a system header?
11423 return;
11424
11426 S.PDiag(diag::warn_pointer_sub_null_ptr)
11427 << S.getLangOpts().CPlusPlus
11428 << Pointer->getSourceRange());
11429}
11430
11431/// Diagnose invalid arithmetic on two function pointers.
11433 Expr *LHS, Expr *RHS) {
11434 assert(LHS->getType()->isAnyPointerType());
11435 assert(RHS->getType()->isAnyPointerType());
11436 S.Diag(Loc, S.getLangOpts().CPlusPlus
11437 ? diag::err_typecheck_pointer_arith_function_type
11438 : diag::ext_gnu_ptr_func_arith)
11439 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11440 // We only show the second type if it differs from the first.
11442 RHS->getType())
11443 << RHS->getType()->getPointeeType()
11444 << LHS->getSourceRange() << RHS->getSourceRange();
11445}
11446
11447/// Diagnose invalid arithmetic on a function pointer.
11449 Expr *Pointer) {
11450 assert(Pointer->getType()->isAnyPointerType());
11451 S.Diag(Loc, S.getLangOpts().CPlusPlus
11452 ? diag::err_typecheck_pointer_arith_function_type
11453 : diag::ext_gnu_ptr_func_arith)
11454 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11455 << 0 /* one pointer, so only one type */
11456 << Pointer->getSourceRange();
11457}
11458
11459/// Emit error if Operand is incomplete pointer type
11460///
11461/// \returns True if pointer has incomplete type
11463 Expr *Operand) {
11464 QualType ResType = Operand->getType();
11465 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11466 ResType = ResAtomicType->getValueType();
11467
11468 assert(ResType->isAnyPointerType());
11469 QualType PointeeTy = ResType->getPointeeType();
11470 return S.RequireCompleteSizedType(
11471 Loc, PointeeTy,
11472 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11473 Operand->getSourceRange());
11474}
11475
11476/// Check the validity of an arithmetic pointer operand.
11477///
11478/// If the operand has pointer type, this code will check for pointer types
11479/// which are invalid in arithmetic operations. These will be diagnosed
11480/// appropriately, including whether or not the use is supported as an
11481/// extension.
11482///
11483/// \returns True when the operand is valid to use (even if as an extension).
11485 Expr *Operand) {
11486 QualType ResType = Operand->getType();
11487 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11488 ResType = ResAtomicType->getValueType();
11489
11490 if (!ResType->isAnyPointerType()) return true;
11491
11492 QualType PointeeTy = ResType->getPointeeType();
11493 if (PointeeTy->isVoidType()) {
11494 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11495 return !S.getLangOpts().CPlusPlus;
11496 }
11497 if (PointeeTy->isFunctionType()) {
11498 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11499 return !S.getLangOpts().CPlusPlus;
11500 }
11501
11502 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11503
11504 return true;
11505}
11506
11507/// Check the validity of a binary arithmetic operation w.r.t. pointer
11508/// operands.
11509///
11510/// This routine will diagnose any invalid arithmetic on pointer operands much
11511/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11512/// for emitting a single diagnostic even for operations where both LHS and RHS
11513/// are (potentially problematic) pointers.
11514///
11515/// \returns True when the operand is valid to use (even if as an extension).
11517 Expr *LHSExpr, Expr *RHSExpr) {
11518 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11519 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11520 if (!isLHSPointer && !isRHSPointer) return true;
11521
11522 QualType LHSPointeeTy, RHSPointeeTy;
11523 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11524 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11525
11526 // if both are pointers check if operation is valid wrt address spaces
11527 if (isLHSPointer && isRHSPointer) {
11528 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
11529 S.getASTContext())) {
11530 S.Diag(Loc,
11531 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11532 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11533 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11534 return false;
11535 }
11536 }
11537
11538 // Check for arithmetic on pointers to incomplete types.
11539 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11540 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11541 if (isLHSVoidPtr || isRHSVoidPtr) {
11542 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11543 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11544 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11545
11546 return !S.getLangOpts().CPlusPlus;
11547 }
11548
11549 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11550 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11551 if (isLHSFuncPtr || isRHSFuncPtr) {
11552 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11553 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11554 RHSExpr);
11555 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11556
11557 return !S.getLangOpts().CPlusPlus;
11558 }
11559
11560 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11561 return false;
11562 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11563 return false;
11564
11565 return true;
11566}
11567
11568/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11569/// literal.
11571 Expr *LHSExpr, Expr *RHSExpr) {
11572 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11573 Expr* IndexExpr = RHSExpr;
11574 if (!StrExpr) {
11575 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11576 IndexExpr = LHSExpr;
11577 }
11578
11579 bool IsStringPlusInt = StrExpr &&
11581 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11582 return;
11583
11584 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11585 Self.Diag(OpLoc, diag::warn_string_plus_int)
11586 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11587
11588 // Only print a fixit for "str" + int, not for int + "str".
11589 if (IndexExpr == RHSExpr) {
11590 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11591 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11592 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11594 << FixItHint::CreateInsertion(EndLoc, "]");
11595 } else
11596 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11597}
11598
11599/// Emit a warning when adding a char literal to a string.
11601 Expr *LHSExpr, Expr *RHSExpr) {
11602 const Expr *StringRefExpr = LHSExpr;
11603 const CharacterLiteral *CharExpr =
11604 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11605
11606 if (!CharExpr) {
11607 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11608 StringRefExpr = RHSExpr;
11609 }
11610
11611 if (!CharExpr || !StringRefExpr)
11612 return;
11613
11614 const QualType StringType = StringRefExpr->getType();
11615
11616 // Return if not a PointerType.
11617 if (!StringType->isAnyPointerType())
11618 return;
11619
11620 // Return if not a CharacterType.
11621 if (!StringType->getPointeeType()->isAnyCharacterType())
11622 return;
11623
11624 ASTContext &Ctx = Self.getASTContext();
11625 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11626
11627 const QualType CharType = CharExpr->getType();
11628 if (!CharType->isAnyCharacterType() &&
11629 CharType->isIntegerType() &&
11630 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11631 Self.Diag(OpLoc, diag::warn_string_plus_char)
11632 << DiagRange << Ctx.CharTy;
11633 } else {
11634 Self.Diag(OpLoc, diag::warn_string_plus_char)
11635 << DiagRange << CharExpr->getType();
11636 }
11637
11638 // Only print a fixit for str + char, not for char + str.
11639 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11640 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11641 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11642 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11644 << FixItHint::CreateInsertion(EndLoc, "]");
11645 } else {
11646 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11647 }
11648}
11649
11650/// Emit error when two pointers are incompatible.
11652 Expr *LHSExpr, Expr *RHSExpr) {
11653 assert(LHSExpr->getType()->isAnyPointerType());
11654 assert(RHSExpr->getType()->isAnyPointerType());
11655 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11656 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11657 << RHSExpr->getSourceRange();
11658}
11659
11660// C99 6.5.6
11663 QualType* CompLHSTy) {
11664 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11665
11666 if (LHS.get()->getType()->isVectorType() ||
11667 RHS.get()->getType()->isVectorType()) {
11668 QualType compType =
11669 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11670 /*AllowBothBool*/ getLangOpts().AltiVec,
11671 /*AllowBoolConversions*/ getLangOpts().ZVector,
11672 /*AllowBooleanOperation*/ false,
11673 /*ReportInvalid*/ true);
11674 if (CompLHSTy) *CompLHSTy = compType;
11675 return compType;
11676 }
11677
11678 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11679 RHS.get()->getType()->isSveVLSBuiltinType()) {
11680 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11682 if (CompLHSTy)
11683 *CompLHSTy = compType;
11684 return compType;
11685 }
11686
11687 if (LHS.get()->getType()->isConstantMatrixType() ||
11688 RHS.get()->getType()->isConstantMatrixType()) {
11689 QualType compType =
11690 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11691 if (CompLHSTy)
11692 *CompLHSTy = compType;
11693 return compType;
11694 }
11695
11697 LHS, RHS, Loc,
11699 if (LHS.isInvalid() || RHS.isInvalid())
11700 return QualType();
11701
11702 // Diagnose "string literal" '+' int and string '+' "char literal".
11703 if (Opc == BO_Add) {
11704 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11705 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11706 }
11707
11708 // handle the common case first (both operands are arithmetic).
11709 if (!compType.isNull() && compType->isArithmeticType()) {
11710 if (CompLHSTy) *CompLHSTy = compType;
11711 return compType;
11712 }
11713
11714 // Type-checking. Ultimately the pointer's going to be in PExp;
11715 // note that we bias towards the LHS being the pointer.
11716 Expr *PExp = LHS.get(), *IExp = RHS.get();
11717
11718 bool isObjCPointer;
11719 if (PExp->getType()->isPointerType()) {
11720 isObjCPointer = false;
11721 } else if (PExp->getType()->isObjCObjectPointerType()) {
11722 isObjCPointer = true;
11723 } else {
11724 std::swap(PExp, IExp);
11725 if (PExp->getType()->isPointerType()) {
11726 isObjCPointer = false;
11727 } else if (PExp->getType()->isObjCObjectPointerType()) {
11728 isObjCPointer = true;
11729 } else {
11730 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11731 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11732 return ResultTy;
11733 }
11734 }
11735 assert(PExp->getType()->isAnyPointerType());
11736
11737 if (!IExp->getType()->isIntegerType())
11738 return InvalidOperands(Loc, LHS, RHS);
11739
11740 // Adding to a null pointer results in undefined behavior.
11743 // In C++ adding zero to a null pointer is defined.
11744 Expr::EvalResult KnownVal;
11745 if (!getLangOpts().CPlusPlus ||
11746 (!IExp->isValueDependent() &&
11747 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11748 KnownVal.Val.getInt() != 0))) {
11749 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11751 Context, BO_Add, PExp, IExp);
11752 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11753 }
11754 }
11755
11756 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11757 return QualType();
11758
11759 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11760 return QualType();
11761
11762 // Arithmetic on label addresses is normally allowed, except when we add
11763 // a ptrauth signature to the addresses.
11764 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11765 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11766 << /*addition*/ 1;
11767 return QualType();
11768 }
11769
11770 // Check array bounds for pointer arithemtic
11771 CheckArrayAccess(PExp, IExp);
11772
11773 if (CompLHSTy) {
11774 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11775 if (LHSTy.isNull()) {
11776 LHSTy = LHS.get()->getType();
11777 if (Context.isPromotableIntegerType(LHSTy))
11778 LHSTy = Context.getPromotedIntegerType(LHSTy);
11779 }
11780 *CompLHSTy = LHSTy;
11781 }
11782
11783 return PExp->getType();
11784}
11785
11786// C99 6.5.6
11788 SourceLocation Loc,
11790 QualType *CompLHSTy) {
11791 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11792
11793 if (LHS.get()->getType()->isVectorType() ||
11794 RHS.get()->getType()->isVectorType()) {
11795 QualType compType =
11796 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11797 /*AllowBothBool*/ getLangOpts().AltiVec,
11798 /*AllowBoolConversions*/ getLangOpts().ZVector,
11799 /*AllowBooleanOperation*/ false,
11800 /*ReportInvalid*/ true);
11801 if (CompLHSTy) *CompLHSTy = compType;
11802 return compType;
11803 }
11804
11805 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11806 RHS.get()->getType()->isSveVLSBuiltinType()) {
11807 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11809 if (CompLHSTy)
11810 *CompLHSTy = compType;
11811 return compType;
11812 }
11813
11814 if (LHS.get()->getType()->isConstantMatrixType() ||
11815 RHS.get()->getType()->isConstantMatrixType()) {
11816 QualType compType =
11817 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11818 if (CompLHSTy)
11819 *CompLHSTy = compType;
11820 return compType;
11821 }
11822
11824 LHS, RHS, Loc,
11826 if (LHS.isInvalid() || RHS.isInvalid())
11827 return QualType();
11828
11829 // Enforce type constraints: C99 6.5.6p3.
11830
11831 // Handle the common case first (both operands are arithmetic).
11832 if (!compType.isNull() && compType->isArithmeticType()) {
11833 if (CompLHSTy) *CompLHSTy = compType;
11834 return compType;
11835 }
11836
11837 // Either ptr - int or ptr - ptr.
11838 if (LHS.get()->getType()->isAnyPointerType()) {
11839 QualType lpointee = LHS.get()->getType()->getPointeeType();
11840
11841 // Diagnose bad cases where we step over interface counts.
11842 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11843 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11844 return QualType();
11845
11846 // Arithmetic on label addresses is normally allowed, except when we add
11847 // a ptrauth signature to the addresses.
11848 if (isa<AddrLabelExpr>(LHS.get()) &&
11849 getLangOpts().PointerAuthIndirectGotos) {
11850 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11851 << /*subtraction*/ 0;
11852 return QualType();
11853 }
11854
11855 // The result type of a pointer-int computation is the pointer type.
11856 if (RHS.get()->getType()->isIntegerType()) {
11857 // Subtracting from a null pointer should produce a warning.
11858 // The last argument to the diagnose call says this doesn't match the
11859 // GNU int-to-pointer idiom.
11862 // In C++ adding zero to a null pointer is defined.
11863 Expr::EvalResult KnownVal;
11864 if (!getLangOpts().CPlusPlus ||
11865 (!RHS.get()->isValueDependent() &&
11866 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11867 KnownVal.Val.getInt() != 0))) {
11868 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11869 }
11870 }
11871
11872 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11873 return QualType();
11874
11875 // Check array bounds for pointer arithemtic
11876 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11877 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11878
11879 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11880 return LHS.get()->getType();
11881 }
11882
11883 // Handle pointer-pointer subtractions.
11884 if (const PointerType *RHSPTy
11885 = RHS.get()->getType()->getAs<PointerType>()) {
11886 QualType rpointee = RHSPTy->getPointeeType();
11887
11888 if (getLangOpts().CPlusPlus) {
11889 // Pointee types must be the same: C++ [expr.add]
11890 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11891 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11892 }
11893 } else {
11894 // Pointee types must be compatible C99 6.5.6p3
11895 if (!Context.typesAreCompatible(
11896 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11897 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11898 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11899 return QualType();
11900 }
11901 }
11902
11904 LHS.get(), RHS.get()))
11905 return QualType();
11906
11907 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11909 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11911
11912 // Subtracting nullptr or from nullptr is suspect
11913 if (LHSIsNullPtr)
11914 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11915 if (RHSIsNullPtr)
11916 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11917
11918 // The pointee type may have zero size. As an extension, a structure or
11919 // union may have zero size or an array may have zero length. In this
11920 // case subtraction does not make sense.
11921 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11922 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11923 if (ElementSize.isZero()) {
11924 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11925 << rpointee.getUnqualifiedType()
11926 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11927 }
11928 }
11929
11930 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11931 return Context.getPointerDiffType();
11932 }
11933 }
11934
11935 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11936 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11937 return ResultTy;
11938}
11939
11941 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11942 return ET->getDecl()->isScoped();
11943 return false;
11944}
11945
11948 QualType LHSType) {
11949 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11950 // so skip remaining warnings as we don't want to modify values within Sema.
11951 if (S.getLangOpts().OpenCL)
11952 return;
11953
11954 if (Opc == BO_Shr &&
11956 S.Diag(Loc, diag::warn_shift_bool) << LHS.get()->getSourceRange();
11957
11958 // Check right/shifter operand
11959 Expr::EvalResult RHSResult;
11960 if (RHS.get()->isValueDependent() ||
11961 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11962 return;
11963 llvm::APSInt Right = RHSResult.Val.getInt();
11964
11965 if (Right.isNegative()) {
11966 S.DiagRuntimeBehavior(Loc, RHS.get(),
11967 S.PDiag(diag::warn_shift_negative)
11968 << RHS.get()->getSourceRange());
11969 return;
11970 }
11971
11972 QualType LHSExprType = LHS.get()->getType();
11973 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11974 if (LHSExprType->isBitIntType())
11975 LeftSize = S.Context.getIntWidth(LHSExprType);
11976 else if (LHSExprType->isFixedPointType()) {
11977 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11978 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11979 }
11980 if (Right.uge(LeftSize)) {
11981 S.DiagRuntimeBehavior(Loc, RHS.get(),
11982 S.PDiag(diag::warn_shift_gt_typewidth)
11983 << RHS.get()->getSourceRange());
11984 return;
11985 }
11986
11987 // FIXME: We probably need to handle fixed point types specially here.
11988 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11989 return;
11990
11991 // When left shifting an ICE which is signed, we can check for overflow which
11992 // according to C++ standards prior to C++2a has undefined behavior
11993 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11994 // more than the maximum value representable in the result type, so never
11995 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11996 // expression is still probably a bug.)
11997 Expr::EvalResult LHSResult;
11998 if (LHS.get()->isValueDependent() ||
12000 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
12001 return;
12002 llvm::APSInt Left = LHSResult.Val.getInt();
12003
12004 // Don't warn if signed overflow is defined, then all the rest of the
12005 // diagnostics will not be triggered because the behavior is defined.
12006 // Also don't warn in C++20 mode (and newer), as signed left shifts
12007 // always wrap and never overflow.
12008 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
12009 return;
12010
12011 // If LHS does not have a non-negative value then, the
12012 // behavior is undefined before C++2a. Warn about it.
12013 if (Left.isNegative()) {
12014 S.DiagRuntimeBehavior(Loc, LHS.get(),
12015 S.PDiag(diag::warn_shift_lhs_negative)
12016 << LHS.get()->getSourceRange());
12017 return;
12018 }
12019
12020 llvm::APInt ResultBits =
12021 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12022 if (ResultBits.ule(LeftSize))
12023 return;
12024 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
12025 Result = Result.shl(Right);
12026
12027 // Print the bit representation of the signed integer as an unsigned
12028 // hexadecimal number.
12029 SmallString<40> HexResult;
12030 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
12031
12032 // If we are only missing a sign bit, this is less likely to result in actual
12033 // bugs -- if the result is cast back to an unsigned type, it will have the
12034 // expected value. Thus we place this behind a different warning that can be
12035 // turned off separately if needed.
12036 if (ResultBits - 1 == LeftSize) {
12037 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
12038 << HexResult << LHSType
12039 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12040 return;
12041 }
12042
12043 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
12044 << HexResult.str() << Result.getSignificantBits() << LHSType
12045 << Left.getBitWidth() << LHS.get()->getSourceRange()
12046 << RHS.get()->getSourceRange();
12047}
12048
12049/// Return the resulting type when a vector is shifted
12050/// by a scalar or vector shift amount.
12052 SourceLocation Loc, bool IsCompAssign) {
12053 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12054 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12055 !LHS.get()->getType()->isVectorType()) {
12056 S.Diag(Loc, diag::err_shift_rhs_only_vector)
12057 << RHS.get()->getType() << LHS.get()->getType()
12058 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12059 return QualType();
12060 }
12061
12062 if (!IsCompAssign) {
12063 LHS = S.UsualUnaryConversions(LHS.get());
12064 if (LHS.isInvalid()) return QualType();
12065 }
12066
12067 RHS = S.UsualUnaryConversions(RHS.get());
12068 if (RHS.isInvalid()) return QualType();
12069
12070 QualType LHSType = LHS.get()->getType();
12071 // Note that LHS might be a scalar because the routine calls not only in
12072 // OpenCL case.
12073 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12074 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12075
12076 // Note that RHS might not be a vector.
12077 QualType RHSType = RHS.get()->getType();
12078 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12079 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12080
12081 // Do not allow shifts for boolean vectors.
12082 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12083 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12084 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12085 << LHS.get()->getType() << RHS.get()->getType()
12086 << LHS.get()->getSourceRange();
12087 return QualType();
12088 }
12089
12090 // The operands need to be integers.
12091 if (!LHSEleType->isIntegerType()) {
12092 S.Diag(Loc, diag::err_typecheck_expect_int)
12093 << LHS.get()->getType() << LHS.get()->getSourceRange();
12094 return QualType();
12095 }
12096
12097 if (!RHSEleType->isIntegerType()) {
12098 S.Diag(Loc, diag::err_typecheck_expect_int)
12099 << RHS.get()->getType() << RHS.get()->getSourceRange();
12100 return QualType();
12101 }
12102
12103 if (!LHSVecTy) {
12104 assert(RHSVecTy);
12105 if (IsCompAssign)
12106 return RHSType;
12107 if (LHSEleType != RHSEleType) {
12108 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
12109 LHSEleType = RHSEleType;
12110 }
12111 QualType VecTy =
12112 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
12113 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
12114 LHSType = VecTy;
12115 } else if (RHSVecTy) {
12116 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12117 // are applied component-wise. So if RHS is a vector, then ensure
12118 // that the number of elements is the same as LHS...
12119 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12120 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12121 << LHS.get()->getType() << RHS.get()->getType()
12122 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12123 return QualType();
12124 }
12125 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12126 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12127 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12128 if (LHSBT != RHSBT &&
12129 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
12130 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
12131 << LHS.get()->getType() << RHS.get()->getType()
12132 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12133 }
12134 }
12135 } else {
12136 // ...else expand RHS to match the number of elements in LHS.
12137 QualType VecTy =
12138 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
12139 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12140 }
12141
12142 return LHSType;
12143}
12144
12146 ExprResult &RHS, SourceLocation Loc,
12147 bool IsCompAssign) {
12148 if (!IsCompAssign) {
12149 LHS = S.UsualUnaryConversions(LHS.get());
12150 if (LHS.isInvalid())
12151 return QualType();
12152 }
12153
12154 RHS = S.UsualUnaryConversions(RHS.get());
12155 if (RHS.isInvalid())
12156 return QualType();
12157
12158 QualType LHSType = LHS.get()->getType();
12159 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12160 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12161 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
12162 : LHSType;
12163
12164 // Note that RHS might not be a vector
12165 QualType RHSType = RHS.get()->getType();
12166 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12167 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12168 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
12169 : RHSType;
12170
12171 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12172 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12173 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12174 << LHSType << RHSType << LHS.get()->getSourceRange();
12175 return QualType();
12176 }
12177
12178 if (!LHSEleType->isIntegerType()) {
12179 S.Diag(Loc, diag::err_typecheck_expect_int)
12180 << LHS.get()->getType() << LHS.get()->getSourceRange();
12181 return QualType();
12182 }
12183
12184 if (!RHSEleType->isIntegerType()) {
12185 S.Diag(Loc, diag::err_typecheck_expect_int)
12186 << RHS.get()->getType() << RHS.get()->getSourceRange();
12187 return QualType();
12188 }
12189
12190 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12191 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
12192 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
12193 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12194 << LHSType << RHSType << LHS.get()->getSourceRange()
12195 << RHS.get()->getSourceRange();
12196 return QualType();
12197 }
12198
12199 if (!LHSType->isSveVLSBuiltinType()) {
12200 assert(RHSType->isSveVLSBuiltinType());
12201 if (IsCompAssign)
12202 return RHSType;
12203 if (LHSEleType != RHSEleType) {
12204 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
12205 LHSEleType = RHSEleType;
12206 }
12207 const llvm::ElementCount VecSize =
12208 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
12209 QualType VecTy =
12210 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
12211 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
12212 LHSType = VecTy;
12213 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12214 if (S.Context.getTypeSize(RHSBuiltinTy) !=
12215 S.Context.getTypeSize(LHSBuiltinTy)) {
12216 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12217 << LHSType << RHSType << LHS.get()->getSourceRange()
12218 << RHS.get()->getSourceRange();
12219 return QualType();
12220 }
12221 } else {
12222 const llvm::ElementCount VecSize =
12223 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
12224 if (LHSEleType != RHSEleType) {
12225 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
12226 RHSEleType = LHSEleType;
12227 }
12228 QualType VecTy =
12229 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
12230 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12231 }
12232
12233 return LHSType;
12234}
12235
12236// C99 6.5.7
12239 bool IsCompAssign) {
12240 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12241
12242 // Vector shifts promote their scalar inputs to vector type.
12243 if (LHS.get()->getType()->isVectorType() ||
12244 RHS.get()->getType()->isVectorType()) {
12245 if (LangOpts.ZVector) {
12246 // The shift operators for the z vector extensions work basically
12247 // like general shifts, except that neither the LHS nor the RHS is
12248 // allowed to be a "vector bool".
12249 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12250 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12251 return InvalidOperands(Loc, LHS, RHS);
12252 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12253 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12254 return InvalidOperands(Loc, LHS, RHS);
12255 }
12256 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12257 }
12258
12259 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12260 RHS.get()->getType()->isSveVLSBuiltinType())
12261 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12262
12263 // Shifts don't perform usual arithmetic conversions, they just do integer
12264 // promotions on each operand. C99 6.5.7p3
12265
12266 // For the LHS, do usual unary conversions, but then reset them away
12267 // if this is a compound assignment.
12268 ExprResult OldLHS = LHS;
12269 LHS = UsualUnaryConversions(LHS.get());
12270 if (LHS.isInvalid())
12271 return QualType();
12272 QualType LHSType = LHS.get()->getType();
12273 if (IsCompAssign) LHS = OldLHS;
12274
12275 // The RHS is simpler.
12276 RHS = UsualUnaryConversions(RHS.get());
12277 if (RHS.isInvalid())
12278 return QualType();
12279 QualType RHSType = RHS.get()->getType();
12280
12281 // C99 6.5.7p2: Each of the operands shall have integer type.
12282 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12283 if ((!LHSType->isFixedPointOrIntegerType() &&
12284 !LHSType->hasIntegerRepresentation()) ||
12285 !RHSType->hasIntegerRepresentation()) {
12286 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12287 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
12288 return ResultTy;
12289 }
12290
12291 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12292
12293 // "The type of the result is that of the promoted left operand."
12294 return LHSType;
12295}
12296
12297/// Diagnose bad pointer comparisons.
12299 ExprResult &LHS, ExprResult &RHS,
12300 bool IsError) {
12301 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12302 : diag::ext_typecheck_comparison_of_distinct_pointers)
12303 << LHS.get()->getType() << RHS.get()->getType()
12304 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12305}
12306
12307/// Returns false if the pointers are converted to a composite type,
12308/// true otherwise.
12310 ExprResult &LHS, ExprResult &RHS) {
12311 // C++ [expr.rel]p2:
12312 // [...] Pointer conversions (4.10) and qualification
12313 // conversions (4.4) are performed on pointer operands (or on
12314 // a pointer operand and a null pointer constant) to bring
12315 // them to their composite pointer type. [...]
12316 //
12317 // C++ [expr.eq]p1 uses the same notion for (in)equality
12318 // comparisons of pointers.
12319
12320 QualType LHSType = LHS.get()->getType();
12321 QualType RHSType = RHS.get()->getType();
12322 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12323 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12324
12325 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12326 if (T.isNull()) {
12327 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12328 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12329 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12330 else
12331 S.InvalidOperands(Loc, LHS, RHS);
12332 return true;
12333 }
12334
12335 return false;
12336}
12337
12339 ExprResult &LHS,
12340 ExprResult &RHS,
12341 bool IsError) {
12342 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12343 : diag::ext_typecheck_comparison_of_fptr_to_void)
12344 << LHS.get()->getType() << RHS.get()->getType()
12345 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12346}
12347
12349 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12350 case Stmt::ObjCArrayLiteralClass:
12351 case Stmt::ObjCDictionaryLiteralClass:
12352 case Stmt::ObjCStringLiteralClass:
12353 case Stmt::ObjCBoxedExprClass:
12354 return true;
12355 default:
12356 // Note that ObjCBoolLiteral is NOT an object literal!
12357 return false;
12358 }
12359}
12360
12361static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12364
12365 // If this is not actually an Objective-C object, bail out.
12366 if (!Type)
12367 return false;
12368
12369 // Get the LHS object's interface type.
12370 QualType InterfaceType = Type->getPointeeType();
12371
12372 // If the RHS isn't an Objective-C object, bail out.
12373 if (!RHS->getType()->isObjCObjectPointerType())
12374 return false;
12375
12376 // Try to find the -isEqual: method.
12377 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12378 ObjCMethodDecl *Method =
12379 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
12380 /*IsInstance=*/true);
12381 if (!Method) {
12382 if (Type->isObjCIdType()) {
12383 // For 'id', just check the global pool.
12384 Method =
12386 /*receiverId=*/true);
12387 } else {
12388 // Check protocols.
12389 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
12390 /*IsInstance=*/true);
12391 }
12392 }
12393
12394 if (!Method)
12395 return false;
12396
12397 QualType T = Method->parameters()[0]->getType();
12398 if (!T->isObjCObjectPointerType())
12399 return false;
12400
12401 QualType R = Method->getReturnType();
12402 if (!R->isScalarType())
12403 return false;
12404
12405 return true;
12406}
12407
12409 ExprResult &LHS, ExprResult &RHS,
12411 Expr *Literal;
12412 Expr *Other;
12413 if (isObjCObjectLiteral(LHS)) {
12414 Literal = LHS.get();
12415 Other = RHS.get();
12416 } else {
12417 Literal = RHS.get();
12418 Other = LHS.get();
12419 }
12420
12421 // Don't warn on comparisons against nil.
12422 Other = Other->IgnoreParenCasts();
12423 if (Other->isNullPointerConstant(S.getASTContext(),
12425 return;
12426
12427 // This should be kept in sync with warn_objc_literal_comparison.
12428 // LK_String should always be after the other literals, since it has its own
12429 // warning flag.
12430 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
12431 assert(LiteralKind != SemaObjC::LK_Block);
12432 if (LiteralKind == SemaObjC::LK_None) {
12433 llvm_unreachable("Unknown Objective-C object literal kind");
12434 }
12435
12436 if (LiteralKind == SemaObjC::LK_String)
12437 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12438 << Literal->getSourceRange();
12439 else
12440 S.Diag(Loc, diag::warn_objc_literal_comparison)
12441 << LiteralKind << Literal->getSourceRange();
12442
12444 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12445 SourceLocation Start = LHS.get()->getBeginLoc();
12447 CharSourceRange OpRange =
12449
12450 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12451 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12452 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12453 << FixItHint::CreateInsertion(End, "]");
12454 }
12455}
12456
12457/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12459 ExprResult &RHS, SourceLocation Loc,
12460 BinaryOperatorKind Opc) {
12461 // Check that left hand side is !something.
12462 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12463 if (!UO || UO->getOpcode() != UO_LNot) return;
12464
12465 // Only check if the right hand side is non-bool arithmetic type.
12466 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12467
12468 // Make sure that the something in !something is not bool.
12469 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12470 if (SubExpr->isKnownToHaveBooleanValue()) return;
12471
12472 // Emit warning.
12473 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12474 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12475 << Loc << IsBitwiseOp;
12476
12477 // First note suggest !(x < y)
12478 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12479 SourceLocation FirstClose = RHS.get()->getEndLoc();
12480 FirstClose = S.getLocForEndOfToken(FirstClose);
12481 if (FirstClose.isInvalid())
12482 FirstOpen = SourceLocation();
12483 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12484 << IsBitwiseOp
12485 << FixItHint::CreateInsertion(FirstOpen, "(")
12486 << FixItHint::CreateInsertion(FirstClose, ")");
12487
12488 // Second note suggests (!x) < y
12489 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12490 SourceLocation SecondClose = LHS.get()->getEndLoc();
12491 SecondClose = S.getLocForEndOfToken(SecondClose);
12492 if (SecondClose.isInvalid())
12493 SecondOpen = SourceLocation();
12494 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12495 << FixItHint::CreateInsertion(SecondOpen, "(")
12496 << FixItHint::CreateInsertion(SecondClose, ")");
12497}
12498
12499// Returns true if E refers to a non-weak array.
12500static bool checkForArray(const Expr *E) {
12501 const ValueDecl *D = nullptr;
12502 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12503 D = DR->getDecl();
12504 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12505 if (Mem->isImplicitAccess())
12506 D = Mem->getMemberDecl();
12507 }
12508 if (!D)
12509 return false;
12510 return D->getType()->isArrayType() && !D->isWeak();
12511}
12512
12513/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12514/// pointer and size is an unsigned integer. Return whether the result is
12515/// always true/false.
12516static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12517 const Expr *RHS,
12518 BinaryOperatorKind Opc) {
12519 if (!LHS->getType()->isPointerType() ||
12520 S.getLangOpts().PointerOverflowDefined)
12521 return std::nullopt;
12522
12523 // Canonicalize to >= or < predicate.
12524 switch (Opc) {
12525 case BO_GE:
12526 case BO_LT:
12527 break;
12528 case BO_GT:
12529 std::swap(LHS, RHS);
12530 Opc = BO_LT;
12531 break;
12532 case BO_LE:
12533 std::swap(LHS, RHS);
12534 Opc = BO_GE;
12535 break;
12536 default:
12537 return std::nullopt;
12538 }
12539
12540 auto *BO = dyn_cast<BinaryOperator>(LHS);
12541 if (!BO || BO->getOpcode() != BO_Add)
12542 return std::nullopt;
12543
12544 Expr *Other;
12545 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
12546 Other = BO->getRHS();
12547 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
12548 Other = BO->getLHS();
12549 else
12550 return std::nullopt;
12551
12552 if (!Other->getType()->isUnsignedIntegerType())
12553 return std::nullopt;
12554
12555 return Opc == BO_GE;
12556}
12557
12558/// Diagnose some forms of syntactically-obvious tautological comparison.
12560 Expr *LHS, Expr *RHS,
12561 BinaryOperatorKind Opc) {
12562 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12563 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12564
12565 QualType LHSType = LHS->getType();
12566 QualType RHSType = RHS->getType();
12567 if (LHSType->hasFloatingRepresentation() ||
12568 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12570 return;
12571
12572 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12573 // Tautological diagnostics.
12574 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12575 return;
12576
12577 // Comparisons between two array types are ill-formed for operator<=>, so
12578 // we shouldn't emit any additional warnings about it.
12579 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12580 return;
12581
12582 // For non-floating point types, check for self-comparisons of the form
12583 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12584 // often indicate logic errors in the program.
12585 //
12586 // NOTE: Don't warn about comparison expressions resulting from macro
12587 // expansion. Also don't warn about comparisons which are only self
12588 // comparisons within a template instantiation. The warnings should catch
12589 // obvious cases in the definition of the template anyways. The idea is to
12590 // warn when the typed comparison operator will always evaluate to the same
12591 // result.
12592
12593 // Used for indexing into %select in warn_comparison_always
12594 enum {
12595 AlwaysConstant,
12596 AlwaysTrue,
12597 AlwaysFalse,
12598 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12599 };
12600
12601 // C++1a [array.comp]:
12602 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12603 // operands of array type.
12604 // C++2a [depr.array.comp]:
12605 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12606 // operands of array type are deprecated.
12607 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12608 RHSStripped->getType()->isArrayType()) {
12609 auto IsDeprArrayComparionIgnored =
12610 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
12611 auto DiagID = S.getLangOpts().CPlusPlus26
12612 ? diag::warn_array_comparison_cxx26
12613 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12614 ? diag::warn_array_comparison
12615 : diag::warn_depr_array_comparison;
12616 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12617 << LHSStripped->getType() << RHSStripped->getType();
12618 // Carry on to produce the tautological comparison warning, if this
12619 // expression is potentially-evaluated, we can resolve the array to a
12620 // non-weak declaration, and so on.
12621 }
12622
12623 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12624 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12625 unsigned Result;
12626 switch (Opc) {
12627 case BO_EQ:
12628 case BO_LE:
12629 case BO_GE:
12630 Result = AlwaysTrue;
12631 break;
12632 case BO_NE:
12633 case BO_LT:
12634 case BO_GT:
12635 Result = AlwaysFalse;
12636 break;
12637 case BO_Cmp:
12638 Result = AlwaysEqual;
12639 break;
12640 default:
12641 Result = AlwaysConstant;
12642 break;
12643 }
12644 S.DiagRuntimeBehavior(Loc, nullptr,
12645 S.PDiag(diag::warn_comparison_always)
12646 << 0 /*self-comparison*/
12647 << Result);
12648 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12649 // What is it always going to evaluate to?
12650 unsigned Result;
12651 switch (Opc) {
12652 case BO_EQ: // e.g. array1 == array2
12653 Result = AlwaysFalse;
12654 break;
12655 case BO_NE: // e.g. array1 != array2
12656 Result = AlwaysTrue;
12657 break;
12658 default: // e.g. array1 <= array2
12659 // The best we can say is 'a constant'
12660 Result = AlwaysConstant;
12661 break;
12662 }
12663 S.DiagRuntimeBehavior(Loc, nullptr,
12664 S.PDiag(diag::warn_comparison_always)
12665 << 1 /*array comparison*/
12666 << Result);
12667 } else if (std::optional<bool> Res =
12668 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12669 S.DiagRuntimeBehavior(Loc, nullptr,
12670 S.PDiag(diag::warn_comparison_always)
12671 << 2 /*pointer comparison*/
12672 << (*Res ? AlwaysTrue : AlwaysFalse));
12673 }
12674 }
12675
12676 if (isa<CastExpr>(LHSStripped))
12677 LHSStripped = LHSStripped->IgnoreParenCasts();
12678 if (isa<CastExpr>(RHSStripped))
12679 RHSStripped = RHSStripped->IgnoreParenCasts();
12680
12681 // Warn about comparisons against a string constant (unless the other
12682 // operand is null); the user probably wants string comparison function.
12683 Expr *LiteralString = nullptr;
12684 Expr *LiteralStringStripped = nullptr;
12685 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12686 !RHSStripped->isNullPointerConstant(S.Context,
12688 LiteralString = LHS;
12689 LiteralStringStripped = LHSStripped;
12690 } else if ((isa<StringLiteral>(RHSStripped) ||
12691 isa<ObjCEncodeExpr>(RHSStripped)) &&
12692 !LHSStripped->isNullPointerConstant(S.Context,
12694 LiteralString = RHS;
12695 LiteralStringStripped = RHSStripped;
12696 }
12697
12698 if (LiteralString) {
12699 S.DiagRuntimeBehavior(Loc, nullptr,
12700 S.PDiag(diag::warn_stringcompare)
12701 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12702 << LiteralString->getSourceRange());
12703 }
12704}
12705
12707 switch (CK) {
12708 default: {
12709#ifndef NDEBUG
12710 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12711 << "\n";
12712#endif
12713 llvm_unreachable("unhandled cast kind");
12714 }
12715 case CK_UserDefinedConversion:
12716 return ICK_Identity;
12717 case CK_LValueToRValue:
12718 return ICK_Lvalue_To_Rvalue;
12719 case CK_ArrayToPointerDecay:
12720 return ICK_Array_To_Pointer;
12721 case CK_FunctionToPointerDecay:
12723 case CK_IntegralCast:
12725 case CK_FloatingCast:
12727 case CK_IntegralToFloating:
12728 case CK_FloatingToIntegral:
12729 return ICK_Floating_Integral;
12730 case CK_IntegralComplexCast:
12731 case CK_FloatingComplexCast:
12732 case CK_FloatingComplexToIntegralComplex:
12733 case CK_IntegralComplexToFloatingComplex:
12735 case CK_FloatingComplexToReal:
12736 case CK_FloatingRealToComplex:
12737 case CK_IntegralComplexToReal:
12738 case CK_IntegralRealToComplex:
12739 return ICK_Complex_Real;
12740 case CK_HLSLArrayRValue:
12741 return ICK_HLSL_Array_RValue;
12742 }
12743}
12744
12746 QualType FromType,
12747 SourceLocation Loc) {
12748 // Check for a narrowing implicit conversion.
12751 SCS.setToType(0, FromType);
12752 SCS.setToType(1, ToType);
12753 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12754 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12755
12756 APValue PreNarrowingValue;
12757 QualType PreNarrowingType;
12758 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12759 PreNarrowingType,
12760 /*IgnoreFloatToIntegralConversion*/ true)) {
12762 // Implicit conversion to a narrower type, but the expression is
12763 // value-dependent so we can't tell whether it's actually narrowing.
12764 case NK_Not_Narrowing:
12765 return false;
12766
12768 // Implicit conversion to a narrower type, and the value is not a constant
12769 // expression.
12770 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12771 << /*Constant*/ 1
12772 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12773 return true;
12774
12776 // Implicit conversion to a narrower type, and the value is not a constant
12777 // expression.
12778 case NK_Type_Narrowing:
12779 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12780 << /*Constant*/ 0 << FromType << ToType;
12781 // TODO: It's not a constant expression, but what if the user intended it
12782 // to be? Can we produce notes to help them figure out why it isn't?
12783 return true;
12784 }
12785 llvm_unreachable("unhandled case in switch");
12786}
12787
12789 ExprResult &LHS,
12790 ExprResult &RHS,
12791 SourceLocation Loc) {
12792 QualType LHSType = LHS.get()->getType();
12793 QualType RHSType = RHS.get()->getType();
12794 // Dig out the original argument type and expression before implicit casts
12795 // were applied. These are the types/expressions we need to check the
12796 // [expr.spaceship] requirements against.
12797 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12798 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12799 QualType LHSStrippedType = LHSStripped.get()->getType();
12800 QualType RHSStrippedType = RHSStripped.get()->getType();
12801
12802 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12803 // other is not, the program is ill-formed.
12804 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12805 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12806 return QualType();
12807 }
12808
12809 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12810 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12811 RHSStrippedType->isEnumeralType();
12812 if (NumEnumArgs == 1) {
12813 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12814 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12815 if (OtherTy->hasFloatingRepresentation()) {
12816 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12817 return QualType();
12818 }
12819 }
12820 if (NumEnumArgs == 2) {
12821 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12822 // type E, the operator yields the result of converting the operands
12823 // to the underlying type of E and applying <=> to the converted operands.
12824 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12825 S.InvalidOperands(Loc, LHS, RHS);
12826 return QualType();
12827 }
12828 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12829 assert(IntType->isArithmeticType());
12830
12831 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12832 // promote the boolean type, and all other promotable integer types, to
12833 // avoid this.
12834 if (S.Context.isPromotableIntegerType(IntType))
12835 IntType = S.Context.getPromotedIntegerType(IntType);
12836
12837 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12838 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12839 LHSType = RHSType = IntType;
12840 }
12841
12842 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12843 // usual arithmetic conversions are applied to the operands.
12844 QualType Type =
12846 if (LHS.isInvalid() || RHS.isInvalid())
12847 return QualType();
12848 if (Type.isNull()) {
12849 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12850 diagnoseScopedEnums(S, Loc, LHS, RHS, BO_Cmp);
12851 return ResultTy;
12852 }
12853
12854 std::optional<ComparisonCategoryType> CCT =
12856 if (!CCT)
12857 return S.InvalidOperands(Loc, LHS, RHS);
12858
12859 bool HasNarrowing = checkThreeWayNarrowingConversion(
12860 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12861 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12862 RHS.get()->getBeginLoc());
12863 if (HasNarrowing)
12864 return QualType();
12865
12866 assert(!Type.isNull() && "composite type for <=> has not been set");
12867
12870}
12871
12873 ExprResult &RHS,
12874 SourceLocation Loc,
12875 BinaryOperatorKind Opc) {
12876 if (Opc == BO_Cmp)
12877 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12878
12879 // C99 6.5.8p3 / C99 6.5.9p4
12880 QualType Type =
12882 if (LHS.isInvalid() || RHS.isInvalid())
12883 return QualType();
12884 if (Type.isNull()) {
12885 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12886 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12887 return ResultTy;
12888 }
12889 assert(Type->isArithmeticType() || Type->isEnumeralType());
12890
12892 return S.InvalidOperands(Loc, LHS, RHS);
12893
12894 // Check for comparisons of floating point operands using != and ==.
12896 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12897
12898 // The result of comparisons is 'bool' in C++, 'int' in C.
12900}
12901
12903 if (!NullE.get()->getType()->isAnyPointerType())
12904 return;
12905 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12906 if (!E.get()->getType()->isAnyPointerType() &&
12910 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12911 if (CL->getValue() == 0)
12912 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12913 << NullValue
12915 NullValue ? "NULL" : "(void *)0");
12916 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12917 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12918 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12919 if (T == Context.CharTy)
12920 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12921 << NullValue
12923 NullValue ? "NULL" : "(void *)0");
12924 }
12925 }
12926}
12927
12928// C99 6.5.8, C++ [expr.rel]
12930 SourceLocation Loc,
12931 BinaryOperatorKind Opc) {
12932 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12933 bool IsThreeWay = Opc == BO_Cmp;
12934 bool IsOrdered = IsRelational || IsThreeWay;
12935 auto IsAnyPointerType = [](ExprResult E) {
12936 QualType Ty = E.get()->getType();
12937 return Ty->isPointerType() || Ty->isMemberPointerType();
12938 };
12939
12940 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12941 // type, array-to-pointer, ..., conversions are performed on both operands to
12942 // bring them to their composite type.
12943 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12944 // any type-related checks.
12945 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12947 if (LHS.isInvalid())
12948 return QualType();
12950 if (RHS.isInvalid())
12951 return QualType();
12952 } else {
12953 LHS = DefaultLvalueConversion(LHS.get());
12954 if (LHS.isInvalid())
12955 return QualType();
12956 RHS = DefaultLvalueConversion(RHS.get());
12957 if (RHS.isInvalid())
12958 return QualType();
12959 }
12960
12961 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12965 }
12966
12967 // Handle vector comparisons separately.
12968 if (LHS.get()->getType()->isVectorType() ||
12969 RHS.get()->getType()->isVectorType())
12970 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12971
12972 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12973 RHS.get()->getType()->isSveVLSBuiltinType())
12974 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12975
12976 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12977 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12978
12979 QualType LHSType = LHS.get()->getType();
12980 QualType RHSType = RHS.get()->getType();
12981 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12982 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12983 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12984
12985 if ((LHSType->isPointerType() &&
12987 (RHSType->isPointerType() &&
12989 return InvalidOperands(Loc, LHS, RHS);
12990
12991 const Expr::NullPointerConstantKind LHSNullKind =
12993 const Expr::NullPointerConstantKind RHSNullKind =
12995 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12996 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12997
12998 auto computeResultTy = [&]() {
12999 if (Opc != BO_Cmp)
13000 return QualType(Context.getLogicalOperationType());
13001 assert(getLangOpts().CPlusPlus);
13002 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
13003
13004 QualType CompositeTy = LHS.get()->getType();
13005 assert(!CompositeTy->isReferenceType());
13006
13007 std::optional<ComparisonCategoryType> CCT =
13009 if (!CCT)
13010 return InvalidOperands(Loc, LHS, RHS);
13011
13012 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
13013 // P0946R0: Comparisons between a null pointer constant and an object
13014 // pointer result in std::strong_equality, which is ill-formed under
13015 // P1959R0.
13016 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
13017 << (LHSIsNull ? LHS.get()->getSourceRange()
13018 : RHS.get()->getSourceRange());
13019 return QualType();
13020 }
13021
13024 };
13025
13026 if (!IsOrdered && LHSIsNull != RHSIsNull) {
13027 bool IsEquality = Opc == BO_EQ;
13028 if (RHSIsNull)
13029 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
13030 RHS.get()->getSourceRange());
13031 else
13032 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
13033 LHS.get()->getSourceRange());
13034 }
13035
13036 if (IsOrdered && LHSType->isFunctionPointerType() &&
13037 RHSType->isFunctionPointerType()) {
13038 // Valid unless a relational comparison of function pointers
13039 bool IsError = Opc == BO_Cmp;
13040 auto DiagID =
13041 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13042 : getLangOpts().CPlusPlus
13043 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13044 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13045 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13046 << RHS.get()->getSourceRange();
13047 if (IsError)
13048 return QualType();
13049 }
13050
13051 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13052 (RHSType->isIntegerType() && !RHSIsNull)) {
13053 // Skip normal pointer conversion checks in this case; we have better
13054 // diagnostics for this below.
13055 } else if (getLangOpts().CPlusPlus) {
13056 // Equality comparison of a function pointer to a void pointer is invalid,
13057 // but we allow it as an extension.
13058 // FIXME: If we really want to allow this, should it be part of composite
13059 // pointer type computation so it works in conditionals too?
13060 if (!IsOrdered &&
13061 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13062 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13063 // This is a gcc extension compatibility comparison.
13064 // In a SFINAE context, we treat this as a hard error to maintain
13065 // conformance with the C++ standard.
13066 bool IsError = isSFINAEContext();
13067 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, IsError);
13068
13069 if (IsError)
13070 return QualType();
13071
13072 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13073 return computeResultTy();
13074 }
13075
13076 // C++ [expr.eq]p2:
13077 // If at least one operand is a pointer [...] bring them to their
13078 // composite pointer type.
13079 // C++ [expr.spaceship]p6
13080 // If at least one of the operands is of pointer type, [...] bring them
13081 // to their composite pointer type.
13082 // C++ [expr.rel]p2:
13083 // If both operands are pointers, [...] bring them to their composite
13084 // pointer type.
13085 // For <=>, the only valid non-pointer types are arrays and functions, and
13086 // we already decayed those, so this is really the same as the relational
13087 // comparison rule.
13088 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13089 (IsOrdered ? 2 : 1) &&
13090 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13091 RHSType->isObjCObjectPointerType()))) {
13092 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13093 return QualType();
13094 return computeResultTy();
13095 }
13096 } else if (LHSType->isPointerType() &&
13097 RHSType->isPointerType()) { // C99 6.5.8p2
13098 // All of the following pointer-related warnings are GCC extensions, except
13099 // when handling null pointer constants.
13100 QualType LCanPointeeTy =
13102 QualType RCanPointeeTy =
13104
13105 // C99 6.5.9p2 and C99 6.5.8p2
13106 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
13107 RCanPointeeTy.getUnqualifiedType())) {
13108 if (IsRelational) {
13109 // Pointers both need to point to complete or incomplete types
13110 if ((LCanPointeeTy->isIncompleteType() !=
13111 RCanPointeeTy->isIncompleteType()) &&
13112 !getLangOpts().C11) {
13113 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
13114 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13115 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13116 << RCanPointeeTy->isIncompleteType();
13117 }
13118 }
13119 } else if (!IsRelational &&
13120 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13121 // Valid unless comparison between non-null pointer and function pointer
13122 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13123 && !LHSIsNull && !RHSIsNull)
13124 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
13125 /*isError*/false);
13126 } else {
13127 // Invalid
13128 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
13129 }
13130 if (LCanPointeeTy != RCanPointeeTy) {
13131 // Treat NULL constant as a special case in OpenCL.
13132 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13133 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
13134 getASTContext())) {
13135 Diag(Loc,
13136 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13137 << LHSType << RHSType << 0 /* comparison */
13138 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13139 }
13140 }
13141 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13142 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13143 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13144 : CK_BitCast;
13145
13146 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13147 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13148 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13149 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13150 bool ChangingCFIUncheckedCallee =
13151 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13152
13153 if (LHSIsNull && !RHSIsNull)
13154 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
13155 else if (!ChangingCFIUncheckedCallee)
13156 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
13157 }
13158 return computeResultTy();
13159 }
13160
13161
13162 // C++ [expr.eq]p4:
13163 // Two operands of type std::nullptr_t or one operand of type
13164 // std::nullptr_t and the other a null pointer constant compare
13165 // equal.
13166 // C23 6.5.9p5:
13167 // If both operands have type nullptr_t or one operand has type nullptr_t
13168 // and the other is a null pointer constant, they compare equal if the
13169 // former is a null pointer.
13170 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13171 if (LHSType->isNullPtrType()) {
13172 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13173 return computeResultTy();
13174 }
13175 if (RHSType->isNullPtrType()) {
13176 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13177 return computeResultTy();
13178 }
13179 }
13180
13181 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13182 // C23 6.5.9p6:
13183 // Otherwise, at least one operand is a pointer. If one is a pointer and
13184 // the other is a null pointer constant or has type nullptr_t, they
13185 // compare equal
13186 if (LHSIsNull && RHSType->isPointerType()) {
13187 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13188 return computeResultTy();
13189 }
13190 if (RHSIsNull && LHSType->isPointerType()) {
13191 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13192 return computeResultTy();
13193 }
13194 }
13195
13196 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13197 // These aren't covered by the composite pointer type rules.
13198 if (!IsOrdered && RHSType->isNullPtrType() &&
13199 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13200 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13201 return computeResultTy();
13202 }
13203 if (!IsOrdered && LHSType->isNullPtrType() &&
13204 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13205 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13206 return computeResultTy();
13207 }
13208
13209 if (getLangOpts().CPlusPlus) {
13210 if (IsRelational &&
13211 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13212 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13213 // HACK: Relational comparison of nullptr_t against a pointer type is
13214 // invalid per DR583, but we allow it within std::less<> and friends,
13215 // since otherwise common uses of it break.
13216 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13217 // friends to have std::nullptr_t overload candidates.
13218 DeclContext *DC = CurContext;
13219 if (isa<FunctionDecl>(DC))
13220 DC = DC->getParent();
13221 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
13222 if (CTSD->isInStdNamespace() &&
13223 llvm::StringSwitch<bool>(CTSD->getName())
13224 .Cases({"less", "less_equal", "greater", "greater_equal"}, true)
13225 .Default(false)) {
13226 if (RHSType->isNullPtrType())
13227 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13228 else
13229 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13230 return computeResultTy();
13231 }
13232 }
13233 }
13234
13235 // C++ [expr.eq]p2:
13236 // If at least one operand is a pointer to member, [...] bring them to
13237 // their composite pointer type.
13238 if (!IsOrdered &&
13239 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13240 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13241 return QualType();
13242 else
13243 return computeResultTy();
13244 }
13245 }
13246
13247 // Handle block pointer types.
13248 if (!IsOrdered && LHSType->isBlockPointerType() &&
13249 RHSType->isBlockPointerType()) {
13250 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13251 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13252
13253 if (!LHSIsNull && !RHSIsNull &&
13254 !Context.typesAreCompatible(lpointee, rpointee)) {
13255 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13256 << LHSType << RHSType << LHS.get()->getSourceRange()
13257 << RHS.get()->getSourceRange();
13258 }
13259 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13260 return computeResultTy();
13261 }
13262
13263 // Allow block pointers to be compared with null pointer constants.
13264 if (!IsOrdered
13265 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13266 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13267 if (!LHSIsNull && !RHSIsNull) {
13268 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13270 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13271 ->getPointeeType()->isVoidType())))
13272 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13273 << LHSType << RHSType << LHS.get()->getSourceRange()
13274 << RHS.get()->getSourceRange();
13275 }
13276 if (LHSIsNull && !RHSIsNull)
13277 LHS = ImpCastExprToType(LHS.get(), RHSType,
13278 RHSType->isPointerType() ? CK_BitCast
13279 : CK_AnyPointerToBlockPointerCast);
13280 else
13281 RHS = ImpCastExprToType(RHS.get(), LHSType,
13282 LHSType->isPointerType() ? CK_BitCast
13283 : CK_AnyPointerToBlockPointerCast);
13284 return computeResultTy();
13285 }
13286
13287 if (LHSType->isObjCObjectPointerType() ||
13288 RHSType->isObjCObjectPointerType()) {
13289 const PointerType *LPT = LHSType->getAs<PointerType>();
13290 const PointerType *RPT = RHSType->getAs<PointerType>();
13291 if (LPT || RPT) {
13292 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13293 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13294
13295 if (!LPtrToVoid && !RPtrToVoid &&
13296 !Context.typesAreCompatible(LHSType, RHSType)) {
13297 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13298 /*isError*/false);
13299 }
13300 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13301 // the RHS, but we have test coverage for this behavior.
13302 // FIXME: Consider using convertPointersToCompositeType in C++.
13303 if (LHSIsNull && !RHSIsNull) {
13304 Expr *E = LHS.get();
13305 if (getLangOpts().ObjCAutoRefCount)
13306 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
13308 LHS = ImpCastExprToType(E, RHSType,
13309 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13310 }
13311 else {
13312 Expr *E = RHS.get();
13313 if (getLangOpts().ObjCAutoRefCount)
13314 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
13316 /*Diagnose=*/true,
13317 /*DiagnoseCFAudited=*/false, Opc);
13318 RHS = ImpCastExprToType(E, LHSType,
13319 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13320 }
13321 return computeResultTy();
13322 }
13323 if (LHSType->isObjCObjectPointerType() &&
13324 RHSType->isObjCObjectPointerType()) {
13325 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13326 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13327 /*isError*/false);
13329 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13330
13331 if (LHSIsNull && !RHSIsNull)
13332 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13333 else
13334 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13335 return computeResultTy();
13336 }
13337
13338 if (!IsOrdered && LHSType->isBlockPointerType() &&
13340 LHS = ImpCastExprToType(LHS.get(), RHSType,
13341 CK_BlockPointerToObjCPointerCast);
13342 return computeResultTy();
13343 } else if (!IsOrdered &&
13345 RHSType->isBlockPointerType()) {
13346 RHS = ImpCastExprToType(RHS.get(), LHSType,
13347 CK_BlockPointerToObjCPointerCast);
13348 return computeResultTy();
13349 }
13350 }
13351 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13352 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13353 unsigned DiagID = 0;
13354 bool isError = false;
13355 if (LangOpts.DebuggerSupport) {
13356 // Under a debugger, allow the comparison of pointers to integers,
13357 // since users tend to want to compare addresses.
13358 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13359 (RHSIsNull && RHSType->isIntegerType())) {
13360 if (IsOrdered) {
13361 isError = getLangOpts().CPlusPlus;
13362 DiagID =
13363 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13364 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13365 }
13366 } else if (getLangOpts().CPlusPlus) {
13367 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13368 isError = true;
13369 } else if (IsOrdered)
13370 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13371 else
13372 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13373
13374 if (DiagID) {
13375 Diag(Loc, DiagID)
13376 << LHSType << RHSType << LHS.get()->getSourceRange()
13377 << RHS.get()->getSourceRange();
13378 if (isError)
13379 return QualType();
13380 }
13381
13382 if (LHSType->isIntegerType())
13383 LHS = ImpCastExprToType(LHS.get(), RHSType,
13384 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13385 else
13386 RHS = ImpCastExprToType(RHS.get(), LHSType,
13387 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13388 return computeResultTy();
13389 }
13390
13391 // Handle block pointers.
13392 if (!IsOrdered && RHSIsNull
13393 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13394 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13395 return computeResultTy();
13396 }
13397 if (!IsOrdered && LHSIsNull
13398 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13399 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13400 return computeResultTy();
13401 }
13402
13403 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13404 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13405 return computeResultTy();
13406 }
13407
13408 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13409 return computeResultTy();
13410 }
13411
13412 if (LHSIsNull && RHSType->isQueueT()) {
13413 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13414 return computeResultTy();
13415 }
13416
13417 if (LHSType->isQueueT() && RHSIsNull) {
13418 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13419 return computeResultTy();
13420 }
13421 }
13422
13423 return InvalidOperands(Loc, LHS, RHS);
13424}
13425
13427 const VectorType *VTy = V->castAs<VectorType>();
13428 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13429
13430 if (isa<ExtVectorType>(VTy)) {
13431 if (VTy->isExtVectorBoolType())
13432 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13433 if (TypeSize == Context.getTypeSize(Context.CharTy))
13434 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13435 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13436 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13437 if (TypeSize == Context.getTypeSize(Context.IntTy))
13438 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13439 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13440 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13441 if (TypeSize == Context.getTypeSize(Context.LongTy))
13442 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13443 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13444 "Unhandled vector element size in vector compare");
13445 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13446 }
13447
13448 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13449 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13451 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13452 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13454 if (TypeSize == Context.getTypeSize(Context.LongTy))
13455 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13457 if (TypeSize == Context.getTypeSize(Context.IntTy))
13458 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13460 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13461 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13463 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13464 "Unhandled vector element size in vector compare");
13465 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13467}
13468
13470 const BuiltinType *VTy = V->castAs<BuiltinType>();
13471 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13472
13473 const QualType ETy = V->getSveEltType(Context);
13474 const auto TypeSize = Context.getTypeSize(ETy);
13475
13476 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13477 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13478 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13479}
13480
13482 SourceLocation Loc,
13483 BinaryOperatorKind Opc) {
13484 if (Opc == BO_Cmp) {
13485 Diag(Loc, diag::err_three_way_vector_comparison);
13486 return QualType();
13487 }
13488
13489 // Check to make sure we're operating on vectors of the same type and width,
13490 // Allowing one side to be a scalar of element type.
13491 QualType vType =
13492 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13493 /*AllowBothBool*/ true,
13494 /*AllowBoolConversions*/ getLangOpts().ZVector,
13495 /*AllowBooleanOperation*/ true,
13496 /*ReportInvalid*/ true);
13497 if (vType.isNull())
13498 return vType;
13499
13500 QualType LHSType = LHS.get()->getType();
13501
13502 // Determine the return type of a vector compare. By default clang will return
13503 // a scalar for all vector compares except vector bool and vector pixel.
13504 // With the gcc compiler we will always return a vector type and with the xl
13505 // compiler we will always return a scalar type. This switch allows choosing
13506 // which behavior is prefered.
13507 if (getLangOpts().AltiVec) {
13508 switch (getLangOpts().getAltivecSrcCompat()) {
13510 // If AltiVec, the comparison results in a numeric type, i.e.
13511 // bool for C++, int for C
13512 if (vType->castAs<VectorType>()->getVectorKind() ==
13514 return Context.getLogicalOperationType();
13515 else
13516 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13517 break;
13519 // For GCC we always return the vector type.
13520 break;
13522 return Context.getLogicalOperationType();
13523 break;
13524 }
13525 }
13526
13527 // For non-floating point types, check for self-comparisons of the form
13528 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13529 // often indicate logic errors in the program.
13530 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13531
13532 // Check for comparisons of floating point operands using != and ==.
13533 if (LHSType->hasFloatingRepresentation()) {
13534 assert(RHS.get()->getType()->hasFloatingRepresentation());
13535 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13536 }
13537
13538 // Return a signed type for the vector.
13539 return GetSignedVectorType(vType);
13540}
13541
13543 ExprResult &RHS,
13544 SourceLocation Loc,
13545 BinaryOperatorKind Opc) {
13546 if (Opc == BO_Cmp) {
13547 Diag(Loc, diag::err_three_way_vector_comparison);
13548 return QualType();
13549 }
13550
13551 // Check to make sure we're operating on vectors of the same type and width,
13552 // Allowing one side to be a scalar of element type.
13554 LHS, RHS, Loc, /*isCompAssign*/ false, ArithConvKind::Comparison);
13555
13556 if (vType.isNull())
13557 return vType;
13558
13559 QualType LHSType = LHS.get()->getType();
13560
13561 // For non-floating point types, check for self-comparisons of the form
13562 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13563 // often indicate logic errors in the program.
13564 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13565
13566 // Check for comparisons of floating point operands using != and ==.
13567 if (LHSType->hasFloatingRepresentation()) {
13568 assert(RHS.get()->getType()->hasFloatingRepresentation());
13569 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13570 }
13571
13572 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13573 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13574
13575 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13576 RHSBuiltinTy->isSVEBool())
13577 return LHSType;
13578
13579 // Return a signed type for the vector.
13580 return GetSignedSizelessVectorType(vType);
13581}
13582
13583static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13584 const ExprResult &XorRHS,
13585 const SourceLocation Loc) {
13586 // Do not diagnose macros.
13587 if (Loc.isMacroID())
13588 return;
13589
13590 // Do not diagnose if both LHS and RHS are macros.
13591 if (XorLHS.get()->getExprLoc().isMacroID() &&
13592 XorRHS.get()->getExprLoc().isMacroID())
13593 return;
13594
13595 bool Negative = false;
13596 bool ExplicitPlus = false;
13597 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13598 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13599
13600 if (!LHSInt)
13601 return;
13602 if (!RHSInt) {
13603 // Check negative literals.
13604 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13605 UnaryOperatorKind Opc = UO->getOpcode();
13606 if (Opc != UO_Minus && Opc != UO_Plus)
13607 return;
13608 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13609 if (!RHSInt)
13610 return;
13611 Negative = (Opc == UO_Minus);
13612 ExplicitPlus = !Negative;
13613 } else {
13614 return;
13615 }
13616 }
13617
13618 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13619 llvm::APInt RightSideValue = RHSInt->getValue();
13620 if (LeftSideValue != 2 && LeftSideValue != 10)
13621 return;
13622
13623 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13624 return;
13625
13627 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13628 llvm::StringRef ExprStr =
13630
13631 CharSourceRange XorRange =
13633 llvm::StringRef XorStr =
13635 // Do not diagnose if xor keyword/macro is used.
13636 if (XorStr == "xor")
13637 return;
13638
13639 std::string LHSStr = std::string(Lexer::getSourceText(
13640 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13641 S.getSourceManager(), S.getLangOpts()));
13642 std::string RHSStr = std::string(Lexer::getSourceText(
13643 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13644 S.getSourceManager(), S.getLangOpts()));
13645
13646 if (Negative) {
13647 RightSideValue = -RightSideValue;
13648 RHSStr = "-" + RHSStr;
13649 } else if (ExplicitPlus) {
13650 RHSStr = "+" + RHSStr;
13651 }
13652
13653 StringRef LHSStrRef = LHSStr;
13654 StringRef RHSStrRef = RHSStr;
13655 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13656 // literals.
13657 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13658 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13659 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13660 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13661 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13662 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13663 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13664 return;
13665
13666 bool SuggestXor =
13667 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13668 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13669 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13670 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13671 std::string SuggestedExpr = "1 << " + RHSStr;
13672 bool Overflow = false;
13673 llvm::APInt One = (LeftSideValue - 1);
13674 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13675 if (Overflow) {
13676 if (RightSideIntValue < 64)
13677 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13678 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13679 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13680 else if (RightSideIntValue == 64)
13681 S.Diag(Loc, diag::warn_xor_used_as_pow)
13682 << ExprStr << toString(XorValue, 10, true);
13683 else
13684 return;
13685 } else {
13686 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13687 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13688 << toString(PowValue, 10, true)
13690 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13691 }
13692
13693 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13694 << ("0x2 ^ " + RHSStr) << SuggestXor;
13695 } else if (LeftSideValue == 10) {
13696 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13697 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13698 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13699 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13700 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13701 << ("0xA ^ " + RHSStr) << SuggestXor;
13702 }
13703}
13704
13706 SourceLocation Loc,
13707 BinaryOperatorKind Opc) {
13708 // Ensure that either both operands are of the same vector type, or
13709 // one operand is of a vector type and the other is of its element type.
13710 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13711 /*AllowBothBool*/ true,
13712 /*AllowBoolConversions*/ false,
13713 /*AllowBooleanOperation*/ false,
13714 /*ReportInvalid*/ false);
13715 if (vType.isNull())
13716 return InvalidOperands(Loc, LHS, RHS);
13717 if (getLangOpts().OpenCL &&
13718 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13720 return InvalidOperands(Loc, LHS, RHS);
13721 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13722 // usage of the logical operators && and || with vectors in C. This
13723 // check could be notionally dropped.
13724 if (!getLangOpts().CPlusPlus &&
13725 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13726 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13727 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13728 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13729 // `select` functions.
13730 if (getLangOpts().HLSL &&
13731 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13732 (void)InvalidOperands(Loc, LHS, RHS);
13733 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13734 return QualType();
13735 }
13736
13737 return GetSignedVectorType(LHS.get()->getType());
13738}
13739
13741 SourceLocation Loc,
13742 BinaryOperatorKind Opc) {
13743
13744 if (!getLangOpts().HLSL) {
13745 assert(false && "Logical operands are not supported in C\\C++");
13746 return QualType();
13747 }
13748
13749 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13750 (void)InvalidOperands(Loc, LHS, RHS);
13751 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13752 return QualType();
13753 }
13754 SemaRef.Diag(LHS.get()->getBeginLoc(), diag::err_hlsl_langstd_unimplemented)
13755 << getLangOpts().getHLSLVersion();
13756 return QualType();
13757}
13758
13760 SourceLocation Loc,
13761 bool IsCompAssign) {
13762 if (!IsCompAssign) {
13764 if (LHS.isInvalid())
13765 return QualType();
13766 }
13768 if (RHS.isInvalid())
13769 return QualType();
13770
13771 // For conversion purposes, we ignore any qualifiers.
13772 // For example, "const float" and "float" are equivalent.
13773 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13774 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13775
13776 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13777 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13778 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13779
13780 if (Context.hasSameType(LHSType, RHSType))
13781 return Context.getCommonSugaredType(LHSType, RHSType);
13782
13783 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13784 // case we have to return InvalidOperands.
13785 ExprResult OriginalLHS = LHS;
13786 ExprResult OriginalRHS = RHS;
13787 if (LHSMatType && !RHSMatType) {
13788 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13789 if (!RHS.isInvalid())
13790 return LHSType;
13791
13792 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13793 }
13794
13795 if (!LHSMatType && RHSMatType) {
13796 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13797 if (!LHS.isInvalid())
13798 return RHSType;
13799 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13800 }
13801
13802 return InvalidOperands(Loc, LHS, RHS);
13803}
13804
13806 SourceLocation Loc,
13807 bool IsCompAssign) {
13808 if (!IsCompAssign) {
13810 if (LHS.isInvalid())
13811 return QualType();
13812 }
13814 if (RHS.isInvalid())
13815 return QualType();
13816
13817 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13818 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13819 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13820
13821 if (LHSMatType && RHSMatType) {
13822 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13823 return InvalidOperands(Loc, LHS, RHS);
13824
13825 if (Context.hasSameType(LHSMatType, RHSMatType))
13826 return Context.getCommonSugaredType(
13827 LHS.get()->getType().getUnqualifiedType(),
13828 RHS.get()->getType().getUnqualifiedType());
13829
13830 QualType LHSELTy = LHSMatType->getElementType(),
13831 RHSELTy = RHSMatType->getElementType();
13832 if (!Context.hasSameType(LHSELTy, RHSELTy))
13833 return InvalidOperands(Loc, LHS, RHS);
13834
13835 return Context.getConstantMatrixType(
13836 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13837 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13838 }
13839 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13840}
13841
13843 switch (Opc) {
13844 default:
13845 return false;
13846 case BO_And:
13847 case BO_AndAssign:
13848 case BO_Or:
13849 case BO_OrAssign:
13850 case BO_Xor:
13851 case BO_XorAssign:
13852 return true;
13853 }
13854}
13855
13857 SourceLocation Loc,
13858 BinaryOperatorKind Opc) {
13859 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13860
13861 bool IsCompAssign =
13862 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13863
13864 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13865
13866 if (LHS.get()->getType()->isVectorType() ||
13867 RHS.get()->getType()->isVectorType()) {
13868 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13870 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13871 /*AllowBothBool*/ true,
13872 /*AllowBoolConversions*/ getLangOpts().ZVector,
13873 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13874 /*ReportInvalid*/ true);
13875 return InvalidOperands(Loc, LHS, RHS);
13876 }
13877
13878 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13879 RHS.get()->getType()->isSveVLSBuiltinType()) {
13880 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13882 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13884 return InvalidOperands(Loc, LHS, RHS);
13885 }
13886
13887 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13888 RHS.get()->getType()->isSveVLSBuiltinType()) {
13889 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13891 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13893 return InvalidOperands(Loc, LHS, RHS);
13894 }
13895
13896 if (Opc == BO_And)
13897 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13898
13899 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13901 return InvalidOperands(Loc, LHS, RHS);
13902
13903 ExprResult LHSResult = LHS, RHSResult = RHS;
13905 LHSResult, RHSResult, Loc,
13907 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13908 return QualType();
13909 LHS = LHSResult.get();
13910 RHS = RHSResult.get();
13911
13912 if (Opc == BO_Xor)
13913 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13914
13915 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13916 return compType;
13917 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13918 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13919 return ResultTy;
13920}
13921
13922// C99 6.5.[13,14]
13924 SourceLocation Loc,
13925 BinaryOperatorKind Opc) {
13926 // Check vector operands differently.
13927 if (LHS.get()->getType()->isVectorType() ||
13928 RHS.get()->getType()->isVectorType())
13929 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13930
13931 if (LHS.get()->getType()->isConstantMatrixType() ||
13932 RHS.get()->getType()->isConstantMatrixType())
13933 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
13934
13935 bool EnumConstantInBoolContext = false;
13936 for (const ExprResult &HS : {LHS, RHS}) {
13937 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13938 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13939 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13940 EnumConstantInBoolContext = true;
13941 }
13942 }
13943
13944 if (EnumConstantInBoolContext)
13945 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13946
13947 // WebAssembly tables can't be used with logical operators.
13948 QualType LHSTy = LHS.get()->getType();
13949 QualType RHSTy = RHS.get()->getType();
13950 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13951 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13952 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13953 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13954 return InvalidOperands(Loc, LHS, RHS);
13955 }
13956
13957 // Diagnose cases where the user write a logical and/or but probably meant a
13958 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13959 // is a constant.
13960 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13961 !LHS.get()->getType()->isBooleanType() &&
13962 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13963 // Don't warn in macros or template instantiations.
13964 !Loc.isMacroID() && !inTemplateInstantiation()) {
13965 // If the RHS can be constant folded, and if it constant folds to something
13966 // that isn't 0 or 1 (which indicate a potential logical operation that
13967 // happened to fold to true/false) then warn.
13968 // Parens on the RHS are ignored.
13969 Expr::EvalResult EVResult;
13970 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13971 llvm::APSInt Result = EVResult.Val.getInt();
13972 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13973 !RHS.get()->getExprLoc().isMacroID()) ||
13974 (Result != 0 && Result != 1)) {
13975 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13976 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13977 // Suggest replacing the logical operator with the bitwise version
13978 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13979 << (Opc == BO_LAnd ? "&" : "|")
13982 Opc == BO_LAnd ? "&" : "|");
13983 if (Opc == BO_LAnd)
13984 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13985 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13988 RHS.get()->getEndLoc()));
13989 }
13990 }
13991 }
13992
13993 if (!Context.getLangOpts().CPlusPlus) {
13994 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13995 // not operate on the built-in scalar and vector float types.
13996 if (Context.getLangOpts().OpenCL &&
13997 Context.getLangOpts().OpenCLVersion < 120) {
13998 if (LHS.get()->getType()->isFloatingType() ||
13999 RHS.get()->getType()->isFloatingType())
14000 return InvalidOperands(Loc, LHS, RHS);
14001 }
14002
14003 LHS = UsualUnaryConversions(LHS.get());
14004 if (LHS.isInvalid())
14005 return QualType();
14006
14007 RHS = UsualUnaryConversions(RHS.get());
14008 if (RHS.isInvalid())
14009 return QualType();
14010
14011 if (LHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14013 if (RHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14015
14016 if (!LHS.get()->getType()->isScalarType() ||
14017 !RHS.get()->getType()->isScalarType())
14018 return InvalidOperands(Loc, LHS, RHS);
14019
14020 return Context.IntTy;
14021 }
14022
14023 // The following is safe because we only use this method for
14024 // non-overloadable operands.
14025
14026 // C++ [expr.log.and]p1
14027 // C++ [expr.log.or]p1
14028 // The operands are both contextually converted to type bool.
14030 if (LHSRes.isInvalid()) {
14031 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14032 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
14033 return ResultTy;
14034 }
14035 LHS = LHSRes;
14036
14038 if (RHSRes.isInvalid()) {
14039 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14040 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
14041 return ResultTy;
14042 }
14043 RHS = RHSRes;
14044
14045 // C++ [expr.log.and]p2
14046 // C++ [expr.log.or]p2
14047 // The result is a bool.
14048 return Context.BoolTy;
14049}
14050
14051static bool IsReadonlyMessage(Expr *E, Sema &S) {
14052 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14053 if (!ME) return false;
14054 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
14055 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14057 if (!Base) return false;
14058 return Base->getMethodDecl() != nullptr;
14059}
14060
14061/// Is the given expression (which must be 'const') a reference to a
14062/// variable which was originally non-const, but which has become
14063/// 'const' due to being captured within a block?
14066 assert(E->isLValue() && E->getType().isConstQualified());
14067 E = E->IgnoreParens();
14068
14069 // Must be a reference to a declaration from an enclosing scope.
14070 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14071 if (!DRE) return NCCK_None;
14073
14074 ValueDecl *Value = DRE->getDecl();
14075
14076 // The declaration must be a value which is not declared 'const'.
14078 return NCCK_None;
14079
14080 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
14081 if (Binding) {
14082 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
14083 assert(!isa<BlockDecl>(Binding->getDeclContext()));
14084 return NCCK_Lambda;
14085 }
14086
14087 VarDecl *Var = dyn_cast<VarDecl>(Value);
14088 if (!Var)
14089 return NCCK_None;
14090 if (Var->getType()->isReferenceType())
14091 return NCCK_None;
14092
14093 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
14094
14095 // Decide whether the first capture was for a block or a lambda.
14096 DeclContext *DC = S.CurContext, *Prev = nullptr;
14097 // Decide whether the first capture was for a block or a lambda.
14098 while (DC) {
14099 // For init-capture, it is possible that the variable belongs to the
14100 // template pattern of the current context.
14101 if (auto *FD = dyn_cast<FunctionDecl>(DC))
14102 if (Var->isInitCapture() &&
14103 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
14104 break;
14105 if (DC == Var->getDeclContext())
14106 break;
14107 Prev = DC;
14108 DC = DC->getParent();
14109 }
14110 // Unless we have an init-capture, we've gone one step too far.
14111 if (!Var->isInitCapture())
14112 DC = Prev;
14113 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
14114}
14115
14116static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14117 Ty = Ty.getNonReferenceType();
14118 if (IsDereference && Ty->isPointerType())
14119 Ty = Ty->getPointeeType();
14120 return !Ty.isConstQualified();
14121}
14122
14123// Update err_typecheck_assign_const and note_typecheck_assign_const
14124// when this enum is changed.
14125enum {
14130 ConstUnknown, // Keep as last element
14131};
14132
14133/// Emit the "read-only variable not assignable" error and print notes to give
14134/// more information about why the variable is not assignable, such as pointing
14135/// to the declaration of a const variable, showing that a method is const, or
14136/// that the function is returning a const reference.
14137static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14138 SourceLocation Loc) {
14139 SourceRange ExprRange = E->getSourceRange();
14140
14141 // Only emit one error on the first const found. All other consts will emit
14142 // a note to the error.
14143 bool DiagnosticEmitted = false;
14144
14145 // Track if the current expression is the result of a dereference, and if the
14146 // next checked expression is the result of a dereference.
14147 bool IsDereference = false;
14148 bool NextIsDereference = false;
14149
14150 // Loop to process MemberExpr chains.
14151 while (true) {
14152 IsDereference = NextIsDereference;
14153
14155 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14156 NextIsDereference = ME->isArrow();
14157 const ValueDecl *VD = ME->getMemberDecl();
14158 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
14159 // Mutable fields can be modified even if the class is const.
14160 if (Field->isMutable()) {
14161 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14162 break;
14163 }
14164
14165 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
14166 if (!DiagnosticEmitted) {
14167 S.Diag(Loc, diag::err_typecheck_assign_const)
14168 << ExprRange << ConstMember << false /*static*/ << Field
14169 << Field->getType();
14170 DiagnosticEmitted = true;
14171 }
14172 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14173 << ConstMember << false /*static*/ << Field << Field->getType()
14174 << Field->getSourceRange();
14175 }
14176 E = ME->getBase();
14177 continue;
14178 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
14179 if (VDecl->getType().isConstQualified()) {
14180 if (!DiagnosticEmitted) {
14181 S.Diag(Loc, diag::err_typecheck_assign_const)
14182 << ExprRange << ConstMember << true /*static*/ << VDecl
14183 << VDecl->getType();
14184 DiagnosticEmitted = true;
14185 }
14186 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14187 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14188 << VDecl->getSourceRange();
14189 }
14190 // Static fields do not inherit constness from parents.
14191 break;
14192 }
14193 break; // End MemberExpr
14194 } else if (const ArraySubscriptExpr *ASE =
14195 dyn_cast<ArraySubscriptExpr>(E)) {
14196 E = ASE->getBase()->IgnoreParenImpCasts();
14197 continue;
14198 } else if (const ExtVectorElementExpr *EVE =
14199 dyn_cast<ExtVectorElementExpr>(E)) {
14200 E = EVE->getBase()->IgnoreParenImpCasts();
14201 continue;
14202 }
14203 break;
14204 }
14205
14206 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
14207 // Function calls
14208 const FunctionDecl *FD = CE->getDirectCallee();
14209 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
14210 if (!DiagnosticEmitted) {
14211 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14212 << ConstFunction << FD;
14213 DiagnosticEmitted = true;
14214 }
14216 diag::note_typecheck_assign_const)
14217 << ConstFunction << FD << FD->getReturnType()
14218 << FD->getReturnTypeSourceRange();
14219 }
14220 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14221 // Point to variable declaration.
14222 if (const ValueDecl *VD = DRE->getDecl()) {
14223 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
14224 if (!DiagnosticEmitted) {
14225 S.Diag(Loc, diag::err_typecheck_assign_const)
14226 << ExprRange << ConstVariable << VD << VD->getType();
14227 DiagnosticEmitted = true;
14228 }
14229 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14230 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14231 }
14232 }
14233 } else if (isa<CXXThisExpr>(E)) {
14234 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14235 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
14236 if (MD->isConst()) {
14237 if (!DiagnosticEmitted) {
14238 S.Diag(Loc, diag::err_typecheck_assign_const_method)
14239 << ExprRange << MD;
14240 DiagnosticEmitted = true;
14241 }
14242 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const_method)
14243 << MD << MD->getSourceRange();
14244 }
14245 }
14246 }
14247 }
14248
14249 if (DiagnosticEmitted)
14250 return;
14251
14252 // Can't determine a more specific message, so display the generic error.
14253 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14254}
14255
14261
14263 const RecordType *Ty,
14264 SourceLocation Loc, SourceRange Range,
14265 OriginalExprKind OEK,
14266 bool &DiagnosticEmitted) {
14267 std::vector<const RecordType *> RecordTypeList;
14268 RecordTypeList.push_back(Ty);
14269 unsigned NextToCheckIndex = 0;
14270 // We walk the record hierarchy breadth-first to ensure that we print
14271 // diagnostics in field nesting order.
14272 while (RecordTypeList.size() > NextToCheckIndex) {
14273 bool IsNested = NextToCheckIndex > 0;
14274 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14275 ->getDecl()
14276 ->getDefinitionOrSelf()
14277 ->fields()) {
14278 // First, check every field for constness.
14279 QualType FieldTy = Field->getType();
14280 if (FieldTy.isConstQualified()) {
14281 if (!DiagnosticEmitted) {
14282 S.Diag(Loc, diag::err_typecheck_assign_const)
14283 << Range << NestedConstMember << OEK << VD
14284 << IsNested << Field;
14285 DiagnosticEmitted = true;
14286 }
14287 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14288 << NestedConstMember << IsNested << Field
14289 << FieldTy << Field->getSourceRange();
14290 }
14291
14292 // Then we append it to the list to check next in order.
14293 FieldTy = FieldTy.getCanonicalType();
14294 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14295 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14296 RecordTypeList.push_back(FieldRecTy);
14297 }
14298 }
14299 ++NextToCheckIndex;
14300 }
14301}
14302
14303/// Emit an error for the case where a record we are trying to assign to has a
14304/// const-qualified field somewhere in its hierarchy.
14305static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14306 SourceLocation Loc) {
14307 QualType Ty = E->getType();
14308 assert(Ty->isRecordType() && "lvalue was not record?");
14309 SourceRange Range = E->getSourceRange();
14310 const auto *RTy = Ty->getAsCanonical<RecordType>();
14311 bool DiagEmitted = false;
14312
14313 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14314 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14315 Range, OEK_Member, DiagEmitted);
14316 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14317 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14318 Range, OEK_Variable, DiagEmitted);
14319 else
14320 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14321 Range, OEK_LValue, DiagEmitted);
14322 if (!DiagEmitted)
14323 DiagnoseConstAssignment(S, E, Loc);
14324}
14325
14326/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14327/// emit an error and return true. If so, return false.
14329 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14330
14332
14333 SourceLocation OrigLoc = Loc;
14335 &Loc);
14336 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14338 if (IsLV == Expr::MLV_Valid)
14339 return false;
14340
14341 unsigned DiagID = 0;
14342 bool NeedType = false;
14343 switch (IsLV) { // C99 6.5.16p2
14345 // Use a specialized diagnostic when we're assigning to an object
14346 // from an enclosing function or block.
14348 if (NCCK == NCCK_Block)
14349 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14350 else
14351 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14352 break;
14353 }
14354
14355 // In ARC, use some specialized diagnostics for occasions where we
14356 // infer 'const'. These are always pseudo-strong variables.
14357 if (S.getLangOpts().ObjCAutoRefCount) {
14358 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14359 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14360 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14361
14362 // Use the normal diagnostic if it's pseudo-__strong but the
14363 // user actually wrote 'const'.
14364 if (var->isARCPseudoStrong() &&
14365 (!var->getTypeSourceInfo() ||
14366 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14367 // There are three pseudo-strong cases:
14368 // - self
14369 ObjCMethodDecl *method = S.getCurMethodDecl();
14370 if (method && var == method->getSelfDecl()) {
14371 DiagID = method->isClassMethod()
14372 ? diag::err_typecheck_arc_assign_self_class_method
14373 : diag::err_typecheck_arc_assign_self;
14374
14375 // - Objective-C externally_retained attribute.
14376 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14377 isa<ParmVarDecl>(var)) {
14378 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14379
14380 // - fast enumeration variables
14381 } else {
14382 DiagID = diag::err_typecheck_arr_assign_enumeration;
14383 }
14384
14385 SourceRange Assign;
14386 if (Loc != OrigLoc)
14387 Assign = SourceRange(OrigLoc, OrigLoc);
14388 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14389 // We need to preserve the AST regardless, so migration tool
14390 // can do its job.
14391 return false;
14392 }
14393 }
14394 }
14395
14396 // If none of the special cases above are triggered, then this is a
14397 // simple const assignment.
14398 if (DiagID == 0) {
14399 DiagnoseConstAssignment(S, E, Loc);
14400 return true;
14401 }
14402
14403 break;
14405 DiagnoseConstAssignment(S, E, Loc);
14406 return true;
14409 return true;
14412 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14413 NeedType = true;
14414 break;
14416 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14417 NeedType = true;
14418 break;
14420 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14421 break;
14422 case Expr::MLV_Valid:
14423 llvm_unreachable("did not take early return for MLV_Valid");
14427 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14428 break;
14431 return S.RequireCompleteType(Loc, E->getType(),
14432 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14434 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14435 break;
14437 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14438 break;
14440 llvm_unreachable("readonly properties should be processed differently");
14442 DiagID = diag::err_readonly_message_assignment;
14443 break;
14445 DiagID = diag::err_no_subobject_property_setting;
14446 break;
14447 }
14448
14449 SourceRange Assign;
14450 if (Loc != OrigLoc)
14451 Assign = SourceRange(OrigLoc, OrigLoc);
14452 if (NeedType)
14453 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14454 else
14455 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14456 return true;
14457}
14458
14459static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14460 SourceLocation Loc,
14461 Sema &Sema) {
14463 return;
14465 return;
14466 if (Loc.isInvalid() || Loc.isMacroID())
14467 return;
14468 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14469 return;
14470
14471 // C / C++ fields
14472 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14473 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14474 if (ML && MR) {
14475 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14476 return;
14477 const ValueDecl *LHSDecl =
14479 const ValueDecl *RHSDecl =
14481 if (LHSDecl != RHSDecl)
14482 return;
14483 if (LHSDecl->getType().isVolatileQualified())
14484 return;
14485 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14486 if (RefTy->getPointeeType().isVolatileQualified())
14487 return;
14488
14489 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14490 }
14491
14492 // Objective-C instance variables
14493 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14494 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14495 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14496 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14497 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14498 if (RL && RR && RL->getDecl() == RR->getDecl())
14499 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14500 }
14501}
14502
14503// C99 6.5.16.1
14505 SourceLocation Loc,
14506 QualType CompoundType,
14507 BinaryOperatorKind Opc) {
14508 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14509
14510 // Verify that LHS is a modifiable lvalue, and emit error if not.
14511 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14512 return QualType();
14513
14514 QualType LHSType = LHSExpr->getType();
14515 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14516 CompoundType;
14517
14518 if (RHS.isUsable()) {
14519 // Even if this check fails don't return early to allow the best
14520 // possible error recovery and to allow any subsequent diagnostics to
14521 // work.
14522 const ValueDecl *Assignee = nullptr;
14523 bool ShowFullyQualifiedAssigneeName = false;
14524 // In simple cases describe what is being assigned to
14525 if (auto *DR = dyn_cast<DeclRefExpr>(LHSExpr->IgnoreParenCasts())) {
14526 Assignee = DR->getDecl();
14527 } else if (auto *ME = dyn_cast<MemberExpr>(LHSExpr->IgnoreParenCasts())) {
14528 Assignee = ME->getMemberDecl();
14529 ShowFullyQualifiedAssigneeName = true;
14530 }
14531
14533 LHSType, RHS.get(), AssignmentAction::Assigning, Loc, Assignee,
14534 ShowFullyQualifiedAssigneeName);
14535 }
14536
14537 // OpenCL v1.2 s6.1.1.1 p2:
14538 // The half data type can only be used to declare a pointer to a buffer that
14539 // contains half values
14540 if (getLangOpts().OpenCL &&
14541 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14542 LHSType->isHalfType()) {
14543 Diag(Loc, diag::err_opencl_half_load_store) << 1
14544 << LHSType.getUnqualifiedType();
14545 return QualType();
14546 }
14547
14548 // WebAssembly tables can't be used on RHS of an assignment expression.
14549 if (RHSType->isWebAssemblyTableType()) {
14550 Diag(Loc, diag::err_wasm_table_art) << 0;
14551 return QualType();
14552 }
14553
14554 AssignConvertType ConvTy;
14555 if (CompoundType.isNull()) {
14556 Expr *RHSCheck = RHS.get();
14557
14558 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14559
14560 QualType LHSTy(LHSType);
14561 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14562 if (RHS.isInvalid())
14563 return QualType();
14564 // Special case of NSObject attributes on c-style pointer types.
14566 ((Context.isObjCNSObjectType(LHSType) &&
14567 RHSType->isObjCObjectPointerType()) ||
14568 (Context.isObjCNSObjectType(RHSType) &&
14569 LHSType->isObjCObjectPointerType())))
14571
14572 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14573 Diag(Loc, diag::err_objc_object_assignment) << LHSType;
14574
14575 // If the RHS is a unary plus or minus, check to see if they = and + are
14576 // right next to each other. If so, the user may have typo'd "x =+ 4"
14577 // instead of "x += 4".
14578 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14579 RHSCheck = ICE->getSubExpr();
14580 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14581 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14582 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14583 // Only if the two operators are exactly adjacent.
14584 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14585 // And there is a space or other character before the subexpr of the
14586 // unary +/-. We don't want to warn on "x=-1".
14587 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14588 UO->getSubExpr()->getBeginLoc().isFileID()) {
14589 Diag(Loc, diag::warn_not_compound_assign)
14590 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14591 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14592 }
14593 }
14594
14595 if (IsAssignConvertCompatible(ConvTy)) {
14596 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14597 // Warn about retain cycles where a block captures the LHS, but
14598 // not if the LHS is a simple variable into which the block is
14599 // being stored...unless that variable can be captured by reference!
14600 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14601 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14602 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14603 ObjC().checkRetainCycles(LHSExpr, RHS.get());
14604 }
14605
14606 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14608 // It is safe to assign a weak reference into a strong variable.
14609 // Although this code can still have problems:
14610 // id x = self.weakProp;
14611 // id y = self.weakProp;
14612 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14613 // paths through the function. This should be revisited if
14614 // -Wrepeated-use-of-weak is made flow-sensitive.
14615 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14616 // variable, which will be valid for the current autorelease scope.
14617 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14618 RHS.get()->getBeginLoc()))
14620
14621 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14622 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14623 }
14624 }
14625 } else {
14626 // Compound assignment "x += y"
14627 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14628 }
14629
14630 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
14632 return QualType();
14633
14634 CheckForNullPointerDereference(*this, LHSExpr);
14635
14636 AssignedEntity AE{LHSExpr};
14637 checkAssignmentLifetime(*this, AE, RHS.get());
14638
14639 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14640 if (CompoundType.isNull()) {
14641 // C++2a [expr.ass]p5:
14642 // A simple-assignment whose left operand is of a volatile-qualified
14643 // type is deprecated unless the assignment is either a discarded-value
14644 // expression or an unevaluated operand
14645 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14646 }
14647 }
14648
14649 // C11 6.5.16p3: The type of an assignment expression is the type of the
14650 // left operand would have after lvalue conversion.
14651 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14652 // qualified type, the value has the unqualified version of the type of the
14653 // lvalue; additionally, if the lvalue has atomic type, the value has the
14654 // non-atomic version of the type of the lvalue.
14655 // C++ 5.17p1: the type of the assignment expression is that of its left
14656 // operand.
14657 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14658}
14659
14660// Scenarios to ignore if expression E is:
14661// 1. an explicit cast expression into void
14662// 2. a function call expression that returns void
14663static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14664 E = E->IgnoreParens();
14665
14666 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14667 if (CE->getCastKind() == CK_ToVoid) {
14668 return true;
14669 }
14670
14671 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14672 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14673 CE->getSubExpr()->getType()->isDependentType()) {
14674 return true;
14675 }
14676 }
14677
14678 if (const auto *CE = dyn_cast<CallExpr>(E))
14679 return CE->getCallReturnType(Context)->isVoidType();
14680 return false;
14681}
14682
14684 // No warnings in macros
14685 if (Loc.isMacroID())
14686 return;
14687
14688 // Don't warn in template instantiations.
14690 return;
14691
14692 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14693 // instead, skip more than needed, then call back into here with the
14694 // CommaVisitor in SemaStmt.cpp.
14695 // The listed locations are the initialization and increment portions
14696 // of a for loop. The additional checks are on the condition of
14697 // if statements, do/while loops, and for loops.
14698 if (getCurScope()->isControlScope())
14699 return;
14700
14701 // If there are multiple comma operators used together, get the RHS of the
14702 // of the comma operator as the LHS.
14703 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14704 if (BO->getOpcode() != BO_Comma)
14705 break;
14706 LHS = BO->getRHS();
14707 }
14708
14709 // Only allow some expressions on LHS to not warn.
14710 if (IgnoreCommaOperand(LHS, Context))
14711 return;
14712
14713 Diag(Loc, diag::warn_comma_operator);
14714 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14715 << LHS->getSourceRange()
14717 LangOpts.CPlusPlus ? "static_cast<void>("
14718 : "(void)(")
14719 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14720 ")");
14721}
14722
14723// C99 6.5.17
14725 SourceLocation Loc) {
14726 LHS = S.CheckPlaceholderExpr(LHS.get());
14727 RHS = S.CheckPlaceholderExpr(RHS.get());
14728 if (LHS.isInvalid() || RHS.isInvalid())
14729 return QualType();
14730
14731 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14732 // operands, but not unary promotions.
14733 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14734
14735 // So we treat the LHS as a ignored value, and in C++ we allow the
14736 // containing site to determine what should be done with the RHS.
14737 LHS = S.IgnoredValueConversions(LHS.get());
14738 if (LHS.isInvalid())
14739 return QualType();
14740
14741 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14742
14743 if (!S.getLangOpts().CPlusPlus) {
14745 if (RHS.isInvalid())
14746 return QualType();
14747 if (!RHS.get()->getType()->isVoidType())
14748 S.RequireCompleteType(Loc, RHS.get()->getType(),
14749 diag::err_incomplete_type);
14750 }
14751
14752 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14753 S.DiagnoseCommaOperator(LHS.get(), Loc);
14754
14755 return RHS.get()->getType();
14756}
14757
14758/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14759/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14762 ExprObjectKind &OK,
14763 SourceLocation OpLoc, bool IsInc,
14764 bool IsPrefix) {
14765 QualType ResType = Op->getType();
14766 // Atomic types can be used for increment / decrement where the non-atomic
14767 // versions can, so ignore the _Atomic() specifier for the purpose of
14768 // checking.
14769 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14770 ResType = ResAtomicType->getValueType();
14771
14772 assert(!ResType.isNull() && "no type for increment/decrement expression");
14773
14774 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14775 // Decrement of bool is not allowed.
14776 if (!IsInc) {
14777 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14778 return QualType();
14779 }
14780 // Increment of bool sets it to true, but is deprecated.
14781 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14782 : diag::warn_increment_bool)
14783 << Op->getSourceRange();
14784 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14785 // Error on enum increments and decrements in C++ mode
14786 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14787 return QualType();
14788 } else if (ResType->isRealType()) {
14789 // OK!
14790 } else if (ResType->isPointerType()) {
14791 // C99 6.5.2.4p2, 6.5.6p2
14792 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14793 return QualType();
14794 } else if (ResType->isOverflowBehaviorType()) {
14795 // OK!
14796 } else if (ResType->isObjCObjectPointerType()) {
14797 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14798 // Otherwise, we just need a complete type.
14799 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14800 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14801 return QualType();
14802 } else if (ResType->isAnyComplexType()) {
14803 // C99 does not support ++/-- on complex types, we allow as an extension.
14804 S.DiagCompat(OpLoc, diag_compat::increment_complex)
14805 << IsInc << Op->getSourceRange();
14806 } else if (ResType->isPlaceholderType()) {
14808 if (PR.isInvalid()) return QualType();
14809 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14810 IsInc, IsPrefix);
14811 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14812 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14813 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14814 (ResType->castAs<VectorType>()->getVectorKind() !=
14816 // The z vector extensions allow ++ and -- for non-bool vectors.
14817 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14818 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14819 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14820 } else {
14821 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14822 << ResType << int(IsInc) << Op->getSourceRange();
14823 return QualType();
14824 }
14825 // At this point, we know we have a real, complex or pointer type.
14826 // Now make sure the operand is a modifiable lvalue.
14827 if (CheckForModifiableLvalue(Op, OpLoc, S))
14828 return QualType();
14829 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14830 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14831 // An operand with volatile-qualified type is deprecated
14832 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14833 << IsInc << ResType;
14834 }
14835 // In C++, a prefix increment is the same type as the operand. Otherwise
14836 // (in C or with postfix), the increment is the unqualified type of the
14837 // operand.
14838 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14839 VK = VK_LValue;
14840 OK = Op->getObjectKind();
14841 return ResType;
14842 } else {
14843 VK = VK_PRValue;
14844 return ResType.getUnqualifiedType();
14845 }
14846}
14847
14848/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14849/// This routine allows us to typecheck complex/recursive expressions
14850/// where the declaration is needed for type checking. We only need to
14851/// handle cases when the expression references a function designator
14852/// or is an lvalue. Here are some examples:
14853/// - &(x) => x
14854/// - &*****f => f for f a function designator.
14855/// - &s.xx => s
14856/// - &s.zz[1].yy -> s, if zz is an array
14857/// - *(x + 1) -> x, if x is an array
14858/// - &"123"[2] -> 0
14859/// - & __real__ x -> x
14860///
14861/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14862/// members.
14864 switch (E->getStmtClass()) {
14865 case Stmt::DeclRefExprClass:
14866 return cast<DeclRefExpr>(E)->getDecl();
14867 case Stmt::MemberExprClass:
14868 // If this is an arrow operator, the address is an offset from
14869 // the base's value, so the object the base refers to is
14870 // irrelevant.
14871 if (cast<MemberExpr>(E)->isArrow())
14872 return nullptr;
14873 // Otherwise, the expression refers to a part of the base
14874 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14875 case Stmt::ArraySubscriptExprClass: {
14876 // FIXME: This code shouldn't be necessary! We should catch the implicit
14877 // promotion of register arrays earlier.
14878 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14879 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14880 if (ICE->getSubExpr()->getType()->isArrayType())
14881 return getPrimaryDecl(ICE->getSubExpr());
14882 }
14883 return nullptr;
14884 }
14885 case Stmt::UnaryOperatorClass: {
14887
14888 switch(UO->getOpcode()) {
14889 case UO_Real:
14890 case UO_Imag:
14891 case UO_Extension:
14892 return getPrimaryDecl(UO->getSubExpr());
14893 default:
14894 return nullptr;
14895 }
14896 }
14897 case Stmt::ParenExprClass:
14898 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14899 case Stmt::ImplicitCastExprClass:
14900 // If the result of an implicit cast is an l-value, we care about
14901 // the sub-expression; otherwise, the result here doesn't matter.
14902 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14903 case Stmt::CXXUuidofExprClass:
14904 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14905 default:
14906 return nullptr;
14907 }
14908}
14909
14910namespace {
14911enum {
14912 AO_Bit_Field = 0,
14913 AO_Vector_Element = 1,
14914 AO_Property_Expansion = 2,
14915 AO_Register_Variable = 3,
14916 AO_Matrix_Element = 4,
14917 AO_No_Error = 5
14918};
14919}
14920/// Diagnose invalid operand for address of operations.
14921///
14922/// \param Type The type of operand which cannot have its address taken.
14924 Expr *E, unsigned Type) {
14925 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14926}
14927
14929 const Expr *Op,
14930 const CXXMethodDecl *MD) {
14931 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14932
14933 if (Op != DRE)
14934 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14935 << Op->getSourceRange();
14936
14937 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14938 if (isa<CXXDestructorDecl>(MD))
14939 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14940 << DRE->getSourceRange();
14941
14942 if (DRE->getQualifier())
14943 return false;
14944
14945 if (MD->getParent()->getName().empty())
14946 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14947 << DRE->getSourceRange();
14948
14949 SmallString<32> Str;
14950 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14951 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14952 << DRE->getSourceRange()
14953 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14954}
14955
14957 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14958 if (PTy->getKind() == BuiltinType::Overload) {
14959 Expr *E = OrigOp.get()->IgnoreParens();
14960 if (!isa<OverloadExpr>(E)) {
14961 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14962 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14963 << OrigOp.get()->getSourceRange();
14964 return QualType();
14965 }
14966
14970 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14971 << OrigOp.get()->getSourceRange();
14972 return QualType();
14973 }
14974
14975 return Context.OverloadTy;
14976 }
14977
14978 if (PTy->getKind() == BuiltinType::UnknownAny)
14979 return Context.UnknownAnyTy;
14980
14981 if (PTy->getKind() == BuiltinType::BoundMember) {
14982 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14983 << OrigOp.get()->getSourceRange();
14984 return QualType();
14985 }
14986
14987 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14988 if (OrigOp.isInvalid()) return QualType();
14989 }
14990
14991 if (OrigOp.get()->isTypeDependent())
14992 return Context.DependentTy;
14993
14994 assert(!OrigOp.get()->hasPlaceholderType());
14995
14996 // Make sure to ignore parentheses in subsequent checks
14997 Expr *op = OrigOp.get()->IgnoreParens();
14998
14999 // In OpenCL captures for blocks called as lambda functions
15000 // are located in the private address space. Blocks used in
15001 // enqueue_kernel can be located in a different address space
15002 // depending on a vendor implementation. Thus preventing
15003 // taking an address of the capture to avoid invalid AS casts.
15004 if (LangOpts.OpenCL) {
15005 auto* VarRef = dyn_cast<DeclRefExpr>(op);
15006 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
15007 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
15008 return QualType();
15009 }
15010 }
15011
15012 if (getLangOpts().C99) {
15013 // Implement C99-only parts of addressof rules.
15014 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
15015 if (uOp->getOpcode() == UO_Deref)
15016 // Per C99 6.5.3.2, the address of a deref always returns a valid result
15017 // (assuming the deref expression is valid).
15018 return uOp->getSubExpr()->getType();
15019 }
15020 // Technically, there should be a check for array subscript
15021 // expressions here, but the result of one is always an lvalue anyway.
15022 }
15023 ValueDecl *dcl = getPrimaryDecl(op);
15024
15025 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
15026 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
15027 op->getBeginLoc()))
15028 return QualType();
15029
15031 unsigned AddressOfError = AO_No_Error;
15032
15033 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15034 bool IsError = isSFINAEContext();
15035 Diag(OpLoc, IsError ? diag::err_typecheck_addrof_temporary
15036 : diag::ext_typecheck_addrof_temporary)
15037 << op->getType() << op->getSourceRange();
15038 if (IsError)
15039 return QualType();
15040 // Materialize the temporary as an lvalue so that we can take its address.
15041 OrigOp = op =
15042 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
15043 } else if (isa<ObjCSelectorExpr>(op)) {
15044 return Context.getPointerType(op->getType());
15045 } else if (lval == Expr::LV_MemberFunction) {
15046 // If it's an instance method, make a member pointer.
15047 // The expression must have exactly the form &A::foo.
15048
15049 // If the underlying expression isn't a decl ref, give up.
15050 if (!isa<DeclRefExpr>(op)) {
15051 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15052 << OrigOp.get()->getSourceRange();
15053 return QualType();
15054 }
15055 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
15057
15058 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15059 QualType MPTy = Context.getMemberPointerType(
15060 op->getType(), DRE->getQualifier(), MD->getParent());
15061
15062 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
15063 !isUnevaluatedContext() && !MPTy->isDependentType()) {
15064 // When pointer authentication is enabled, argument and return types of
15065 // vitual member functions must be complete. This is because vitrual
15066 // member function pointers are implemented using virtual dispatch
15067 // thunks and the thunks cannot be emitted if the argument or return
15068 // types are incomplete.
15069 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15070 SourceLocation DeclRefLoc,
15071 SourceLocation RetArgTypeLoc) {
15072 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
15073 Diag(DeclRefLoc,
15074 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15075 Diag(RetArgTypeLoc,
15076 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15077 << T;
15078 return true;
15079 }
15080 return false;
15081 };
15082 QualType RetTy = MD->getReturnType();
15083 bool IsIncomplete =
15084 !RetTy->isVoidType() &&
15085 ReturnOrParamTypeIsIncomplete(
15086 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15087 for (auto *PVD : MD->parameters())
15088 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15089 PVD->getBeginLoc());
15090 if (IsIncomplete)
15091 return QualType();
15092 }
15093
15094 // Under the MS ABI, lock down the inheritance model now.
15095 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15096 (void)isCompleteType(OpLoc, MPTy);
15097 return MPTy;
15098 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15099 // C99 6.5.3.2p1
15100 // The operand must be either an l-value or a function designator
15101 if (!op->getType()->isFunctionType()) {
15102 // Use a special diagnostic for loads from property references.
15103 if (isa<PseudoObjectExpr>(op)) {
15104 AddressOfError = AO_Property_Expansion;
15105 } else {
15106 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
15107 << op->getType() << op->getSourceRange();
15108 return QualType();
15109 }
15110 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
15111 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
15112 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15113 }
15114
15115 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15116 // The operand cannot be a bit-field
15117 AddressOfError = AO_Bit_Field;
15118 } else if (op->getObjectKind() == OK_VectorComponent) {
15119 // The operand cannot be an element of a vector
15120 AddressOfError = AO_Vector_Element;
15121 } else if (op->getObjectKind() == OK_MatrixComponent) {
15122 // The operand cannot be an element of a matrix.
15123 AddressOfError = AO_Matrix_Element;
15124 } else if (dcl) { // C99 6.5.3.2p1
15125 // We have an lvalue with a decl. Make sure the decl is not declared
15126 // with the register storage-class specifier.
15127 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
15128 // in C++ it is not error to take address of a register
15129 // variable (c++03 7.1.1P3)
15130 if (vd->getStorageClass() == SC_Register &&
15132 AddressOfError = AO_Register_Variable;
15133 }
15134 } else if (isa<MSPropertyDecl>(dcl)) {
15135 AddressOfError = AO_Property_Expansion;
15136 } else if (isa<FunctionTemplateDecl>(dcl)) {
15137 return Context.OverloadTy;
15138 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
15139 // Okay: we can take the address of a field.
15140 // Could be a pointer to member, though, if there is an explicit
15141 // scope qualifier for the class.
15142
15143 // [C++26] [expr.prim.id.general]
15144 // If an id-expression E denotes a non-static non-type member
15145 // of some class C [...] and if E is a qualified-id, E is
15146 // not the un-parenthesized operand of the unary & operator [...]
15147 // the id-expression is transformed into a class member access expression.
15148 if (auto *DRE = dyn_cast<DeclRefExpr>(op);
15149 DRE && DRE->getQualifier() && !isa<ParenExpr>(OrigOp.get())) {
15150 DeclContext *Ctx = dcl->getDeclContext();
15151 if (Ctx && Ctx->isRecord()) {
15152 if (dcl->getType()->isReferenceType()) {
15153 Diag(OpLoc,
15154 diag::err_cannot_form_pointer_to_member_of_reference_type)
15155 << dcl->getDeclName() << dcl->getType();
15156 return QualType();
15157 }
15158
15159 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
15160 Ctx = Ctx->getParent();
15161
15162 QualType MPTy = Context.getMemberPointerType(
15163 op->getType(), DRE->getQualifier(), cast<CXXRecordDecl>(Ctx));
15164 // Under the MS ABI, lock down the inheritance model now.
15165 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15166 (void)isCompleteType(OpLoc, MPTy);
15167 return MPTy;
15168 }
15169 }
15173 llvm_unreachable("Unknown/unexpected decl type");
15174 }
15175
15176 if (AddressOfError != AO_No_Error) {
15177 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
15178 return QualType();
15179 }
15180
15181 if (lval == Expr::LV_IncompleteVoidType) {
15182 // Taking the address of a void variable is technically illegal, but we
15183 // allow it in cases which are otherwise valid.
15184 // Example: "extern void x; void* y = &x;".
15185 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
15186 }
15187
15188 // If the operand has type "type", the result has type "pointer to type".
15189 if (op->getType()->isObjCObjectType())
15190 return Context.getObjCObjectPointerType(op->getType());
15191
15192 // Cannot take the address of WebAssembly references or tables.
15193 if (Context.getTargetInfo().getTriple().isWasm()) {
15194 QualType OpTy = op->getType();
15195 if (OpTy.isWebAssemblyReferenceType()) {
15196 Diag(OpLoc, diag::err_wasm_ca_reference)
15197 << 1 << OrigOp.get()->getSourceRange();
15198 return QualType();
15199 }
15200 if (OpTy->isWebAssemblyTableType()) {
15201 Diag(OpLoc, diag::err_wasm_table_pr)
15202 << 1 << OrigOp.get()->getSourceRange();
15203 return QualType();
15204 }
15205 }
15206
15207 CheckAddressOfPackedMember(op);
15208
15209 return Context.getPointerType(op->getType());
15210}
15211
15212static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15213 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
15214 if (!DRE)
15215 return;
15216 const Decl *D = DRE->getDecl();
15217 if (!D)
15218 return;
15219 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
15220 if (!Param)
15221 return;
15222 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
15223 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15224 return;
15225 if (FunctionScopeInfo *FD = S.getCurFunction())
15226 FD->ModifiedNonNullParams.insert(Param);
15227}
15228
15229/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15231 SourceLocation OpLoc,
15232 bool IsAfterAmp = false) {
15233 ExprResult ConvResult = S.UsualUnaryConversions(Op);
15234 if (ConvResult.isInvalid())
15235 return QualType();
15236 Op = ConvResult.get();
15237 QualType OpTy = Op->getType();
15239
15241 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15242 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
15243 Op->getSourceRange());
15244 }
15245
15246 if (const PointerType *PT = OpTy->getAs<PointerType>())
15247 {
15248 Result = PT->getPointeeType();
15249 }
15250 else if (const ObjCObjectPointerType *OPT =
15252 Result = OPT->getPointeeType();
15253 else {
15255 if (PR.isInvalid()) return QualType();
15256 if (PR.get() != Op)
15257 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
15258 }
15259
15260 if (Result.isNull()) {
15261 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
15262 << OpTy << Op->getSourceRange();
15263 return QualType();
15264 }
15265
15266 if (Result->isVoidType()) {
15267 // C++ [expr.unary.op]p1:
15268 // [...] the expression to which [the unary * operator] is applied shall
15269 // be a pointer to an object type, or a pointer to a function type
15270 LangOptions LO = S.getLangOpts();
15271 if (LO.CPlusPlus)
15272 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
15273 << OpTy << Op->getSourceRange();
15274 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15275 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
15276 << OpTy << Op->getSourceRange();
15277 }
15278
15279 // Dereferences are usually l-values...
15280 VK = VK_LValue;
15281
15282 // ...except that certain expressions are never l-values in C.
15283 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15284 VK = VK_PRValue;
15285
15286 return Result;
15287}
15288
15289BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15291 switch (Kind) {
15292 default: llvm_unreachable("Unknown binop!");
15293 case tok::periodstar: Opc = BO_PtrMemD; break;
15294 case tok::arrowstar: Opc = BO_PtrMemI; break;
15295 case tok::star: Opc = BO_Mul; break;
15296 case tok::slash: Opc = BO_Div; break;
15297 case tok::percent: Opc = BO_Rem; break;
15298 case tok::plus: Opc = BO_Add; break;
15299 case tok::minus: Opc = BO_Sub; break;
15300 case tok::lessless: Opc = BO_Shl; break;
15301 case tok::greatergreater: Opc = BO_Shr; break;
15302 case tok::lessequal: Opc = BO_LE; break;
15303 case tok::less: Opc = BO_LT; break;
15304 case tok::greaterequal: Opc = BO_GE; break;
15305 case tok::greater: Opc = BO_GT; break;
15306 case tok::exclaimequal: Opc = BO_NE; break;
15307 case tok::equalequal: Opc = BO_EQ; break;
15308 case tok::spaceship: Opc = BO_Cmp; break;
15309 case tok::amp: Opc = BO_And; break;
15310 case tok::caret: Opc = BO_Xor; break;
15311 case tok::pipe: Opc = BO_Or; break;
15312 case tok::ampamp: Opc = BO_LAnd; break;
15313 case tok::pipepipe: Opc = BO_LOr; break;
15314 case tok::equal: Opc = BO_Assign; break;
15315 case tok::starequal: Opc = BO_MulAssign; break;
15316 case tok::slashequal: Opc = BO_DivAssign; break;
15317 case tok::percentequal: Opc = BO_RemAssign; break;
15318 case tok::plusequal: Opc = BO_AddAssign; break;
15319 case tok::minusequal: Opc = BO_SubAssign; break;
15320 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15321 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15322 case tok::ampequal: Opc = BO_AndAssign; break;
15323 case tok::caretequal: Opc = BO_XorAssign; break;
15324 case tok::pipeequal: Opc = BO_OrAssign; break;
15325 case tok::comma: Opc = BO_Comma; break;
15326 }
15327 return Opc;
15328}
15329
15331 tok::TokenKind Kind) {
15333 switch (Kind) {
15334 default: llvm_unreachable("Unknown unary op!");
15335 case tok::plusplus: Opc = UO_PreInc; break;
15336 case tok::minusminus: Opc = UO_PreDec; break;
15337 case tok::amp: Opc = UO_AddrOf; break;
15338 case tok::star: Opc = UO_Deref; break;
15339 case tok::plus: Opc = UO_Plus; break;
15340 case tok::minus: Opc = UO_Minus; break;
15341 case tok::tilde: Opc = UO_Not; break;
15342 case tok::exclaim: Opc = UO_LNot; break;
15343 case tok::kw___real: Opc = UO_Real; break;
15344 case tok::kw___imag: Opc = UO_Imag; break;
15345 case tok::kw___extension__: Opc = UO_Extension; break;
15346 }
15347 return Opc;
15348}
15349
15350const FieldDecl *
15352 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15353 // common for setters.
15354 // struct A {
15355 // int X;
15356 // -void setX(int X) { X = X; }
15357 // +void setX(int X) { this->X = X; }
15358 // };
15359
15360 // Only consider parameters for self assignment fixes.
15361 if (!isa<ParmVarDecl>(SelfAssigned))
15362 return nullptr;
15363 const auto *Method =
15364 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15365 if (!Method)
15366 return nullptr;
15367
15368 const CXXRecordDecl *Parent = Method->getParent();
15369 // In theory this is fixable if the lambda explicitly captures this, but
15370 // that's added complexity that's rarely going to be used.
15371 if (Parent->isLambda())
15372 return nullptr;
15373
15374 // FIXME: Use an actual Lookup operation instead of just traversing fields
15375 // in order to get base class fields.
15376 auto Field =
15377 llvm::find_if(Parent->fields(),
15378 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15379 return F->getDeclName() == Name;
15380 });
15381 return (Field != Parent->field_end()) ? *Field : nullptr;
15382}
15383
15384/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15385/// This warning suppressed in the event of macro expansions.
15386static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15387 SourceLocation OpLoc, bool IsBuiltin) {
15389 return;
15390 if (S.isUnevaluatedContext())
15391 return;
15392 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15393 return;
15394 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15395 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15396 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15397 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15398 if (!LHSDeclRef || !RHSDeclRef ||
15399 LHSDeclRef->getLocation().isMacroID() ||
15400 RHSDeclRef->getLocation().isMacroID())
15401 return;
15402 const ValueDecl *LHSDecl =
15403 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15404 const ValueDecl *RHSDecl =
15405 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15406 if (LHSDecl != RHSDecl)
15407 return;
15408 if (LHSDecl->getType().isVolatileQualified())
15409 return;
15410 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15411 if (RefTy->getPointeeType().isVolatileQualified())
15412 return;
15413
15414 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15415 : diag::warn_self_assignment_overloaded)
15416 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15417 << RHSExpr->getSourceRange();
15418 if (const FieldDecl *SelfAssignField =
15420 Diag << 1 << SelfAssignField
15421 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15422 else
15423 Diag << 0;
15424}
15425
15426/// Check if a bitwise-& is performed on an Objective-C pointer. This
15427/// is usually indicative of introspection within the Objective-C pointer.
15429 SourceLocation OpLoc) {
15430 if (!S.getLangOpts().ObjC)
15431 return;
15432
15433 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15434 const Expr *LHS = L.get();
15435 const Expr *RHS = R.get();
15436
15438 ObjCPointerExpr = LHS;
15439 OtherExpr = RHS;
15440 }
15441 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15442 ObjCPointerExpr = RHS;
15443 OtherExpr = LHS;
15444 }
15445
15446 // This warning is deliberately made very specific to reduce false
15447 // positives with logic that uses '&' for hashing. This logic mainly
15448 // looks for code trying to introspect into tagged pointers, which
15449 // code should generally never do.
15450 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15451 unsigned Diag = diag::warn_objc_pointer_masking;
15452 // Determine if we are introspecting the result of performSelectorXXX.
15453 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15454 // Special case messages to -performSelector and friends, which
15455 // can return non-pointer values boxed in a pointer value.
15456 // Some clients may wish to silence warnings in this subcase.
15457 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15458 Selector S = ME->getSelector();
15459 StringRef SelArg0 = S.getNameForSlot(0);
15460 if (SelArg0.starts_with("performSelector"))
15461 Diag = diag::warn_objc_pointer_masking_performSelector;
15462 }
15463
15464 S.Diag(OpLoc, Diag)
15465 << ObjCPointerExpr->getSourceRange();
15466 }
15467}
15468
15469// This helper function promotes a binary operator's operands (which are of a
15470// half vector type) to a vector of floats and then truncates the result to
15471// a vector of either half or short.
15473 BinaryOperatorKind Opc, QualType ResultTy,
15475 bool IsCompAssign, SourceLocation OpLoc,
15476 FPOptionsOverride FPFeatures) {
15477 auto &Context = S.getASTContext();
15478 assert((isVector(ResultTy, Context.HalfTy) ||
15479 isVector(ResultTy, Context.ShortTy)) &&
15480 "Result must be a vector of half or short");
15481 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15482 isVector(RHS.get()->getType(), Context.HalfTy) &&
15483 "both operands expected to be a half vector");
15484
15485 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15486 QualType BinOpResTy = RHS.get()->getType();
15487
15488 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15489 // change BinOpResTy to a vector of ints.
15490 if (isVector(ResultTy, Context.ShortTy))
15491 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15492
15493 if (IsCompAssign)
15494 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15495 ResultTy, VK, OK, OpLoc, FPFeatures,
15496 BinOpResTy, BinOpResTy);
15497
15498 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15499 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15500 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15501 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15502}
15503
15504/// Returns true if conversion between vectors of halfs and vectors of floats
15505/// is needed.
15506static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15507 QualType ResultTy, Expr *E0,
15508 Expr *E1 = nullptr) {
15509 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType)
15510 return false;
15511
15512 // The conversion truncates the result to a half/short vector, so it shouldn't
15513 // apply when the result is not that type (e.g. HLSL comparisons).
15514 if (ResultTy->isVectorType() && !isVector(ResultTy, Ctx.HalfTy) &&
15515 !isVector(ResultTy, Ctx.ShortTy))
15516 return false;
15517
15518 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15519 QualType Ty = E->IgnoreImplicit()->getType();
15520
15521 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15522 // to vectors of floats. Although the element type of the vectors is __fp16,
15523 // the vectors shouldn't be treated as storage-only types. See the
15524 // discussion here: https://reviews.llvm.org/rG825235c140e7
15525 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15526 if (VT->getVectorKind() == VectorKind::Neon)
15527 return false;
15528 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15529 }
15530 return false;
15531 };
15532
15533 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15534}
15535
15537 BinaryOperatorKind Opc, Expr *LHSExpr,
15538 Expr *RHSExpr, bool ForFoldExpression) {
15539 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15540 // The syntax only allows initializer lists on the RHS of assignment,
15541 // so we don't need to worry about accepting invalid code for
15542 // non-assignment operators.
15543 // C++11 5.17p9:
15544 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15545 // of x = {} is x = T().
15547 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15548 InitializedEntity Entity =
15550 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15551 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15552 if (Init.isInvalid())
15553 return Init;
15554 RHSExpr = Init.get();
15555 }
15556
15557 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15558 QualType ResultTy; // Result type of the binary operator.
15559 // The following two variables are used for compound assignment operators
15560 QualType CompLHSTy; // Type of LHS after promotions for computation
15561 QualType CompResultTy; // Type of computation result
15564 bool ConvertHalfVec = false;
15565
15566 if (!LHS.isUsable() || !RHS.isUsable())
15567 return ExprError();
15568
15569 if (getLangOpts().OpenCL) {
15570 QualType LHSTy = LHSExpr->getType();
15571 QualType RHSTy = RHSExpr->getType();
15572 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15573 // the ATOMIC_VAR_INIT macro.
15574 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15575 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15576 if (BO_Assign == Opc)
15577 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15578 else
15579 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15580 return ExprError();
15581 }
15582
15583 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15584 // only with a builtin functions and therefore should be disallowed here.
15585 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15586 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15587 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15588 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15589 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15590 return ExprError();
15591 }
15592 }
15593
15594 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15595 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15596
15597 switch (Opc) {
15598 case BO_Assign:
15599 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15600 if (getLangOpts().CPlusPlus &&
15601 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15602 VK = LHS.get()->getValueKind();
15603 OK = LHS.get()->getObjectKind();
15604 }
15605 if (!ResultTy.isNull()) {
15606 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15607 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15608
15609 // Avoid copying a block to the heap if the block is assigned to a local
15610 // auto variable that is declared in the same scope as the block. This
15611 // optimization is unsafe if the local variable is declared in an outer
15612 // scope. For example:
15613 //
15614 // BlockTy b;
15615 // {
15616 // b = ^{...};
15617 // }
15618 // // It is unsafe to invoke the block here if it wasn't copied to the
15619 // // heap.
15620 // b();
15621
15622 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15623 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15624 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15625 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15626 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15627
15629 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15631 }
15632 RecordModifiableNonNullParam(*this, LHS.get());
15633 break;
15634 case BO_PtrMemD:
15635 case BO_PtrMemI:
15636 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15637 Opc == BO_PtrMemI);
15638 break;
15639 case BO_Mul:
15640 case BO_Div:
15641 ConvertHalfVec = true;
15642 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15643 break;
15644 case BO_Rem:
15645 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15646 break;
15647 case BO_Add:
15648 ConvertHalfVec = true;
15649 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15650 break;
15651 case BO_Sub:
15652 ConvertHalfVec = true;
15653 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);
15654 break;
15655 case BO_Shl:
15656 case BO_Shr:
15657 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15658 break;
15659 case BO_LE:
15660 case BO_LT:
15661 case BO_GE:
15662 case BO_GT:
15663 ConvertHalfVec = true;
15664 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15665
15666 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
15667 !ForFoldExpression && BI && BI->isComparisonOp())
15668 Diag(OpLoc, diag::warn_consecutive_comparison)
15669 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
15670
15671 break;
15672 case BO_EQ:
15673 case BO_NE:
15674 ConvertHalfVec = true;
15675 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15676 break;
15677 case BO_Cmp:
15678 ConvertHalfVec = true;
15679 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15680 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15681 break;
15682 case BO_And:
15683 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15684 [[fallthrough]];
15685 case BO_Xor:
15686 case BO_Or:
15687 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15688 break;
15689 case BO_LAnd:
15690 case BO_LOr:
15691 ConvertHalfVec = true;
15692 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15693 break;
15694 case BO_MulAssign:
15695 case BO_DivAssign:
15696 ConvertHalfVec = true;
15697 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15698 CompLHSTy = CompResultTy;
15699 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15700 ResultTy =
15701 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15702 break;
15703 case BO_RemAssign:
15704 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15705 CompLHSTy = CompResultTy;
15706 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15707 ResultTy =
15708 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15709 break;
15710 case BO_AddAssign:
15711 ConvertHalfVec = true;
15712 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15713 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15714 ResultTy =
15715 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15716 break;
15717 case BO_SubAssign:
15718 ConvertHalfVec = true;
15719 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15720 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15721 ResultTy =
15722 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15723 break;
15724 case BO_ShlAssign:
15725 case BO_ShrAssign:
15726 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15727 CompLHSTy = CompResultTy;
15728 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15729 ResultTy =
15730 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15731 break;
15732 case BO_AndAssign:
15733 case BO_OrAssign: // fallthrough
15734 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15735 [[fallthrough]];
15736 case BO_XorAssign:
15737 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15738 CompLHSTy = CompResultTy;
15739 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15740 ResultTy =
15741 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15742 break;
15743 case BO_Comma:
15744 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15745 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15746 VK = RHS.get()->getValueKind();
15747 OK = RHS.get()->getObjectKind();
15748 }
15749 break;
15750 }
15751 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15752 return ExprError();
15753
15754 // Some of the binary operations require promoting operands of half vector to
15755 // float vectors and truncating the result back to half vector. For now, we do
15756 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15757 // arm64).
15758 assert(
15759 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15760 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15761 "both sides are half vectors or neither sides are");
15762 ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context, ResultTy,
15763 LHS.get(), RHS.get());
15764
15765 // Check for array bounds violations for both sides of the BinaryOperator
15766 CheckArrayAccess(LHS.get());
15767 CheckArrayAccess(RHS.get());
15768
15769 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15770 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15771 &Context.Idents.get("object_setClass"),
15773 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15774 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15775 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15777 "object_setClass(")
15778 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15779 ",")
15780 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15781 }
15782 else
15783 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15784 }
15785 else if (const ObjCIvarRefExpr *OIRE =
15786 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15787 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15788
15789 // Opc is not a compound assignment if CompResultTy is null.
15790 if (CompResultTy.isNull()) {
15791 if (ConvertHalfVec)
15792 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15793 OpLoc, CurFPFeatureOverrides());
15794 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15795 VK, OK, OpLoc, CurFPFeatureOverrides());
15796 }
15797
15798 // Handle compound assignments.
15799 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15801 VK = VK_LValue;
15802 OK = LHS.get()->getObjectKind();
15803 }
15804
15805 // The LHS is not converted to the result type for fixed-point compound
15806 // assignment as the common type is computed on demand. Reset the CompLHSTy
15807 // to the LHS type we would have gotten after unary conversions.
15808 if (CompResultTy->isFixedPointType())
15809 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15810
15811 if (ConvertHalfVec)
15812 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15813 OpLoc, CurFPFeatureOverrides());
15814
15816 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15817 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15818}
15819
15820/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15821/// operators are mixed in a way that suggests that the programmer forgot that
15822/// comparison operators have higher precedence. The most typical example of
15823/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15825 SourceLocation OpLoc, Expr *LHSExpr,
15826 Expr *RHSExpr) {
15827 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15828 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15829
15830 // Check that one of the sides is a comparison operator and the other isn't.
15831 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15832 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15833 if (isLeftComp == isRightComp)
15834 return;
15835
15836 // Bitwise operations are sometimes used as eager logical ops.
15837 // Don't diagnose this.
15838 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15839 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15840 if (isLeftBitwise || isRightBitwise)
15841 return;
15842
15843 SourceRange DiagRange = isLeftComp
15844 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15845 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15846 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15847 SourceRange ParensRange =
15848 isLeftComp
15849 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15850 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15851
15852 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15853 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15854 SuggestParentheses(Self, OpLoc,
15855 Self.PDiag(diag::note_precedence_silence) << OpStr,
15856 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15857 SuggestParentheses(Self, OpLoc,
15858 Self.PDiag(diag::note_precedence_bitwise_first)
15860 ParensRange);
15861}
15862
15863/// It accepts a '&&' expr that is inside a '||' one.
15864/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15865/// in parentheses.
15866static void
15868 BinaryOperator *Bop) {
15869 assert(Bop->getOpcode() == BO_LAnd);
15870 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15871 << Bop->getSourceRange() << OpLoc;
15873 Self.PDiag(diag::note_precedence_silence)
15874 << Bop->getOpcodeStr(),
15875 Bop->getSourceRange());
15876}
15877
15878/// Look for '&&' in the left hand of a '||' expr.
15880 Expr *LHSExpr, Expr *RHSExpr) {
15881 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15882 if (Bop->getOpcode() == BO_LAnd) {
15883 // If it's "string_literal && a || b" don't warn since the precedence
15884 // doesn't matter.
15885 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15886 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15887 } else if (Bop->getOpcode() == BO_LOr) {
15888 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15889 // If it's "a || b && string_literal || c" we didn't warn earlier for
15890 // "a || b && string_literal", but warn now.
15891 if (RBop->getOpcode() == BO_LAnd &&
15892 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15893 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15894 }
15895 }
15896 }
15897}
15898
15899/// Look for '&&' in the right hand of a '||' expr.
15901 Expr *LHSExpr, Expr *RHSExpr) {
15902 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15903 if (Bop->getOpcode() == BO_LAnd) {
15904 // If it's "a || b && string_literal" don't warn since the precedence
15905 // doesn't matter.
15906 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15907 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15908 }
15909 }
15910}
15911
15912/// Look for bitwise op in the left or right hand of a bitwise op with
15913/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15914/// the '&' expression in parentheses.
15916 SourceLocation OpLoc, Expr *SubExpr) {
15917 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15918 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15919 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15920 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15921 << Bop->getSourceRange() << OpLoc;
15922 SuggestParentheses(S, Bop->getOperatorLoc(),
15923 S.PDiag(diag::note_precedence_silence)
15924 << Bop->getOpcodeStr(),
15925 Bop->getSourceRange());
15926 }
15927 }
15928}
15929
15931 Expr *SubExpr, StringRef Shift) {
15932 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15933 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15934 StringRef Op = Bop->getOpcodeStr();
15935 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15936 << Bop->getSourceRange() << OpLoc << Shift << Op;
15937 SuggestParentheses(S, Bop->getOperatorLoc(),
15938 S.PDiag(diag::note_precedence_silence) << Op,
15939 Bop->getSourceRange());
15940 }
15941 }
15942}
15943
15945 Expr *LHSExpr, Expr *RHSExpr) {
15946 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15947 if (!OCE)
15948 return;
15949
15950 FunctionDecl *FD = OCE->getDirectCallee();
15951 if (!FD || !FD->isOverloadedOperator())
15952 return;
15953
15955 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15956 return;
15957
15958 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15959 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15960 << (Kind == OO_LessLess);
15962 S.PDiag(diag::note_precedence_silence)
15963 << (Kind == OO_LessLess ? "<<" : ">>"),
15964 OCE->getSourceRange());
15966 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15967 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15968}
15969
15970/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15971/// precedence.
15973 SourceLocation OpLoc, Expr *LHSExpr,
15974 Expr *RHSExpr){
15975 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15977 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15978
15979 // Diagnose "arg1 & arg2 | arg3"
15980 if ((Opc == BO_Or || Opc == BO_Xor) &&
15981 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15982 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15983 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15984 }
15985
15986 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15987 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15988 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15989 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15990 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15991 }
15992
15993 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15994 || Opc == BO_Shr) {
15995 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15996 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15997 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15998 }
15999
16000 // Warn on overloaded shift operators and comparisons, such as:
16001 // cout << 5 == 4;
16003 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
16004}
16005
16007 tok::TokenKind Kind,
16008 Expr *LHSExpr, Expr *RHSExpr) {
16009 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
16010 assert(LHSExpr && "ActOnBinOp(): missing left expression");
16011 assert(RHSExpr && "ActOnBinOp(): missing right expression");
16012
16013 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16014 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
16015
16019
16020 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
16021 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
16022
16023 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
16024}
16025
16027 UnresolvedSetImpl &Functions) {
16029 if (OverOp != OO_None && OverOp != OO_Equal)
16030 LookupOverloadedOperatorName(OverOp, S, Functions);
16031
16032 // In C++20 onwards, we may have a second operator to look up.
16033 if (getLangOpts().CPlusPlus20) {
16035 LookupOverloadedOperatorName(ExtraOp, S, Functions);
16036 }
16037}
16038
16039/// Build an overloaded binary operator expression in the given scope.
16042 Expr *LHS, Expr *RHS) {
16043 switch (Opc) {
16044 case BO_Assign:
16045 // In the non-overloaded case, we warn about self-assignment (x = x) for
16046 // both simple assignment and certain compound assignments where algebra
16047 // tells us the operation yields a constant result. When the operator is
16048 // overloaded, we can't do the latter because we don't want to assume that
16049 // those algebraic identities still apply; for example, a path-building
16050 // library might use operator/= to append paths. But it's still reasonable
16051 // to assume that simple assignment is just moving/copying values around
16052 // and so self-assignment is likely a bug.
16053 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
16054 [[fallthrough]];
16055 case BO_DivAssign:
16056 case BO_RemAssign:
16057 case BO_SubAssign:
16058 case BO_AndAssign:
16059 case BO_OrAssign:
16060 case BO_XorAssign:
16061 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
16062 break;
16063 default:
16064 break;
16065 }
16066
16067 // Find all of the overloaded operators visible from this point.
16068 UnresolvedSet<16> Functions;
16069 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
16070
16071 // Build the (potentially-overloaded, potentially-dependent)
16072 // binary operation.
16073 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
16074}
16075
16077 BinaryOperatorKind Opc, Expr *LHSExpr,
16078 Expr *RHSExpr, bool ForFoldExpression) {
16079 if (!LHSExpr || !RHSExpr)
16080 return ExprError();
16081
16082 // We want to end up calling one of SemaPseudoObject::checkAssignment
16083 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16084 // both expressions are overloadable or either is type-dependent),
16085 // or CreateBuiltinBinOp (in any other case). We also want to get
16086 // any placeholder types out of the way.
16087
16088 // Handle pseudo-objects in the LHS.
16089 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16090 // Assignments with a pseudo-object l-value need special analysis.
16091 if (pty->getKind() == BuiltinType::PseudoObject &&
16093 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
16094
16095 // Don't resolve overloads if the other type is overloadable.
16096 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16097 // We can't actually test that if we still have a placeholder,
16098 // though. Fortunately, none of the exceptions we see in that
16099 // code below are valid when the LHS is an overload set. Note
16100 // that an overload set can be dependently-typed, but it never
16101 // instantiates to having an overloadable type.
16102 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16103 if (resolvedRHS.isInvalid()) return ExprError();
16104 RHSExpr = resolvedRHS.get();
16105
16106 if (RHSExpr->isTypeDependent() ||
16107 RHSExpr->getType()->isOverloadableType())
16108 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16109 }
16110
16111 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16112 // template, diagnose the missing 'template' keyword instead of diagnosing
16113 // an invalid use of a bound member function.
16114 //
16115 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16116 // to C++1z [over.over]/1.4, but we already checked for that case above.
16117 if (Opc == BO_LT && inTemplateInstantiation() &&
16118 (pty->getKind() == BuiltinType::BoundMember ||
16119 pty->getKind() == BuiltinType::Overload)) {
16120 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
16121 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16122 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
16123 return isa<FunctionTemplateDecl>(ND);
16124 })) {
16125 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16126 : OE->getNameLoc(),
16127 diag::err_template_kw_missing)
16128 << OE->getName().getAsIdentifierInfo();
16129 return ExprError();
16130 }
16131 }
16132
16133 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
16134 if (LHS.isInvalid()) return ExprError();
16135 LHSExpr = LHS.get();
16136 }
16137
16138 // Handle pseudo-objects in the RHS.
16139 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16140 // An overload in the RHS can potentially be resolved by the type
16141 // being assigned to.
16142 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16143 if (getLangOpts().CPlusPlus &&
16144 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16145 LHSExpr->getType()->isOverloadableType()))
16146 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16147
16148 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16149 ForFoldExpression);
16150 }
16151
16152 // Don't resolve overloads if the other type is overloadable.
16153 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16154 LHSExpr->getType()->isOverloadableType())
16155 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16156
16157 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16158 if (!resolvedRHS.isUsable()) return ExprError();
16159 RHSExpr = resolvedRHS.get();
16160 }
16161
16162 if (getLangOpts().HLSL) {
16163 if (LHSExpr->getType()->isHLSLResourceRecord() ||
16164 LHSExpr->getType()->isHLSLResourceRecordArray()) {
16165 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, OpLoc))
16166 return ExprError();
16167 } else if (RHSExpr->getType()->isHLSLResourceRecord()) {
16168 std::optional<ExprResult> ConvRHS =
16170 if (ConvRHS && Context.hasSameUnqualifiedType(
16171 LHSExpr->getType(), ConvRHS->get()->getType())) {
16172 assert(!ConvRHS->isInvalid());
16173 RHSExpr = ConvRHS->get();
16174 }
16175 }
16176 }
16177
16178 if (getLangOpts().CPlusPlus) {
16179 bool CanOverloadBinOp =
16180 !getLangOpts().HLSL ||
16181 HLSL().canHaveOverloadedBinOp(LHSExpr->getType(), Opc) ||
16182 HLSL().canHaveOverloadedBinOp(RHSExpr->getType(), Opc);
16183 bool TypeDependent =
16184 LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent();
16185 bool Overloadable = LHSExpr->getType()->isOverloadableType() ||
16186 RHSExpr->getType()->isOverloadableType();
16187 if (CanOverloadBinOp && (TypeDependent || Overloadable))
16188 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16189 }
16190
16191 if (getLangOpts().RecoveryAST &&
16192 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16193 assert(!getLangOpts().CPlusPlus);
16194 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16195 "Should only occur in error-recovery path.");
16197 // C [6.15.16] p3:
16198 // An assignment expression has the value of the left operand after the
16199 // assignment, but is not an lvalue.
16201 Context, LHSExpr, RHSExpr, Opc,
16203 OpLoc, CurFPFeatureOverrides());
16204 QualType ResultType;
16205 switch (Opc) {
16206 case BO_Assign:
16207 ResultType = LHSExpr->getType().getUnqualifiedType();
16208 break;
16209 case BO_LT:
16210 case BO_GT:
16211 case BO_LE:
16212 case BO_GE:
16213 case BO_EQ:
16214 case BO_NE:
16215 case BO_LAnd:
16216 case BO_LOr:
16217 // These operators have a fixed result type regardless of operands.
16218 ResultType = Context.IntTy;
16219 break;
16220 case BO_Comma:
16221 ResultType = RHSExpr->getType();
16222 break;
16223 default:
16224 ResultType = Context.DependentTy;
16225 break;
16226 }
16227 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
16228 VK_PRValue, OK_Ordinary, OpLoc,
16230 }
16231
16232 // Build a built-in binary operation.
16233 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16234}
16235
16237 if (T.isNull() || T->isDependentType())
16238 return false;
16239
16240 if (!Ctx.isPromotableIntegerType(T))
16241 return true;
16242
16243 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
16244}
16245
16247 UnaryOperatorKind Opc, Expr *InputExpr,
16248 bool IsAfterAmp) {
16249 ExprResult Input = InputExpr;
16252 QualType resultType;
16253 bool CanOverflow = false;
16254
16255 bool ConvertHalfVec = false;
16256 if (getLangOpts().OpenCL) {
16257 QualType Ty = InputExpr->getType();
16258 // The only legal unary operation for atomics is '&'.
16259 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16260 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16261 // only with a builtin functions and therefore should be disallowed here.
16262 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16263 || Ty->isBlockPointerType())) {
16264 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16265 << InputExpr->getType()
16266 << Input.get()->getSourceRange());
16267 }
16268 }
16269
16270 if (getLangOpts().HLSL && OpLoc.isValid()) {
16271 if (Opc == UO_AddrOf)
16272 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
16273 if (Opc == UO_Deref)
16274 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
16275 }
16276
16277 if (InputExpr->isTypeDependent() &&
16278 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
16279 resultType = Context.DependentTy;
16280 } else {
16281 switch (Opc) {
16282 case UO_PreInc:
16283 case UO_PreDec:
16284 case UO_PostInc:
16285 case UO_PostDec:
16286 resultType =
16287 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
16288 Opc == UO_PreInc || Opc == UO_PostInc,
16289 Opc == UO_PreInc || Opc == UO_PreDec);
16290 CanOverflow = isOverflowingIntegerType(Context, resultType);
16291 break;
16292 case UO_AddrOf:
16293 resultType = CheckAddressOfOperand(Input, OpLoc);
16294 CheckAddressOfNoDeref(InputExpr);
16295 RecordModifiableNonNullParam(*this, InputExpr);
16296 break;
16297 case UO_Deref: {
16299 if (Input.isInvalid())
16300 return ExprError();
16301 resultType =
16302 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
16303 break;
16304 }
16305 case UO_Plus:
16306 case UO_Minus:
16307 CanOverflow = Opc == UO_Minus &&
16309 Input = UsualUnaryConversions(Input.get());
16310 if (Input.isInvalid())
16311 return ExprError();
16312 // Unary plus and minus require promoting an operand of half vector to a
16313 // float vector and truncating the result back to a half vector. For now,
16314 // we do this only when HalfArgsAndReturns is set (that is, when the
16315 // target is arm or arm64).
16316 ConvertHalfVec = needsConversionOfHalfVec(
16317 true, Context, Input.get()->getType(), Input.get());
16318
16319 // If the operand is a half vector, promote it to a float vector.
16320 if (ConvertHalfVec)
16321 Input = convertVector(Input.get(), Context.FloatTy, *this);
16322 resultType = Input.get()->getType();
16323 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16324 break;
16325 else if (resultType->isVectorType() &&
16326 // The z vector extensions don't allow + or - with bool vectors.
16327 (!Context.getLangOpts().ZVector ||
16328 resultType->castAs<VectorType>()->getVectorKind() !=
16330 break;
16331 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16332 break;
16333 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16334 Opc == UO_Plus && resultType->isPointerType())
16335 break;
16336
16337 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16338 << resultType << Input.get()->getSourceRange());
16339
16340 case UO_Not: // bitwise complement
16341 Input = UsualUnaryConversions(Input.get());
16342 if (Input.isInvalid())
16343 return ExprError();
16344 resultType = Input.get()->getType();
16345 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16346 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16347 // C99 does not support '~' for complex conjugation.
16348 Diag(OpLoc, diag::ext_integer_complement_complex)
16349 << resultType << Input.get()->getSourceRange();
16350 else if (resultType->hasIntegerRepresentation())
16351 break;
16352 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16353 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16354 // on vector float types.
16355 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16356 if (!T->isIntegerType())
16357 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16358 << resultType << Input.get()->getSourceRange());
16359 } else {
16360 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16361 << resultType << Input.get()->getSourceRange());
16362 }
16363 break;
16364
16365 case UO_LNot: // logical negation
16366 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16368 if (Input.isInvalid())
16369 return ExprError();
16370 resultType = Input.get()->getType();
16371
16372 // Though we still have to promote half FP to float...
16373 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16374 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
16375 .get();
16376 resultType = Context.FloatTy;
16377 }
16378
16379 // WebAsembly tables can't be used in unary expressions.
16380 if (resultType->isPointerType() &&
16382 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16383 << resultType << Input.get()->getSourceRange());
16384 }
16385
16386 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16387 // C99 6.5.3.3p1: ok, fallthrough;
16388 if (Context.getLangOpts().CPlusPlus) {
16389 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16390 // operand contextually converted to bool.
16391 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16392 ScalarTypeToBooleanCastKind(resultType));
16393 } else if (Context.getLangOpts().OpenCL &&
16394 Context.getLangOpts().OpenCLVersion < 120) {
16395 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16396 // operate on scalar float types.
16397 if (!resultType->isIntegerType() && !resultType->isPointerType())
16398 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16399 << resultType << Input.get()->getSourceRange());
16400 }
16401 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16402 !resultType->hasBooleanRepresentation()) {
16403 // HLSL unary logical 'not' behaves like C++, which states that the
16404 // operand is converted to bool and the result is bool, however HLSL
16405 // extends this property to vectors.
16406 const VectorType *VTy = resultType->castAs<VectorType>();
16407 resultType =
16408 Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
16409
16410 Input = ImpCastExprToType(
16411 Input.get(), resultType,
16413 .get();
16414 break;
16415 } else if (resultType->isExtVectorType()) {
16416 if (Context.getLangOpts().OpenCL &&
16417 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16418 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16419 // operate on vector float types.
16420 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16421 if (!T->isIntegerType())
16422 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16423 << resultType << Input.get()->getSourceRange());
16424 }
16425 // Vector logical not returns the signed variant of the operand type.
16426 resultType = GetSignedVectorType(resultType);
16427 break;
16428 } else if (Context.getLangOpts().CPlusPlus &&
16429 resultType->isVectorType()) {
16430 const VectorType *VTy = resultType->castAs<VectorType>();
16431 if (VTy->getVectorKind() != VectorKind::Generic)
16432 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16433 << resultType << Input.get()->getSourceRange());
16434
16435 // Vector logical not returns the signed variant of the operand type.
16436 resultType = GetSignedVectorType(resultType);
16437 break;
16438 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16439 resultType = Context.getLogicalOperationType();
16440 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(InputExpr);
16441 break;
16442 } else {
16443 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16444 << resultType << Input.get()->getSourceRange());
16445 }
16446
16447 // LNot always has type int. C99 6.5.3.3p5.
16448 // In C++, it's bool. C++ 5.3.1p8
16449 resultType = Context.getLogicalOperationType();
16450 break;
16451 case UO_Real:
16452 case UO_Imag:
16453 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16454 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16455 // ordinary complex l-values to ordinary l-values and all other values to
16456 // r-values.
16457 if (Input.isInvalid())
16458 return ExprError();
16459 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16460 if (Input.get()->isGLValue() &&
16461 Input.get()->getObjectKind() == OK_Ordinary)
16462 VK = Input.get()->getValueKind();
16463 } else if (!getLangOpts().CPlusPlus) {
16464 // In C, a volatile scalar is read by __imag. In C++, it is not.
16465 Input = DefaultLvalueConversion(Input.get());
16466 }
16467 break;
16468 case UO_Extension:
16469 resultType = Input.get()->getType();
16470 VK = Input.get()->getValueKind();
16471 OK = Input.get()->getObjectKind();
16472 break;
16473 case UO_Coawait:
16474 // It's unnecessary to represent the pass-through operator co_await in the
16475 // AST; just return the input expression instead.
16476 assert(!Input.get()->getType()->isDependentType() &&
16477 "the co_await expression must be non-dependant before "
16478 "building operator co_await");
16479 return Input;
16480 }
16481 }
16482 if (resultType.isNull() || Input.isInvalid())
16483 return ExprError();
16484
16485 // Check for array bounds violations in the operand of the UnaryOperator,
16486 // except for the '*' and '&' operators that have to be handled specially
16487 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16488 // that are explicitly defined as valid by the standard).
16489 if (Opc != UO_AddrOf && Opc != UO_Deref)
16490 CheckArrayAccess(Input.get());
16491
16492 auto *UO =
16493 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16494 OpLoc, CanOverflow, CurFPFeatureOverrides());
16495
16496 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16497 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16499 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16500
16501 // Convert the result back to a half vector.
16502 if (ConvertHalfVec)
16503 return convertVector(UO, Context.HalfTy, *this);
16504 return UO;
16505}
16506
16508 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16509 if (!DRE->getQualifier())
16510 return false;
16511
16512 ValueDecl *VD = DRE->getDecl();
16513 if (!VD->isCXXClassMember())
16514 return false;
16515
16517 return true;
16518 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16519 return Method->isImplicitObjectMemberFunction();
16520
16521 return false;
16522 }
16523
16524 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16525 if (!ULE->getQualifier())
16526 return false;
16527
16528 for (NamedDecl *D : ULE->decls()) {
16529 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16530 if (Method->isImplicitObjectMemberFunction())
16531 return true;
16532 } else {
16533 // Overload set does not contain methods.
16534 break;
16535 }
16536 }
16537
16538 return false;
16539 }
16540
16541 return false;
16542}
16543
16545 UnaryOperatorKind Opc, Expr *Input,
16546 bool IsAfterAmp) {
16547 // First things first: handle placeholders so that the
16548 // overloaded-operator check considers the right type.
16549 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16550 // Increment and decrement of pseudo-object references.
16551 if (pty->getKind() == BuiltinType::PseudoObject &&
16553 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
16554
16555 // extension is always a builtin operator.
16556 if (Opc == UO_Extension)
16557 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16558
16559 // & gets special logic for several kinds of placeholder.
16560 // The builtin code knows what to do.
16561 if (Opc == UO_AddrOf &&
16562 (pty->getKind() == BuiltinType::Overload ||
16563 pty->getKind() == BuiltinType::UnknownAny ||
16564 pty->getKind() == BuiltinType::BoundMember))
16565 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16566
16567 // Anything else needs to be handled now.
16569 if (Result.isInvalid()) return ExprError();
16570 Input = Result.get();
16571 }
16572
16573 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16575 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16576 // Find all of the overloaded operators visible from this point.
16577 UnresolvedSet<16> Functions;
16579 if (S && OverOp != OO_None)
16580 LookupOverloadedOperatorName(OverOp, S, Functions);
16581
16582 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16583 }
16584
16585 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16586}
16587
16589 Expr *Input, bool IsAfterAmp) {
16590 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16591 IsAfterAmp);
16592}
16593
16595 LabelDecl *TheDecl) {
16596 TheDecl->markUsed(Context);
16597 // Create the AST node. The address of a label always has type 'void*'.
16598 auto *Res = new (Context) AddrLabelExpr(
16599 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16600
16601 if (getCurFunction())
16602 getCurFunction()->AddrLabels.push_back(Res);
16603
16604 return Res;
16605}
16606
16609 // Make sure we diagnose jumping into a statement expression.
16611}
16612
16614 // Note that function is also called by TreeTransform when leaving a
16615 // StmtExpr scope without rebuilding anything.
16616
16619}
16620
16622 SourceLocation RPLoc) {
16623 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16624}
16625
16627 SourceLocation RPLoc, unsigned TemplateDepth) {
16628 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16629 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16630
16633 assert(!Cleanup.exprNeedsCleanups() &&
16634 "cleanups within StmtExpr not correctly bound!");
16636
16637 // FIXME: there are a variety of strange constraints to enforce here, for
16638 // example, it is not possible to goto into a stmt expression apparently.
16639 // More semantic analysis is needed.
16640
16641 // If there are sub-stmts in the compound stmt, take the type of the last one
16642 // as the type of the stmtexpr.
16643 QualType Ty = Context.VoidTy;
16644 bool StmtExprMayBindToTemp = false;
16645 if (!Compound->body_empty()) {
16646 if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
16647 if (const Expr *Value = LastStmt->getExprStmt()) {
16648 StmtExprMayBindToTemp = true;
16649 Ty = Value->getType();
16650 }
16651 }
16652 }
16653
16654 // FIXME: Check that expression type is complete/non-abstract; statement
16655 // expressions are not lvalues.
16656 Expr *ResStmtExpr =
16657 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16658 if (StmtExprMayBindToTemp)
16659 return MaybeBindToTemporary(ResStmtExpr);
16660 return ResStmtExpr;
16661}
16662
16664 if (ER.isInvalid())
16665 return ExprError();
16666
16667 // Do function/array conversion on the last expression, but not
16668 // lvalue-to-rvalue. However, initialize an unqualified type.
16670 if (ER.isInvalid())
16671 return ExprError();
16672 Expr *E = ER.get();
16673
16674 if (E->isTypeDependent())
16675 return E;
16676
16677 // In ARC, if the final expression ends in a consume, splice
16678 // the consume out and bind it later. In the alternate case
16679 // (when dealing with a retainable type), the result
16680 // initialization will create a produce. In both cases the
16681 // result will be +1, and we'll need to balance that out with
16682 // a bind.
16683 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16684 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16685 return Cast->getSubExpr();
16686
16687 // FIXME: Provide a better location for the initialization.
16691 SourceLocation(), E);
16692}
16693
16695 TypeSourceInfo *TInfo,
16696 const Designation &Desig,
16697 SourceLocation RParenLoc) {
16698 QualType ArgTy = TInfo->getType();
16699 bool Dependent = ArgTy->isDependentType();
16700 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16701
16702 // We must have at least one component that refers to the type, and the first
16703 // one is known to be a field designator. Verify that the ArgTy represents
16704 // a struct/union/class.
16705 if (!Dependent && !ArgTy->isRecordType())
16706 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16707 << ArgTy << TypeRange);
16708
16709 // Type must be complete per C99 7.17p3 because a declaring a variable
16710 // with an incomplete type would be ill-formed.
16711 if (!Dependent
16712 && RequireCompleteType(BuiltinLoc, ArgTy,
16713 diag::err_offsetof_incomplete_type, TypeRange))
16714 return ExprError();
16715
16716 bool DidWarnAboutNonPOD = false;
16717 QualType CurrentType = ArgTy;
16720 for (unsigned I = 0, N = Desig.getNumDesignators(); I != N; ++I) {
16721 const Designator &D = Desig.getDesignator(I);
16722 assert(!D.isArrayRangeDesignator());
16723 if (D.isArrayDesignator()) {
16724 // Offset of an array sub-field. TODO: Should we allow vector elements?
16725 if (!CurrentType->isDependentType()) {
16726 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16727 if(!AT)
16728 return ExprError(Diag(D.getEndLoc(), diag::err_offsetof_array_type)
16729 << CurrentType);
16730 CurrentType = AT->getElementType();
16731 } else
16732 CurrentType = Context.DependentTy;
16733
16735 if (IdxRval.isInvalid())
16736 return ExprError();
16737 Expr *Idx = IdxRval.get();
16738
16739 // The expression must be an integral expression.
16740 // FIXME: An integral constant expression?
16741 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16742 !Idx->getType()->isIntegerType())
16743 return ExprError(
16744 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16745 << Idx->getSourceRange());
16746
16747 // Record this array index.
16748 Comps.push_back(
16749 OffsetOfNode(D.getBeginLoc(), Exprs.size(), D.getEndLoc()));
16750 Exprs.push_back(Idx);
16751 continue;
16752 }
16753
16754 assert(D.isFieldDesignator());
16755 const IdentifierInfo *Name = D.getFieldDecl();
16756
16757 // Offset of a field.
16758 if (CurrentType->isDependentType()) {
16759 // We have the offset of a field, but we can't look into the dependent
16760 // type. Just record the identifier of the field.
16761 Comps.push_back(OffsetOfNode(D.getBeginLoc(), Name, D.getEndLoc()));
16762 CurrentType = Context.DependentTy;
16763 continue;
16764 }
16765
16766 // We need to have a complete type to look into.
16767 if (RequireCompleteType(D.getBeginLoc(), CurrentType,
16768 diag::err_offsetof_incomplete_type))
16769 return ExprError();
16770
16771 // Look for the designated field.
16772 auto *RD = CurrentType->getAsRecordDecl();
16773 if (!RD)
16774 return ExprError(Diag(D.getEndLoc(), diag::err_offsetof_record_type)
16775 << CurrentType);
16776
16777 // C++ [lib.support.types]p5:
16778 // The macro offsetof accepts a restricted set of type arguments in this
16779 // International Standard. type shall be a POD structure or a POD union
16780 // (clause 9).
16781 // C++11 [support.types]p4:
16782 // If type is not a standard-layout class (Clause 9), the results are
16783 // undefined.
16784 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16785 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16786 unsigned DiagID =
16787 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16788 : diag::ext_offsetof_non_pod_type;
16789
16790 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16791 Diag(BuiltinLoc, DiagID)
16793 << CurrentType;
16794 DidWarnAboutNonPOD = true;
16795 }
16796 }
16797
16798 // Look for the field.
16799 LookupResult R(*this, Name, D.getBeginLoc(), LookupMemberName);
16800 LookupQualifiedName(R, RD);
16801 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16802 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16803 if (!MemberDecl) {
16804 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16805 MemberDecl = IndirectMemberDecl->getAnonField();
16806 }
16807
16808 if (!MemberDecl) {
16809 // Lookup could be ambiguous when looking up a placeholder variable
16810 // __builtin_offsetof(S, _).
16811 // In that case we would already have emitted a diagnostic
16812 if (!R.isAmbiguous())
16813 Diag(BuiltinLoc, diag::err_no_member)
16814 << Name << RD << SourceRange(D.getBeginLoc(), D.getEndLoc());
16815 return ExprError();
16816 }
16817
16818 // C99 7.17p3:
16819 // (If the specified member is a bit-field, the behavior is undefined.)
16820 //
16821 // We diagnose this as an error.
16822 if (MemberDecl->isBitField()) {
16823 Diag(D.getEndLoc(), diag::err_offsetof_bitfield)
16824 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
16825 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16826 return ExprError();
16827 }
16828
16829 RecordDecl *Parent = MemberDecl->getParent();
16830 if (IndirectMemberDecl)
16831 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16832
16833 // If the member was found in a base class, introduce OffsetOfNodes for
16834 // the base class indirections.
16835 CXXBasePaths Paths;
16836 if (IsDerivedFrom(D.getBeginLoc(), CurrentType,
16837 Context.getCanonicalTagType(Parent), Paths)) {
16838 if (Paths.getDetectedVirtual()) {
16839 Diag(D.getEndLoc(), diag::err_offsetof_field_of_virtual_base)
16840 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
16841 return ExprError();
16842 }
16843
16844 CXXBasePath &Path = Paths.front();
16845 for (const CXXBasePathElement &B : Path)
16846 Comps.push_back(OffsetOfNode(B.Base));
16847 }
16848
16849 if (IndirectMemberDecl) {
16850 for (auto *FI : IndirectMemberDecl->chain()) {
16851 assert(isa<FieldDecl>(FI));
16852 Comps.push_back(
16854 }
16855 } else
16856 Comps.push_back(OffsetOfNode(D.getBeginLoc(), MemberDecl, D.getEndLoc()));
16857
16858 CurrentType = MemberDecl->getType().getNonReferenceType();
16859 }
16860
16861 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16862 Comps, Exprs, RParenLoc);
16863}
16864
16867 ParsedType ParsedArgTy,
16868 const Designation &Desig,
16869 SourceLocation RParenLoc) {
16870
16871 TypeSourceInfo *ArgTInfo;
16872 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16873 if (ArgTy.isNull())
16874 return ExprError();
16875
16876 if (!ArgTInfo)
16877 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16878
16879 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Desig, RParenLoc);
16880}
16881
16883 Expr *CondExpr,
16884 Expr *LHSExpr, Expr *RHSExpr,
16885 SourceLocation RPLoc) {
16886 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16887
16890 QualType resType;
16891 bool CondIsTrue = false;
16892 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16893 resType = Context.DependentTy;
16894 } else {
16895 // The conditional expression is required to be a constant expression.
16896 llvm::APSInt condEval(32);
16898 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16899 if (CondICE.isInvalid())
16900 return ExprError();
16901 CondExpr = CondICE.get();
16902 CondIsTrue = condEval.getZExtValue();
16903
16904 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16905 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16906
16907 resType = ActiveExpr->getType();
16908 VK = ActiveExpr->getValueKind();
16909 OK = ActiveExpr->getObjectKind();
16910 }
16911
16912 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16913 resType, VK, OK, RPLoc, CondIsTrue);
16914}
16915
16916//===----------------------------------------------------------------------===//
16917// Clang Extensions.
16918//===----------------------------------------------------------------------===//
16919
16920void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16922
16923 if (LangOpts.CPlusPlus) {
16925 Decl *ManglingContextDecl;
16926 std::tie(MCtx, ManglingContextDecl) =
16927 getCurrentMangleNumberContext(Block->getDeclContext());
16928 if (MCtx) {
16929 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16930 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16931 }
16932 }
16933
16934 PushBlockScope(CurScope, Block);
16935 CurContext->addDecl(Block);
16936 if (CurScope)
16937 PushDeclContext(CurScope, Block);
16938 else
16939 CurContext = Block;
16940
16942
16943 // Enter a new evaluation context to insulate the block from any
16944 // cleanups from the enclosing full-expression.
16947}
16948
16950 Scope *CurScope) {
16951 assert(ParamInfo.getIdentifier() == nullptr &&
16952 "block-id should have no identifier!");
16953 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16954 BlockScopeInfo *CurBlock = getCurBlock();
16955
16956 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16957 QualType T = Sig->getType();
16959
16960 // GetTypeForDeclarator always produces a function type for a block
16961 // literal signature. Furthermore, it is always a FunctionProtoType
16962 // unless the function was written with a typedef.
16963 assert(T->isFunctionType() &&
16964 "GetTypeForDeclarator made a non-function block signature");
16965
16966 // Look for an explicit signature in that function type.
16967 FunctionProtoTypeLoc ExplicitSignature;
16968
16969 if ((ExplicitSignature = Sig->getTypeLoc()
16971
16972 // Check whether that explicit signature was synthesized by
16973 // GetTypeForDeclarator. If so, don't save that as part of the
16974 // written signature.
16975 if (ExplicitSignature.getLocalRangeBegin() ==
16976 ExplicitSignature.getLocalRangeEnd()) {
16977 // This would be much cheaper if we stored TypeLocs instead of
16978 // TypeSourceInfos.
16979 TypeLoc Result = ExplicitSignature.getReturnLoc();
16980 unsigned Size = Result.getFullDataSize();
16981 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16982 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16983
16984 ExplicitSignature = FunctionProtoTypeLoc();
16985 }
16986 }
16987
16988 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16989 CurBlock->FunctionType = T;
16990
16991 const auto *Fn = T->castAs<FunctionType>();
16992 QualType RetTy = Fn->getReturnType();
16993 bool isVariadic =
16994 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16995
16996 CurBlock->TheDecl->setIsVariadic(isVariadic);
16997
16998 // Context.DependentTy is used as a placeholder for a missing block
16999 // return type. TODO: what should we do with declarators like:
17000 // ^ * { ... }
17001 // If the answer is "apply template argument deduction"....
17002 if (RetTy != Context.DependentTy) {
17003 CurBlock->ReturnType = RetTy;
17004 CurBlock->TheDecl->setBlockMissingReturnType(false);
17005 CurBlock->HasImplicitReturnType = false;
17006 }
17007
17008 // Push block parameters from the declarator if we had them.
17010 if (ExplicitSignature) {
17011 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
17012 ParmVarDecl *Param = ExplicitSignature.getParam(I);
17013 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
17014 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
17015 // Diagnose this as an extension in C17 and earlier.
17016 if (!getLangOpts().C23)
17017 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
17018 }
17019 Params.push_back(Param);
17020 }
17021
17022 // Fake up parameter variables if we have a typedef, like
17023 // ^ fntype { ... }
17024 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
17025 for (const auto &I : Fn->param_types()) {
17027 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
17028 Params.push_back(Param);
17029 }
17030 }
17031
17032 // Set the parameters on the block decl.
17033 if (!Params.empty()) {
17034 CurBlock->TheDecl->setParams(Params);
17036 /*CheckParameterNames=*/false);
17037 }
17038
17039 // Finally we can process decl attributes.
17040 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
17041
17042 // Put the parameter variables in scope.
17043 for (auto *AI : CurBlock->TheDecl->parameters()) {
17044 AI->setOwningFunction(CurBlock->TheDecl);
17045
17046 // If this has an identifier, add it to the scope stack.
17047 if (AI->getIdentifier()) {
17048 CheckShadow(CurBlock->TheScope, AI);
17049
17050 PushOnScopeChains(AI, CurBlock->TheScope);
17051 }
17052
17053 if (AI->isInvalidDecl())
17054 CurBlock->TheDecl->setInvalidDecl();
17055 }
17056}
17057
17058void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17059 // Leave the expression-evaluation context.
17062
17063 // Pop off CurBlock, handle nested blocks.
17066}
17067
17069 Stmt *Body, Scope *CurScope) {
17070 // If blocks are disabled, emit an error.
17071 if (!LangOpts.Blocks)
17072 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
17073
17074 // Leave the expression-evaluation context.
17077 assert(!Cleanup.exprNeedsCleanups() &&
17078 "cleanups within block not correctly bound!");
17080
17082 BlockDecl *BD = BSI->TheDecl;
17083
17085
17086 if (BSI->HasImplicitReturnType)
17088
17089 QualType RetTy = Context.VoidTy;
17090 if (!BSI->ReturnType.isNull())
17091 RetTy = BSI->ReturnType;
17092
17093 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17094 QualType BlockTy;
17095
17096 // If the user wrote a function type in some form, try to use that.
17097 if (!BSI->FunctionType.isNull()) {
17098 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17099
17100 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17101 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
17102
17103 // Turn protoless block types into nullary block types.
17104 if (isa<FunctionNoProtoType>(FTy)) {
17106 EPI.ExtInfo = Ext;
17107 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17108
17109 // Otherwise, if we don't need to change anything about the function type,
17110 // preserve its sugar structure.
17111 } else if (FTy->getReturnType() == RetTy &&
17112 (!NoReturn || FTy->getNoReturnAttr())) {
17113 BlockTy = BSI->FunctionType;
17114
17115 // Otherwise, make the minimal modifications to the function type.
17116 } else {
17119 EPI.TypeQuals = Qualifiers();
17120 EPI.ExtInfo = Ext;
17121 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
17122 }
17123
17124 // If we don't have a function type, just build one from nothing.
17125 } else {
17127 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
17128 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17129 }
17130
17132 BlockTy = Context.getBlockPointerType(BlockTy);
17133
17134 // If needed, diagnose invalid gotos and switches in the block.
17135 if (getCurFunction()->NeedsScopeChecking() &&
17136 !PP.isCodeCompletionEnabled())
17138
17139 BD->setBody(cast<CompoundStmt>(Body));
17140
17141 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17143
17144 // Try to apply the named return value optimization. We have to check again
17145 // if we can do this, though, because blocks keep return statements around
17146 // to deduce an implicit return type.
17147 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17148 !BD->isDependentContext())
17149 computeNRVO(Body, BSI);
17150
17156
17158
17159 // Set the captured variables on the block.
17161 for (Capture &Cap : BSI->Captures) {
17162 if (Cap.isInvalid() || Cap.isThisCapture())
17163 continue;
17164 // Cap.getVariable() is always a VarDecl because
17165 // blocks cannot capture structured bindings or other ValueDecl kinds.
17166 auto *Var = cast<VarDecl>(Cap.getVariable());
17167 Expr *CopyExpr = nullptr;
17168 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17169 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17170 // The capture logic needs the destructor, so make sure we mark it.
17171 // Usually this is unnecessary because most local variables have
17172 // their destructors marked at declaration time, but parameters are
17173 // an exception because it's technically only the call site that
17174 // actually requires the destructor.
17175 if (isa<ParmVarDecl>(Var))
17177
17178 // Enter a separate potentially-evaluated context while building block
17179 // initializers to isolate their cleanups from those of the block
17180 // itself.
17181 // FIXME: Is this appropriate even when the block itself occurs in an
17182 // unevaluated operand?
17185
17186 SourceLocation Loc = Cap.getLocation();
17187
17189 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
17190
17191 // According to the blocks spec, the capture of a variable from
17192 // the stack requires a const copy constructor. This is not true
17193 // of the copy/move done to move a __block variable to the heap.
17194 if (!Result.isInvalid() &&
17195 !Result.get()->getType().isConstQualified()) {
17197 Result.get()->getType().withConst(),
17198 CK_NoOp, VK_LValue);
17199 }
17200
17201 if (!Result.isInvalid()) {
17203 InitializedEntity::InitializeBlock(Var->getLocation(),
17204 Cap.getCaptureType()),
17205 Loc, Result.get());
17206 }
17207
17208 // Build a full-expression copy expression if initialization
17209 // succeeded and used a non-trivial constructor. Recover from
17210 // errors by pretending that the copy isn't necessary.
17211 if (!Result.isInvalid() &&
17212 !cast<CXXConstructExpr>(Result.get())->getConstructor()
17213 ->isTrivial()) {
17215 CopyExpr = Result.get();
17216 }
17217 }
17218 }
17219
17220 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17221 CopyExpr);
17222 Captures.push_back(NewCap);
17223 }
17224 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
17225
17226 // Pop the block scope now but keep it alive to the end of this function.
17228 AnalysisWarnings.getPolicyInEffectAt(Body->getEndLoc());
17229 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
17230
17231 BlockExpr *Result = new (Context)
17232 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17233
17234 // If the block isn't obviously global, i.e. it captures anything at
17235 // all, then we need to do a few things in the surrounding context:
17236 if (Result->getBlockDecl()->hasCaptures()) {
17237 // First, this expression has a new cleanup object.
17238 ExprCleanupObjects.push_back(Result->getBlockDecl());
17239 Cleanup.setExprNeedsCleanups(true);
17240
17241 // It also gets a branch-protected scope if any of the captured
17242 // variables needs destruction.
17243 for (const auto &CI : Result->getBlockDecl()->captures()) {
17244 const VarDecl *var = CI.getVariable();
17245 if (var->getType().isDestructedType() != QualType::DK_none) {
17247 break;
17248 }
17249 }
17250 }
17251
17252 if (getCurFunction())
17253 getCurFunction()->addBlock(BD);
17254
17255 // This can happen if the block's return type is deduced, but
17256 // the return expression is invalid.
17257 if (BD->isInvalidDecl())
17258 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
17259 {Result}, Result->getType());
17260 return Result;
17261}
17262
17264 SourceLocation RPLoc) {
17265 TypeSourceInfo *TInfo;
17266 GetTypeFromParser(Ty, &TInfo);
17267 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17268}
17269
17271 Expr *E, TypeSourceInfo *TInfo,
17272 SourceLocation RPLoc) {
17273 Expr *OrigExpr = E;
17275
17276 // CUDA device global function does not support varargs.
17277 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17278 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
17281 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
17282 }
17283 }
17284
17285 // NVPTX does not support va_arg expression.
17286 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17287 Context.getTargetInfo().getTriple().isNVPTX())
17288 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
17289
17290 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17291 // as Microsoft ABI on an actual Microsoft platform, where
17292 // __builtin_ms_va_list and __builtin_va_list are the same.)
17293 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17294 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17295 QualType MSVaListType = Context.getBuiltinMSVaListType();
17296 if (Context.hasSameType(MSVaListType, E->getType())) {
17297 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
17298 return ExprError();
17299 VAKind = VAArgExpr::VA_MS;
17300 }
17301 }
17302
17303 // Get the va_list type
17304 QualType VaListType = Context.getBuiltinVaListType();
17305
17306 // It might be a __builtin_zos_va_list!
17307 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinZOSVaList()) {
17308 // E->getType() can be:
17309 // - va_list: equal to array (char*)[2] (inside function)
17310 // - char **: decayed array (va_list passed as parameter)
17311 // We need to check for both cases.
17312 QualType ZOSVaListType = Context.getBuiltinZOSVaListType();
17313 assert(ZOSVaListType->isArrayType() &&
17314 "__builtin_zos_va_list must be an array type");
17315 QualType DecayedType = Context.getArrayDecayedType(ZOSVaListType);
17316 if (Context.hasSameType(ZOSVaListType, E->getType()) ||
17317 Context.hasSameType(DecayedType, E->getType())) {
17318 VAKind = VAArgExpr::VA_ZOS;
17319 VaListType = ZOSVaListType;
17320 }
17321 }
17322
17323 if (VAKind != VAArgExpr::VA_MS) {
17324 if (VaListType->isArrayType()) {
17325 // Deal with implicit array decay; for example, on x86-64,
17326 // va_list is an array, but it's supposed to decay to
17327 // a pointer for va_arg.
17328 VaListType = Context.getArrayDecayedType(VaListType);
17329 // Make sure the input expression also decays appropriately.
17331 if (Result.isInvalid())
17332 return ExprError();
17333 E = Result.get();
17334 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17335 // If va_list is a record type and we are compiling in C++ mode,
17336 // check the argument using reference binding.
17338 Context, Context.getLValueReferenceType(VaListType), false);
17340 if (Init.isInvalid())
17341 return ExprError();
17342 E = Init.getAs<Expr>();
17343 } else {
17344 // Otherwise, the va_list argument must be an l-value because
17345 // it is modified by va_arg.
17346 if (!E->isTypeDependent() &&
17347 CheckForModifiableLvalue(E, BuiltinLoc, *this))
17348 return ExprError();
17349 }
17350 }
17351
17352 if ((VAKind != VAArgExpr::VA_MS) && !E->isTypeDependent() &&
17353 !Context.hasSameType(VaListType, E->getType()))
17354 return ExprError(
17355 Diag(E->getBeginLoc(),
17356 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17357 << OrigExpr->getType() << E->getSourceRange());
17358
17359 if (!TInfo->getType()->isDependentType()) {
17360 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17361 diag::err_second_parameter_to_va_arg_incomplete,
17362 TInfo->getTypeLoc()))
17363 return ExprError();
17364
17366 TInfo->getType(),
17367 diag::err_second_parameter_to_va_arg_abstract,
17368 TInfo->getTypeLoc()))
17369 return ExprError();
17370
17371 if (!TInfo->getType().isPODType(Context)) {
17372 Diag(TInfo->getTypeLoc().getBeginLoc(),
17373 TInfo->getType()->isObjCLifetimeType()
17374 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17375 : diag::warn_second_parameter_to_va_arg_not_pod)
17376 << TInfo->getType()
17377 << TInfo->getTypeLoc().getSourceRange();
17378 }
17379
17380 if (TInfo->getType()->isArrayType()) {
17382 PDiag(diag::warn_second_parameter_to_va_arg_array)
17383 << TInfo->getType()
17384 << TInfo->getTypeLoc().getSourceRange());
17385 }
17386
17387 // Check for va_arg where arguments of the given type will be promoted
17388 // (i.e. this va_arg is guaranteed to have undefined behavior).
17389 QualType PromoteType;
17390 if (Context.isPromotableIntegerType(TInfo->getType())) {
17391 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17392 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17393 // and C23 7.16.1.1p2 says, in part:
17394 // If type is not compatible with the type of the actual next argument
17395 // (as promoted according to the default argument promotions), the
17396 // behavior is undefined, except for the following cases:
17397 // - both types are pointers to qualified or unqualified versions of
17398 // compatible types;
17399 // - one type is compatible with a signed integer type, the other
17400 // type is compatible with the corresponding unsigned integer type,
17401 // and the value is representable in both types;
17402 // - one type is pointer to qualified or unqualified void and the
17403 // other is a pointer to a qualified or unqualified character type;
17404 // - or, the type of the next argument is nullptr_t and type is a
17405 // pointer type that has the same representation and alignment
17406 // requirements as a pointer to a character type.
17407 // Given that type compatibility is the primary requirement (ignoring
17408 // qualifications), you would think we could call typesAreCompatible()
17409 // directly to test this. However, in C++, that checks for *same type*,
17410 // which causes false positives when passing an enumeration type to
17411 // va_arg. Instead, get the underlying type of the enumeration and pass
17412 // that.
17413 QualType UnderlyingType = TInfo->getType();
17414 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17415 UnderlyingType = ED->getIntegerType();
17416 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17417 /*CompareUnqualified*/ true))
17418 PromoteType = QualType();
17419
17420 // If the types are still not compatible, we need to test whether the
17421 // promoted type and the underlying type are the same except for
17422 // signedness. Ask the AST for the correctly corresponding type and see
17423 // if that's compatible.
17424 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17425 PromoteType->isUnsignedIntegerType() !=
17426 UnderlyingType->isUnsignedIntegerType()) {
17427 UnderlyingType =
17428 UnderlyingType->isUnsignedIntegerType()
17429 ? Context.getCorrespondingSignedType(UnderlyingType)
17430 : Context.getCorrespondingUnsignedType(UnderlyingType);
17431 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17432 /*CompareUnqualified*/ true))
17433 PromoteType = QualType();
17434 }
17435 }
17436 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17437 PromoteType = Context.DoubleTy;
17438 if (!PromoteType.isNull())
17440 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17441 << TInfo->getType()
17442 << PromoteType
17443 << TInfo->getTypeLoc().getSourceRange());
17444 }
17445
17447 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, VAKind);
17448}
17449
17451 // The type of __null will be int or long, depending on the size of
17452 // pointers on the target.
17453 QualType Ty;
17454 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17455 if (pw == Context.getTargetInfo().getIntWidth())
17456 Ty = Context.IntTy;
17457 else if (pw == Context.getTargetInfo().getLongWidth())
17458 Ty = Context.LongTy;
17459 else if (pw == Context.getTargetInfo().getLongLongWidth())
17460 Ty = Context.LongLongTy;
17461 else {
17462 llvm_unreachable("I don't know size of pointer!");
17463 }
17464
17465 return new (Context) GNUNullExpr(Ty, TokenLoc);
17466}
17467
17469 CXXRecordDecl *ImplDecl = nullptr;
17470
17471 // Fetch the std::source_location::__impl decl.
17472 if (NamespaceDecl *Std = S.getStdNamespace()) {
17473 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17475 if (S.LookupQualifiedName(ResultSL, Std)) {
17476 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17477 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17479 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17480 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17481 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17482 }
17483 }
17484 }
17485 }
17486
17487 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17488 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17489 return nullptr;
17490 }
17491
17492 // Verify that __impl is a trivial struct type, with no base classes, and with
17493 // only the four expected fields.
17494 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17495 ImplDecl->getNumBases() != 0) {
17496 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17497 return nullptr;
17498 }
17499
17500 unsigned Count = 0;
17501 for (FieldDecl *F : ImplDecl->fields()) {
17502 StringRef Name = F->getName();
17503
17504 if (Name == "_M_file_name") {
17505 if (F->getType() !=
17507 break;
17508 Count++;
17509 } else if (Name == "_M_function_name") {
17510 if (F->getType() !=
17512 break;
17513 Count++;
17514 } else if (Name == "_M_line") {
17515 if (!F->getType()->isIntegerType())
17516 break;
17517 Count++;
17518 } else if (Name == "_M_column") {
17519 if (!F->getType()->isIntegerType())
17520 break;
17521 Count++;
17522 } else {
17523 Count = 100; // invalid
17524 break;
17525 }
17526 }
17527 if (Count != 4) {
17528 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17529 return nullptr;
17530 }
17531
17532 return ImplDecl;
17533}
17534
17536 SourceLocation BuiltinLoc,
17537 SourceLocation RPLoc) {
17538 QualType ResultTy;
17539 switch (Kind) {
17544 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17545 ResultTy =
17546 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17547 break;
17548 }
17551 ResultTy = Context.UnsignedIntTy;
17552 break;
17556 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17558 return ExprError();
17559 }
17560 ResultTy = Context.getPointerType(
17561 Context.getCanonicalTagType(StdSourceLocationImplDecl).withConst());
17562 break;
17563 }
17564
17565 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17566}
17567
17569 SourceLocation BuiltinLoc,
17570 SourceLocation RPLoc,
17571 DeclContext *ParentContext) {
17572 return new (Context)
17573 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17574}
17575
17577 StringLiteral *BinaryData, StringRef FileName) {
17579 Data->BinaryData = BinaryData;
17580 Data->FileName = FileName;
17581 return new (Context)
17582 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17583 Data->getDataElementCount());
17584}
17585
17587 const Expr *SrcExpr) {
17588 if (!DstType->isFunctionPointerType() ||
17589 !SrcExpr->getType()->isFunctionType())
17590 return false;
17591
17592 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17593 if (!DRE)
17594 return false;
17595
17596 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17597 if (!FD)
17598 return false;
17599
17601 /*Complain=*/true,
17602 SrcExpr->getBeginLoc());
17603}
17604
17606 SourceLocation Loc,
17607 QualType DstType, QualType SrcType,
17608 Expr *SrcExpr, AssignmentAction Action,
17609 bool *Complained) {
17610 if (Complained)
17611 *Complained = false;
17612
17613 // Decode the result (notice that AST's are still created for extensions).
17614 bool CheckInferredResultType = false;
17615 bool isInvalid = false;
17616 unsigned DiagKind = 0;
17617 ConversionFixItGenerator ConvHints;
17618 bool MayHaveConvFixit = false;
17619 bool MayHaveFunctionDiff = false;
17620 const ObjCInterfaceDecl *IFace = nullptr;
17621 const ObjCProtocolDecl *PDecl = nullptr;
17622
17623 switch (ConvTy) {
17625 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17626 return false;
17628 // Still a valid conversion, but we may want to diagnose for C++
17629 // compatibility reasons.
17630 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17631 break;
17633 if (getLangOpts().CPlusPlus) {
17634 DiagKind = diag::err_typecheck_convert_pointer_int;
17635 isInvalid = true;
17636 } else {
17637 DiagKind = diag::ext_typecheck_convert_pointer_int;
17638 }
17639 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17640 MayHaveConvFixit = true;
17641 break;
17643 if (getLangOpts().CPlusPlus) {
17644 DiagKind = diag::err_typecheck_convert_int_pointer;
17645 isInvalid = true;
17646 } else {
17647 DiagKind = diag::ext_typecheck_convert_int_pointer;
17648 }
17649 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17650 MayHaveConvFixit = true;
17651 break;
17653 DiagKind =
17654 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17655 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17656 MayHaveConvFixit = true;
17657 break;
17659 if (getLangOpts().CPlusPlus) {
17660 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17661 isInvalid = true;
17662 } else {
17663 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17664 }
17665 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17666 MayHaveConvFixit = true;
17667 break;
17670 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17671 } else if (getLangOpts().CPlusPlus) {
17672 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17673 isInvalid = true;
17674 } else {
17675 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17676 }
17677 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17678 SrcType->isObjCObjectPointerType();
17679 if (CheckInferredResultType) {
17680 SrcType = SrcType.getUnqualifiedType();
17681 DstType = DstType.getUnqualifiedType();
17682 } else {
17683 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17684 }
17685 MayHaveConvFixit = true;
17686 break;
17688 if (getLangOpts().CPlusPlus) {
17689 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17690 isInvalid = true;
17691 } else {
17692 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17693 }
17694 break;
17696 if (getLangOpts().CPlusPlus) {
17697 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17698 isInvalid = true;
17699 } else {
17700 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17701 }
17702 break;
17704 // Perform decay if necessary.
17705 if (SrcType->canDecayToPointerType())
17706 SrcType = Context.getDecayedType(SrcType);
17707
17708 isInvalid = true;
17709
17710 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17711 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17712 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17713 DiagKind = diag::err_typecheck_incompatible_address_space;
17714 break;
17715 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17716 DiagKind = diag::err_typecheck_incompatible_ownership;
17717 break;
17718 } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {
17719 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17720 break;
17721 }
17722
17723 llvm_unreachable("unknown error case for discarding qualifiers!");
17724 // fallthrough
17725 }
17727 if (SrcType->isArrayType())
17728 SrcType = Context.getArrayDecayedType(SrcType);
17729
17730 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17731 break;
17733 // If the qualifiers lost were because we were applying the
17734 // (deprecated) C++ conversion from a string literal to a char*
17735 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17736 // Ideally, this check would be performed in
17737 // checkPointerTypesForAssignment. However, that would require a
17738 // bit of refactoring (so that the second argument is an
17739 // expression, rather than a type), which should be done as part
17740 // of a larger effort to fix checkPointerTypesForAssignment for
17741 // C++ semantics.
17742 if (getLangOpts().CPlusPlus &&
17744 return false;
17745 if (getLangOpts().CPlusPlus) {
17746 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17747 isInvalid = true;
17748 } else {
17749 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17750 }
17751
17752 break;
17754 if (getLangOpts().CPlusPlus) {
17755 isInvalid = true;
17756 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17757 } else {
17758 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17759 }
17760 break;
17762 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17763 isInvalid = true;
17764 break;
17766 DiagKind = diag::err_int_to_block_pointer;
17767 isInvalid = true;
17768 break;
17770 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17771 isInvalid = true;
17772 break;
17774 if (SrcType->isObjCQualifiedIdType()) {
17775 const ObjCObjectPointerType *srcOPT =
17776 SrcType->castAs<ObjCObjectPointerType>();
17777 for (auto *srcProto : srcOPT->quals()) {
17778 PDecl = srcProto;
17779 break;
17780 }
17781 if (const ObjCInterfaceType *IFaceT =
17783 IFace = IFaceT->getDecl();
17784 }
17785 else if (DstType->isObjCQualifiedIdType()) {
17786 const ObjCObjectPointerType *dstOPT =
17787 DstType->castAs<ObjCObjectPointerType>();
17788 for (auto *dstProto : dstOPT->quals()) {
17789 PDecl = dstProto;
17790 break;
17791 }
17792 if (const ObjCInterfaceType *IFaceT =
17794 IFace = IFaceT->getDecl();
17795 }
17796 if (getLangOpts().CPlusPlus) {
17797 DiagKind = diag::err_incompatible_qualified_id;
17798 isInvalid = true;
17799 } else {
17800 DiagKind = diag::warn_incompatible_qualified_id;
17801 }
17802 break;
17803 }
17805 if (getLangOpts().CPlusPlus) {
17806 DiagKind = diag::err_incompatible_vectors;
17807 isInvalid = true;
17808 } else {
17809 DiagKind = diag::warn_incompatible_vectors;
17810 }
17811 break;
17813 DiagKind = diag::err_arc_weak_unavailable_assign;
17814 isInvalid = true;
17815 break;
17817 return false;
17819 assert(!SrcType->isFunctionType() &&
17820 "Unexpected function type found in IncompatibleOBTKinds assignment");
17821 if (SrcType->canDecayToPointerType())
17822 SrcType = Context.getDecayedType(SrcType);
17823
17824 auto getOBTKindName = [](QualType Ty) -> StringRef {
17825 if (Ty->isPointerType())
17826 Ty = Ty->getPointeeType();
17827 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
17828 return OBT->getBehaviorKind() ==
17829 OverflowBehaviorType::OverflowBehaviorKind::Trap
17830 ? "__ob_trap"
17831 : "__ob_wrap";
17832 }
17833 llvm_unreachable("OBT kind unhandled");
17834 };
17835
17836 Diag(Loc, diag::err_incompatible_obt_kinds_assignment)
17837 << DstType << SrcType << getOBTKindName(DstType)
17838 << getOBTKindName(SrcType);
17839 isInvalid = true;
17840 return true;
17841 }
17843 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17844 if (Complained)
17845 *Complained = true;
17846 return true;
17847 }
17848
17849 DiagKind = diag::err_typecheck_convert_incompatible;
17850 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17851 MayHaveConvFixit = true;
17852 isInvalid = true;
17853 MayHaveFunctionDiff = true;
17854 break;
17855 }
17856
17857 QualType FirstType, SecondType;
17858 switch (Action) {
17861 // The destination type comes first.
17862 FirstType = DstType;
17863 SecondType = SrcType;
17864 break;
17865
17872 // The source type comes first.
17873 FirstType = SrcType;
17874 SecondType = DstType;
17875 break;
17876 }
17877
17878 PartialDiagnostic FDiag = PDiag(DiagKind);
17879 AssignmentAction ActionForDiag = Action;
17881 ActionForDiag = AssignmentAction::Passing;
17882
17883 FDiag << FirstType << SecondType << ActionForDiag
17884 << SrcExpr->getSourceRange();
17885
17886 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17887 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17888 auto isPlainChar = [](const clang::Type *Type) {
17889 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17890 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17891 };
17892 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17893 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17894 }
17895
17896 // If we can fix the conversion, suggest the FixIts.
17897 if (!ConvHints.isNull()) {
17898 for (FixItHint &H : ConvHints.Hints)
17899 FDiag << H;
17900 }
17901
17902 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17903
17904 if (MayHaveFunctionDiff)
17905 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17906
17907 Diag(Loc, FDiag);
17908 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17909 DiagKind == diag::err_incompatible_qualified_id) &&
17910 PDecl && IFace && !IFace->hasDefinition())
17911 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17912 << IFace << PDecl;
17913
17914 if (SecondType == Context.OverloadTy)
17916 FirstType, /*TakingAddress=*/true);
17917
17918 if (CheckInferredResultType)
17920
17921 if (Action == AssignmentAction::Returning &&
17924
17925 if (Complained)
17926 *Complained = true;
17927 return isInvalid;
17928}
17929
17931 llvm::APSInt *Result,
17932 AllowFoldKind CanFold) {
17933 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17934 public:
17935 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17936 QualType T) override {
17937 return S.Diag(Loc, diag::err_ice_not_integral)
17938 << T << S.LangOpts.CPlusPlus;
17939 }
17940 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17941 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17942 }
17943 } Diagnoser;
17944
17945 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17946}
17947
17949 llvm::APSInt *Result,
17950 unsigned DiagID,
17951 AllowFoldKind CanFold) {
17952 class IDDiagnoser : public VerifyICEDiagnoser {
17953 unsigned DiagID;
17954
17955 public:
17956 IDDiagnoser(unsigned DiagID)
17957 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17958
17959 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17960 return S.Diag(Loc, DiagID);
17961 }
17962 } Diagnoser(DiagID);
17963
17964 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17965}
17966
17972
17975 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17976}
17977
17980 VerifyICEDiagnoser &Diagnoser,
17981 AllowFoldKind CanFold) {
17982 SourceLocation DiagLoc = E->getBeginLoc();
17983
17984 if (getLangOpts().CPlusPlus11) {
17985 // C++11 [expr.const]p5:
17986 // If an expression of literal class type is used in a context where an
17987 // integral constant expression is required, then that class type shall
17988 // have a single non-explicit conversion function to an integral or
17989 // unscoped enumeration type
17990 ExprResult Converted;
17991 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17992 VerifyICEDiagnoser &BaseDiagnoser;
17993 public:
17994 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17995 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17996 BaseDiagnoser.Suppress, true),
17997 BaseDiagnoser(BaseDiagnoser) {}
17998
17999 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
18000 QualType T) override {
18001 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
18002 }
18003
18004 SemaDiagnosticBuilder diagnoseIncomplete(
18005 Sema &S, SourceLocation Loc, QualType T) override {
18006 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
18007 }
18008
18009 SemaDiagnosticBuilder diagnoseExplicitConv(
18010 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18011 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
18012 }
18013
18014 SemaDiagnosticBuilder noteExplicitConv(
18015 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18016 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18017 << ConvTy->isEnumeralType() << ConvTy;
18018 }
18019
18020 SemaDiagnosticBuilder diagnoseAmbiguous(
18021 Sema &S, SourceLocation Loc, QualType T) override {
18022 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
18023 }
18024
18025 SemaDiagnosticBuilder noteAmbiguous(
18026 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18027 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18028 << ConvTy->isEnumeralType() << ConvTy;
18029 }
18030
18031 SemaDiagnosticBuilder diagnoseConversion(
18032 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18033 llvm_unreachable("conversion functions are permitted");
18034 }
18035 } ConvertDiagnoser(Diagnoser);
18036
18037 Converted = PerformContextualImplicitConversion(DiagLoc, E,
18038 ConvertDiagnoser);
18039 if (Converted.isInvalid())
18040 return Converted;
18041 E = Converted.get();
18042 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
18043 // don't try to evaluate it later. We also don't want to return the
18044 // RecoveryExpr here, as it results in this call succeeding, thus callers of
18045 // this function will attempt to use 'Value'.
18046 if (isa<RecoveryExpr>(E))
18047 return ExprError();
18049 return ExprError();
18050 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
18051 // An ICE must be of integral or unscoped enumeration type.
18052 if (!Diagnoser.Suppress)
18053 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
18054 << E->getSourceRange();
18055 return ExprError();
18056 }
18057
18058 ExprResult RValueExpr = DefaultLvalueConversion(E);
18059 if (RValueExpr.isInvalid())
18060 return ExprError();
18061
18062 E = RValueExpr.get();
18063
18064 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18065 // in the non-ICE case.
18068 if (Result)
18070 if (!isa<ConstantExpr>(E))
18073
18074 if (Notes.empty())
18075 return E;
18076
18077 // If our only note is the usual "invalid subexpression" note, just point
18078 // the caret at its location rather than producing an essentially
18079 // redundant note.
18080 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18081 diag::note_invalid_subexpr_in_const_expr) {
18082 DiagLoc = Notes[0].first;
18083 Notes.clear();
18084 }
18085
18086 if (getLangOpts().CPlusPlus) {
18087 if (!Diagnoser.Suppress) {
18088 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18089 for (const PartialDiagnosticAt &Note : Notes)
18090 Diag(Note.first, Note.second);
18091 }
18092 return ExprError();
18093 }
18094
18095 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18096 for (const PartialDiagnosticAt &Note : Notes)
18097 Diag(Note.first, Note.second);
18098
18099 return E;
18100 }
18101
18102 Expr::EvalResult EvalResult;
18104 EvalResult.Diag = &Notes;
18105
18106 // Try to evaluate the expression, and produce diagnostics explaining why it's
18107 // not a constant expression as a side-effect.
18108 bool Folded =
18109 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
18110 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
18111 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
18112
18113 if (!isa<ConstantExpr>(E))
18114 E = ConstantExpr::Create(Context, E, EvalResult.Val);
18115
18116 // In C++11, we can rely on diagnostics being produced for any expression
18117 // which is not a constant expression. If no diagnostics were produced, then
18118 // this is a constant expression.
18119 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18120 if (Result)
18121 *Result = EvalResult.Val.getInt();
18122 return E;
18123 }
18124
18125 // If our only note is the usual "invalid subexpression" note, just point
18126 // the caret at its location rather than producing an essentially
18127 // redundant note.
18128 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18129 diag::note_invalid_subexpr_in_const_expr) {
18130 DiagLoc = Notes[0].first;
18131 Notes.clear();
18132 }
18133
18134 if (!Folded || CanFold == AllowFoldKind::No) {
18135 if (!Diagnoser.Suppress) {
18136 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18137 for (const PartialDiagnosticAt &Note : Notes)
18138 Diag(Note.first, Note.second);
18139 }
18140
18141 return ExprError();
18142 }
18143
18144 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18145 for (const PartialDiagnosticAt &Note : Notes)
18146 Diag(Note.first, Note.second);
18147
18148 if (Result)
18149 *Result = EvalResult.Val.getInt();
18150 return E;
18151}
18152
18153namespace {
18154 // Handle the case where we conclude a expression which we speculatively
18155 // considered to be unevaluated is actually evaluated.
18156 class TransformToPE : public TreeTransform<TransformToPE> {
18157 typedef TreeTransform<TransformToPE> BaseTransform;
18158
18159 public:
18160 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18161
18162 // Make sure we redo semantic analysis
18163 bool AlwaysRebuild() { return true; }
18164 bool ReplacingOriginal() { return true; }
18165
18166 // We need to special-case DeclRefExprs referring to FieldDecls which
18167 // are not part of a member pointer formation; normal TreeTransforming
18168 // doesn't catch this case because of the way we represent them in the AST.
18169 // FIXME: This is a bit ugly; is it really the best way to handle this
18170 // case?
18171 //
18172 // Error on DeclRefExprs referring to FieldDecls.
18173 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18174 if (isa<FieldDecl>(E->getDecl()) &&
18175 !SemaRef.isUnevaluatedContext())
18176 return SemaRef.Diag(E->getLocation(),
18177 diag::err_invalid_non_static_member_use)
18178 << E->getDecl() << E->getSourceRange();
18179
18180 return BaseTransform::TransformDeclRefExpr(E);
18181 }
18182
18183 // Exception: filter out member pointer formation
18184 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18185 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18186 return E;
18187
18188 return BaseTransform::TransformUnaryOperator(E);
18189 }
18190
18191 // The body of a lambda-expression is in a separate expression evaluation
18192 // context so never needs to be transformed.
18193 // FIXME: Ideally we wouldn't transform the closure type either, and would
18194 // just recreate the capture expressions and lambda expression.
18195 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18196 return SkipLambdaBody(E, Body);
18197 }
18198 };
18199}
18200
18202 assert(isUnevaluatedContext() &&
18203 "Should only transform unevaluated expressions");
18204 ExprEvalContexts.back().Context =
18205 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18207 return E;
18208 return TransformToPE(*this).TransformExpr(E);
18209}
18210
18212 assert(isUnevaluatedContext() &&
18213 "Should only transform unevaluated expressions");
18216 return TInfo;
18217 return TransformToPE(*this).TransformType(TInfo);
18218}
18219
18220void
18222 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18224 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
18225 LambdaContextDecl, ExprContext);
18226
18227 // Discarded statements and immediate contexts nested in other
18228 // discarded statements or immediate context are themselves
18229 // a discarded statement or an immediate context, respectively.
18230 ExprEvalContexts.back().InDiscardedStatement =
18232
18233 // C++23 [expr.const]/p15
18234 // An expression or conversion is in an immediate function context if [...]
18235 // it is a subexpression of a manifestly constant-evaluated expression or
18236 // conversion.
18237 const auto &Prev = parentEvaluationContext();
18238 ExprEvalContexts.back().InImmediateFunctionContext =
18239 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18240
18241 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18242 Prev.InImmediateEscalatingFunctionContext;
18243
18244 Cleanup.reset();
18245 if (!MaybeODRUseExprs.empty())
18246 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
18247}
18248
18249void
18253 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18254 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
18255}
18256
18258 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18259 // [expr.const]/p14.1
18260 // An expression or conversion is in an immediate function context if it is
18261 // potentially evaluated and either: its innermost enclosing non-block scope
18262 // is a function parameter scope of an immediate function.
18264 FD && FD->isConsteval()
18266 : NewContext);
18270
18271 Current.InDiscardedStatement = false;
18272
18273 if (FD) {
18274
18275 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18276 // context is nested in an immediate function context, so smaller contexts
18277 // that appear inside immediate functions (like variable initializers) are
18278 // considered to be inside an immediate function context even though by
18279 // themselves they are not immediate function contexts. But when a new
18280 // function is entered, we need to reset this tracking, since the entered
18281 // function might be not an immediate function.
18282
18284 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18285
18286 if (isLambdaMethod(FD))
18288 FD->isConsteval() ||
18289 (isLambdaMethod(FD) && (Parent.isConstantEvaluated() ||
18290 Parent.isImmediateFunctionContext()));
18291 else
18293 }
18294}
18295
18297 TypeSourceInfo *TSI) {
18298 return BuildCXXReflectExpr(CaretCaretLoc, TSI);
18299}
18300
18302 TypeSourceInfo *TSI) {
18303 return CXXReflectExpr::Create(Context, CaretCaretLoc, TSI);
18304}
18305
18306namespace {
18307
18308const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18309 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18310 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
18311 if (E->getOpcode() == UO_Deref)
18312 return CheckPossibleDeref(S, E->getSubExpr());
18313 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
18314 return CheckPossibleDeref(S, E->getBase());
18315 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
18316 return CheckPossibleDeref(S, E->getBase());
18317 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
18318 QualType Inner;
18319 QualType Ty = E->getType();
18320 if (const auto *Ptr = Ty->getAs<PointerType>())
18321 Inner = Ptr->getPointeeType();
18322 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
18323 Inner = Arr->getElementType();
18324 else
18325 return nullptr;
18326
18327 if (Inner->hasAttr(attr::NoDeref))
18328 return E;
18329 }
18330 return nullptr;
18331}
18332
18333} // namespace
18334
18336 for (const Expr *E : Rec.PossibleDerefs) {
18337 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
18338 if (DeclRef) {
18339 const ValueDecl *Decl = DeclRef->getDecl();
18340 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
18341 << Decl->getName() << E->getSourceRange();
18342 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
18343 } else {
18344 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
18345 << E->getSourceRange();
18346 }
18347 }
18348 Rec.PossibleDerefs.clear();
18349}
18350
18353 return;
18354
18355 // Note: ignoring parens here is not justified by the standard rules, but
18356 // ignoring parentheses seems like a more reasonable approach, and this only
18357 // drives a deprecation warning so doesn't affect conformance.
18358 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
18359 if (BO->getOpcode() == BO_Assign) {
18360 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18361 llvm::erase(LHSs, BO->getLHS());
18362 }
18363 }
18364}
18365
18367 assert(getLangOpts().CPlusPlus20 &&
18368 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18369 "Cannot mark an immediate escalating expression outside of an "
18370 "immediate escalating context");
18371 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
18372 Call && Call->getCallee()) {
18373 if (auto *DeclRef =
18374 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18375 DeclRef->setIsImmediateEscalating(true);
18376 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
18377 Ctr->setIsImmediateEscalating(true);
18378 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
18379 DeclRef->setIsImmediateEscalating(true);
18380 } else {
18381 assert(false && "expected an immediately escalating expression");
18382 }
18384 FI->FoundImmediateEscalatingExpression = true;
18385}
18386
18388 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18389 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18392 return E;
18393
18394 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18395 /// It's OK if this fails; we'll also remove this in
18396 /// HandleImmediateInvocations, but catching it here allows us to avoid
18397 /// walking the AST looking for it in simple cases.
18398 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18399 if (auto *DeclRef =
18400 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18401 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18402
18403 // C++23 [expr.const]/p16
18404 // An expression or conversion is immediate-escalating if it is not initially
18405 // in an immediate function context and it is [...] an immediate invocation
18406 // that is not a constant expression and is not a subexpression of an
18407 // immediate invocation.
18408 APValue Cached;
18409 auto CheckConstantExpressionAndKeepResult = [&]() {
18410 Expr::EvalResult Eval;
18411 bool Res = E.get()->EvaluateAsConstantExpr(
18412 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
18413 if (Res && !Eval.DiagEmitted) {
18414 Cached = std::move(Eval.Val);
18415 return true;
18416 }
18417 return false;
18418 };
18419
18420 if (!E.get()->isValueDependent() &&
18421 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18422 !CheckConstantExpressionAndKeepResult()) {
18424 return E;
18425 }
18426
18427 if (Cleanup.exprNeedsCleanups()) {
18428 // Since an immediate invocation is a full expression itself - it requires
18429 // an additional ExprWithCleanups node, but it can participate to a bigger
18430 // full expression which actually requires cleanups to be run after so
18431 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18432 // may discard cleanups for outer expression too early.
18433
18434 // Note that ExprWithCleanups created here must always have empty cleanup
18435 // objects:
18436 // - compound literals do not create cleanup objects in C++ and immediate
18437 // invocations are C++-only.
18438 // - blocks are not allowed inside constant expressions and compiler will
18439 // issue an error if they appear there.
18440 //
18441 // Hence, in correct code any cleanup objects created inside current
18442 // evaluation context must be outside the immediate invocation.
18444 Cleanup.cleanupsHaveSideEffects(), {});
18445 }
18446
18448 getASTContext(), E.get(),
18449 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18450 getASTContext()),
18451 /*IsImmediateInvocation*/ true);
18452 if (Cached.hasValue())
18453 Res->MoveIntoResult(Cached, getASTContext());
18454 /// Value-dependent constant expressions should not be immediately
18455 /// evaluated until they are instantiated.
18456 if (!Res->isValueDependent())
18457 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18458 return Res;
18459}
18460
18464 Expr::EvalResult Eval;
18465 Eval.Diag = &Notes;
18466 ConstantExpr *CE = Candidate.getPointer();
18467 bool Result = CE->EvaluateAsConstantExpr(
18468 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18469 if (!Result || !Notes.empty()) {
18471 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18472 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18473 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18474 FunctionDecl *FD = nullptr;
18475 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18476 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18477 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18478 FD = Call->getConstructor();
18479 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18480 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18481
18482 assert(FD && FD->isImmediateFunction() &&
18483 "could not find an immediate function in this expression");
18484 if (FD->isInvalidDecl())
18485 return;
18486 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18487 << FD << FD->isConsteval();
18488 if (auto Context =
18490 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18491 << Context->Decl;
18492 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18493 }
18494 if (!FD->isConsteval())
18496 for (auto &Note : Notes)
18497 SemaRef.Diag(Note.first, Note.second);
18498 return;
18499 }
18501}
18502
18506 struct ComplexRemove : TreeTransform<ComplexRemove> {
18508 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18511 CurrentII;
18512 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18515 4>::reverse_iterator Current)
18516 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18517 void RemoveImmediateInvocation(ConstantExpr* E) {
18518 auto It = std::find_if(CurrentII, IISet.rend(),
18520 return Elem.getPointer() == E;
18521 });
18522 // It is possible that some subexpression of the current immediate
18523 // invocation was handled from another expression evaluation context. Do
18524 // not handle the current immediate invocation if some of its
18525 // subexpressions failed before.
18526 if (It == IISet.rend()) {
18527 if (SemaRef.FailedImmediateInvocations.contains(E))
18528 CurrentII->setInt(1);
18529 } else {
18530 It->setInt(1); // Mark as deleted
18531 }
18532 }
18533 ExprResult TransformConstantExpr(ConstantExpr *E) {
18534 if (!E->isImmediateInvocation())
18535 return Base::TransformConstantExpr(E);
18536 RemoveImmediateInvocation(E);
18537 return Base::TransformExpr(E->getSubExpr());
18538 }
18539 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18540 /// we need to remove its DeclRefExpr from the DRSet.
18541 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18542 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18543 return Base::TransformCXXOperatorCallExpr(E);
18544 }
18545 /// Base::TransformUserDefinedLiteral doesn't preserve the
18546 /// UserDefinedLiteral node.
18547 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18548 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18549 /// here.
18550 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18551 if (!Init)
18552 return Init;
18553
18554 // We cannot use IgnoreImpCasts because we need to preserve
18555 // full expressions.
18556 while (true) {
18557 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
18558 Init = ICE->getSubExpr();
18559 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
18560 Init = ICE->getSubExpr();
18561 else
18562 break;
18563 }
18564 /// ConstantExprs are the first layer of implicit node to be removed so if
18565 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18566 if (auto *CE = dyn_cast<ConstantExpr>(Init);
18567 CE && CE->isImmediateInvocation())
18568 RemoveImmediateInvocation(CE);
18569 return Base::TransformInitializer(Init, NotCopyInit);
18570 }
18571 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18572 DRSet.erase(E);
18573 return E;
18574 }
18575 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18576 // Do not rebuild lambdas to avoid creating a new type.
18577 // Lambdas have already been processed inside their eval contexts.
18578 return E;
18579 }
18580
18581 // We do not have enough information to transform opaque expressions and
18582 // assume they do not contain immediate subexpressions.
18583 ExprResult TransformOpaqueValueExpr(OpaqueValueExpr *E) { return E; }
18584
18585 bool AlwaysRebuild() { return false; }
18586 bool ReplacingOriginal() { return true; }
18587 bool AllowSkippingCXXConstructExpr() {
18588 bool Res = AllowSkippingFirstCXXConstructExpr;
18589 AllowSkippingFirstCXXConstructExpr = true;
18590 return Res;
18591 }
18592 bool AllowSkippingFirstCXXConstructExpr = true;
18593 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18595
18596 /// CXXConstructExpr with a single argument are getting skipped by
18597 /// TreeTransform in some situtation because they could be implicit. This
18598 /// can only occur for the top-level CXXConstructExpr because it is used
18599 /// nowhere in the expression being transformed therefore will not be rebuilt.
18600 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18601 /// skipping the first CXXConstructExpr.
18602 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18603 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18604
18605 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18606 // The result may not be usable in case of previous compilation errors.
18607 // In this case evaluation of the expression may result in crash so just
18608 // don't do anything further with the result.
18609 if (Res.isUsable()) {
18611 It->getPointer()->setSubExpr(Res.get());
18612 }
18613}
18614
18615static void
18618 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18619 Rec.ReferenceToConsteval.size() == 0) ||
18621 return;
18622
18623 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18624 // [...]
18625 // - the initializer of a variable that is usable in constant expressions or
18626 // has constant initialization.
18627 if (SemaRef.getLangOpts().CPlusPlus23 &&
18628 Rec.ExprContext ==
18630 auto *VD = dyn_cast<VarDecl>(Rec.ManglingContextDecl);
18631 if (VD && (VD->isUsableInConstantExpressions(SemaRef.Context) ||
18632 VD->hasConstantInitialization())) {
18633 // An expression or conversion is in an 'immediate function context' if it
18634 // is potentially evaluated and either:
18635 // [...]
18636 // - it is a subexpression of a manifestly constant-evaluated expression
18637 // or conversion.
18638 return;
18639 }
18640 }
18641
18642 /// When we have more than 1 ImmediateInvocationCandidates or previously
18643 /// failed immediate invocations, we need to check for nested
18644 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18645 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18646 /// invocation.
18647 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18649
18650 /// Prevent sema calls during the tree transform from adding pointers that
18651 /// are already in the sets.
18652 llvm::SaveAndRestore DisableIITracking(
18654
18655 /// Prevent diagnostic during tree transfrom as they are duplicates
18657
18658 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18659 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18660 if (!It->getInt())
18662 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18663 Rec.ReferenceToConsteval.size()) {
18664 struct SimpleRemove : DynamicRecursiveASTVisitor {
18665 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18666 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18667 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18668 DRSet.erase(E);
18669 return DRSet.size();
18670 }
18671 } Visitor(Rec.ReferenceToConsteval);
18672 Visitor.TraverseStmt(
18673 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18674 }
18675 for (auto CE : Rec.ImmediateInvocationCandidates)
18676 if (!CE.getInt())
18678 for (auto *DR : Rec.ReferenceToConsteval) {
18679 // If the expression is immediate escalating, it is not an error;
18680 // The outer context itself becomes immediate and further errors,
18681 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18682 if (DR->isImmediateEscalating())
18683 continue;
18684 auto *FD = cast<FunctionDecl>(DR->getDecl());
18685 const NamedDecl *ND = FD;
18686 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18687 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18688 ND = MD->getParent();
18689
18690 // C++23 [expr.const]/p16
18691 // An expression or conversion is immediate-escalating if it is not
18692 // initially in an immediate function context and it is [...] a
18693 // potentially-evaluated id-expression that denotes an immediate function
18694 // that is not a subexpression of an immediate invocation.
18695 bool ImmediateEscalating = false;
18696 bool IsPotentiallyEvaluated =
18697 Rec.Context ==
18699 Rec.Context ==
18701 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18702 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18703
18705 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18706 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18707 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18708 if (!FD->getBuiltinID())
18709 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18710 if (auto Context =
18712 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18713 << Context->Decl;
18714 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18715 }
18716 if (FD->isImmediateEscalating() && !FD->isConsteval())
18718
18719 } else {
18721 }
18722 }
18723}
18724
18727 if (!Rec.Lambdas.empty()) {
18729 if (!getLangOpts().CPlusPlus20 &&
18730 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18731 Rec.isUnevaluated() ||
18733 unsigned D;
18734 if (Rec.isUnevaluated()) {
18735 // C++11 [expr.prim.lambda]p2:
18736 // A lambda-expression shall not appear in an unevaluated operand
18737 // (Clause 5).
18738 D = diag::err_lambda_unevaluated_operand;
18739 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18740 // C++1y [expr.const]p2:
18741 // A conditional-expression e is a core constant expression unless the
18742 // evaluation of e, following the rules of the abstract machine, would
18743 // evaluate [...] a lambda-expression.
18744 D = diag::err_lambda_in_constant_expression;
18745 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18746 // C++17 [expr.prim.lamda]p2:
18747 // A lambda-expression shall not appear [...] in a template-argument.
18748 D = diag::err_lambda_in_invalid_context;
18749 } else
18750 llvm_unreachable("Couldn't infer lambda error message.");
18751
18752 for (const auto *L : Rec.Lambdas)
18753 Diag(L->getBeginLoc(), D);
18754 }
18755 }
18756
18757 // Append the collected materialized temporaries into previous context before
18758 // exit if the previous also is a lifetime extending context.
18760 parentEvaluationContext().InLifetimeExtendingContext &&
18761 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18764 }
18765
18767 HandleImmediateInvocations(*this, Rec);
18768
18769 // Warn on any volatile-qualified simple-assignments that are not discarded-
18770 // value expressions nor unevaluated operands (those cases get removed from
18771 // this list by CheckUnusedVolatileAssignment).
18772 for (auto *BO : Rec.VolatileAssignmentLHSs)
18773 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18774 << BO->getType();
18775
18776 // When are coming out of an unevaluated context, clear out any
18777 // temporaries that we may have created as part of the evaluation of
18778 // the expression in that context: they aren't relevant because they
18779 // will never be constructed.
18780 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18782 ExprCleanupObjects.end());
18783 Cleanup = Rec.ParentCleanup;
18786 // Otherwise, merge the contexts together.
18787 } else {
18788 Cleanup.mergeFrom(Rec.ParentCleanup);
18789 MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
18790 }
18791
18793
18794 // Pop the current expression evaluation context off the stack.
18795 ExprEvalContexts.pop_back();
18796}
18797
18799 ExprCleanupObjects.erase(
18800 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18801 ExprCleanupObjects.end());
18802 Cleanup.reset();
18803 MaybeODRUseExprs.clear();
18804}
18805
18808 if (Result.isInvalid())
18809 return ExprError();
18810 E = Result.get();
18811 if (!E->getType()->isVariablyModifiedType())
18812 return E;
18814}
18815
18816/// Are we in a context that is potentially constant evaluated per C++20
18817/// [expr.const]p12?
18819 /// C++2a [expr.const]p12:
18820 // An expression or conversion is potentially constant evaluated if it is
18821 switch (SemaRef.ExprEvalContexts.back().Context) {
18824
18825 // -- a manifestly constant-evaluated expression,
18829 // -- a potentially-evaluated expression,
18831 // -- an immediate subexpression of a braced-init-list,
18832
18833 // -- [FIXME] an expression of the form & cast-expression that occurs
18834 // within a templated entity
18835 // -- a subexpression of one of the above that is not a subexpression of
18836 // a nested unevaluated operand.
18837 return true;
18838
18841 // Expressions in this context are never evaluated.
18842 return false;
18843 }
18844 llvm_unreachable("Invalid context");
18845}
18846
18847/// Return true if this function has a calling convention that requires mangling
18848/// in the size of the parameter pack.
18850 // These manglings are only applicable for targets whcih use Microsoft
18851 // mangling scheme for C.
18853 return false;
18854
18855 // If this is C++ and this isn't an extern "C" function, parameters do not
18856 // need to be complete. In this case, C++ mangling will apply, which doesn't
18857 // use the size of the parameters.
18858 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18859 return false;
18860
18861 // Stdcall, fastcall, and vectorcall need this special treatment.
18862 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18863 switch (CC) {
18864 case CC_X86StdCall:
18865 case CC_X86FastCall:
18866 case CC_X86VectorCall:
18867 return true;
18868 default:
18869 break;
18870 }
18871 return false;
18872}
18873
18874/// Require that all of the parameter types of function be complete. Normally,
18875/// parameter types are only required to be complete when a function is called
18876/// or defined, but to mangle functions with certain calling conventions, the
18877/// mangler needs to know the size of the parameter list. In this situation,
18878/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18879/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18880/// result in a linker error. Clang doesn't implement this behavior, and instead
18881/// attempts to error at compile time.
18883 SourceLocation Loc) {
18884 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18885 FunctionDecl *FD;
18886 ParmVarDecl *Param;
18887
18888 public:
18889 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18890 : FD(FD), Param(Param) {}
18891
18892 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18893 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18894 StringRef CCName;
18895 switch (CC) {
18896 case CC_X86StdCall:
18897 CCName = "stdcall";
18898 break;
18899 case CC_X86FastCall:
18900 CCName = "fastcall";
18901 break;
18902 case CC_X86VectorCall:
18903 CCName = "vectorcall";
18904 break;
18905 default:
18906 llvm_unreachable("CC does not need mangling");
18907 }
18908
18909 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18910 << Param->getDeclName() << FD->getDeclName() << CCName;
18911 }
18912 };
18913
18914 for (ParmVarDecl *Param : FD->parameters()) {
18915 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18916 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18917 }
18918}
18919
18920namespace {
18921enum class OdrUseContext {
18922 /// Declarations in this context are not odr-used.
18923 None,
18924 /// Declarations in this context are formally odr-used, but this is a
18925 /// dependent context.
18926 Dependent,
18927 /// Declarations in this context are odr-used but not actually used (yet).
18928 FormallyOdrUsed,
18929 /// Declarations in this context are used.
18930 Used
18931};
18932}
18933
18934/// Are we within a context in which references to resolved functions or to
18935/// variables result in odr-use?
18936static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18939
18940 if (Context.isUnevaluated())
18941 return OdrUseContext::None;
18942
18944 return OdrUseContext::Dependent;
18945
18946 if (Context.isDiscardedStatementContext())
18947 return OdrUseContext::FormallyOdrUsed;
18948
18949 else if (Context.Context ==
18951 return OdrUseContext::FormallyOdrUsed;
18952
18953 return OdrUseContext::Used;
18954}
18955
18957 if (!Func->isConstexpr())
18958 return false;
18959
18960 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18961 return true;
18962
18963 // Lambda conversion operators are never user provided.
18964 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))
18965 return isLambdaConversionOperator(Conv);
18966
18967 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18968 return CCD && CCD->getInheritedConstructor();
18969}
18970
18972 bool MightBeOdrUse) {
18973 assert(Func && "No function?");
18974
18975 Func->setReferenced();
18976
18977 // Recursive functions aren't really used until they're used from some other
18978 // context.
18979 bool IsRecursiveCall = CurContext == Func;
18980
18981 // C++11 [basic.def.odr]p3:
18982 // A function whose name appears as a potentially-evaluated expression is
18983 // odr-used if it is the unique lookup result or the selected member of a
18984 // set of overloaded functions [...].
18985 //
18986 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18987 // can just check that here.
18988 OdrUseContext OdrUse =
18989 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18990 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18991 OdrUse = OdrUseContext::FormallyOdrUsed;
18992
18993 // Trivial default constructors and destructors are never actually used.
18994 // FIXME: What about other special members?
18995 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18996 OdrUse == OdrUseContext::Used) {
18997 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18998 if (Constructor->isDefaultConstructor())
18999 OdrUse = OdrUseContext::FormallyOdrUsed;
19001 OdrUse = OdrUseContext::FormallyOdrUsed;
19002 }
19003
19004 // C++20 [expr.const]p12:
19005 // A function [...] is needed for constant evaluation if it is [...] a
19006 // constexpr function that is named by an expression that is potentially
19007 // constant evaluated
19008 bool NeededForConstantEvaluation =
19011
19012 // Determine whether we require a function definition to exist, per
19013 // C++11 [temp.inst]p3:
19014 // Unless a function template specialization has been explicitly
19015 // instantiated or explicitly specialized, the function template
19016 // specialization is implicitly instantiated when the specialization is
19017 // referenced in a context that requires a function definition to exist.
19018 // C++20 [temp.inst]p7:
19019 // The existence of a definition of a [...] function is considered to
19020 // affect the semantics of the program if the [...] function is needed for
19021 // constant evaluation by an expression
19022 // C++20 [basic.def.odr]p10:
19023 // Every program shall contain exactly one definition of every non-inline
19024 // function or variable that is odr-used in that program outside of a
19025 // discarded statement
19026 // C++20 [special]p1:
19027 // The implementation will implicitly define [defaulted special members]
19028 // if they are odr-used or needed for constant evaluation.
19029 //
19030 // Note that we skip the implicit instantiation of templates that are only
19031 // used in unused default arguments or by recursive calls to themselves.
19032 // This is formally non-conforming, but seems reasonable in practice.
19033 bool NeedDefinition =
19034 !IsRecursiveCall &&
19035 (OdrUse == OdrUseContext::Used ||
19036 (NeededForConstantEvaluation && !Func->isPureVirtual()));
19037
19038 // C++14 [temp.expl.spec]p6:
19039 // If a template [...] is explicitly specialized then that specialization
19040 // shall be declared before the first use of that specialization that would
19041 // cause an implicit instantiation to take place, in every translation unit
19042 // in which such a use occurs
19043 if (NeedDefinition &&
19044 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
19045 Func->getMemberSpecializationInfo()))
19047
19048 if (getLangOpts().CUDA)
19049 CUDA().CheckCall(Loc, Func);
19050
19051 // If we need a definition, try to create one.
19052 if (NeedDefinition && !Func->getBody()) {
19055 dyn_cast<CXXConstructorDecl>(Func)) {
19057 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
19058 if (Constructor->isDefaultConstructor()) {
19059 if (Constructor->isTrivial() &&
19060 !Constructor->hasAttr<DLLExportAttr>())
19061 return;
19063 } else if (Constructor->isCopyConstructor()) {
19065 } else if (Constructor->isMoveConstructor()) {
19067 }
19068 } else if (Constructor->getInheritedConstructor()) {
19070 }
19071 } else if (CXXDestructorDecl *Destructor =
19072 dyn_cast<CXXDestructorDecl>(Func)) {
19074 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
19075 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
19076 return;
19078 }
19079 if (Destructor->isVirtual() && getLangOpts().AppleKext)
19080 MarkVTableUsed(Loc, Destructor->getParent());
19081 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
19082 if (MethodDecl->isOverloadedOperator() &&
19083 MethodDecl->getOverloadedOperator() == OO_Equal) {
19084 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
19085 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
19086 if (MethodDecl->isCopyAssignmentOperator())
19087 DefineImplicitCopyAssignment(Loc, MethodDecl);
19088 else if (MethodDecl->isMoveAssignmentOperator())
19089 DefineImplicitMoveAssignment(Loc, MethodDecl);
19090 }
19091 } else if (isa<CXXConversionDecl>(MethodDecl) &&
19092 MethodDecl->getParent()->isLambda()) {
19093 CXXConversionDecl *Conversion =
19094 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
19095 if (Conversion->isLambdaToBlockPointerConversion())
19097 else
19099 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19100 MarkVTableUsed(Loc, MethodDecl->getParent());
19101 }
19102
19103 if (Func->isDefaulted() && !Func->isDeleted()) {
19107 }
19108
19109 // Implicit instantiation of function templates and member functions of
19110 // class templates.
19111 if (Func->isImplicitlyInstantiable()) {
19113 Func->getTemplateSpecializationKindForInstantiation();
19114 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19115 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19116 if (FirstInstantiation) {
19117 PointOfInstantiation = Loc;
19118 if (auto *MSI = Func->getMemberSpecializationInfo())
19119 MSI->setPointOfInstantiation(Loc);
19120 // FIXME: Notify listener.
19121 else
19122 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19123 } else if (TSK != TSK_ImplicitInstantiation) {
19124 // Use the point of use as the point of instantiation, instead of the
19125 // point of explicit instantiation (which we track as the actual point
19126 // of instantiation). This gives better backtraces in diagnostics.
19127 PointOfInstantiation = Loc;
19128 }
19129
19130 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19131 Func->isConstexpr()) {
19132 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
19133 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
19134 CodeSynthesisContexts.size())
19136 std::make_pair(Func, PointOfInstantiation));
19137 else if (Func->isConstexpr())
19138 // Do not defer instantiations of constexpr functions, to avoid the
19139 // expression evaluator needing to call back into Sema if it sees a
19140 // call to such a function.
19141 InstantiateFunctionDefinition(PointOfInstantiation, Func);
19142 else {
19143 Func->setInstantiationIsPending(true);
19144 PendingInstantiations.push_back(
19145 std::make_pair(Func, PointOfInstantiation));
19146 if (llvm::isTimeTraceVerbose()) {
19147 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
19148 std::string Name;
19149 llvm::raw_string_ostream OS(Name);
19150 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
19151 /*Qualified=*/true);
19152 return Name;
19153 });
19154 }
19155 // Notify the consumer that a function was implicitly instantiated.
19156 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
19157 }
19158 }
19159 } else {
19160 // Walk redefinitions, as some of them may be instantiable.
19161 for (auto *i : Func->redecls()) {
19162 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
19163 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
19164 }
19165 }
19166 });
19167 }
19168
19169 // If a constructor was defined in the context of a default parameter
19170 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19171 // context), its initializers may not be referenced yet.
19172 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
19174 *this,
19175 Constructor->isImmediateFunction()
19178 Constructor);
19179 for (CXXCtorInitializer *Init : Constructor->inits()) {
19180 if (Init->isInClassMemberInitializer())
19181 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
19182 MarkDeclarationsReferencedInExpr(Init->getInit());
19183 });
19184 }
19185 }
19186
19187 // C++14 [except.spec]p17:
19188 // An exception-specification is considered to be needed when:
19189 // - the function is odr-used or, if it appears in an unevaluated operand,
19190 // would be odr-used if the expression were potentially-evaluated;
19191 //
19192 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19193 // function is a pure virtual function we're calling, and in that case the
19194 // function was selected by overload resolution and we need to resolve its
19195 // exception specification for a different reason.
19196 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19198 ResolveExceptionSpec(Loc, FPT);
19199
19200 // A callee could be called by a host function then by a device function.
19201 // If we only try recording once, we will miss recording the use on device
19202 // side. Therefore keep trying until it is recorded.
19203 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19204 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
19206
19207 // If this is the first "real" use, act on that.
19208 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19209 // Keep track of used but undefined functions.
19210 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19211 if (mightHaveNonExternalLinkage(Func))
19212 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19213 else if (Func->getMostRecentDecl()->isInlined() &&
19214 !LangOpts.GNUInline &&
19215 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19216 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19218 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19219 }
19220
19221 // Some x86 Windows calling conventions mangle the size of the parameter
19222 // pack into the name. Computing the size of the parameters requires the
19223 // parameter types to be complete. Check that now.
19226
19227 // In the MS C++ ABI, the compiler emits destructor variants where they are
19228 // used. If the destructor is used here but defined elsewhere, mark the
19229 // virtual base destructors referenced. If those virtual base destructors
19230 // are inline, this will ensure they are defined when emitting the complete
19231 // destructor variant. This checking may be redundant if the destructor is
19232 // provided later in this TU.
19233 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19234 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
19235 CXXRecordDecl *Parent = Dtor->getParent();
19236 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19238 }
19239 }
19240
19241 Func->markUsed(Context);
19242 }
19243}
19244
19245/// Directly mark a variable odr-used. Given a choice, prefer to use
19246/// MarkVariableReferenced since it does additional checks and then
19247/// calls MarkVarDeclODRUsed.
19248/// If the variable must be captured:
19249/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19250/// - else capture it in the DeclContext that maps to the
19251/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19252static void
19254 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19255 // Keep track of used but undefined variables.
19256 // FIXME: We shouldn't suppress this warning for static data members.
19257 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19258 assert(Var && "expected a capturable variable");
19259
19261 (!Var->isExternallyVisible() || Var->isInline() ||
19263 !(Var->isStaticDataMember() && Var->hasInit())) {
19265 if (old.isInvalid())
19266 old = Loc;
19267 }
19268 QualType CaptureType, DeclRefType;
19269 if (SemaRef.LangOpts.OpenMP)
19272 /*EllipsisLoc*/ SourceLocation(),
19273 /*BuildAndDiagnose*/ true, CaptureType,
19274 DeclRefType, FunctionScopeIndexToStopAt);
19275
19276 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19277 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
19278 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
19279 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
19280 if (VarTarget == SemaCUDA::CVT_Host &&
19281 (UserTarget == CUDAFunctionTarget::Device ||
19282 UserTarget == CUDAFunctionTarget::HostDevice ||
19283 UserTarget == CUDAFunctionTarget::Global)) {
19284 // Diagnose ODR-use of host global variables in device functions.
19285 // Reference of device global variables in host functions is allowed
19286 // through shadow variables therefore it is not diagnosed.
19287 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19288 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
19289 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19291 Var->getType().isConstQualified()
19292 ? diag::note_cuda_const_var_unpromoted
19293 : diag::note_cuda_host_var);
19294 }
19295 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19296 // Also capture __device__ const variables, which are classified
19297 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19298 // an explicit CUDADeviceAttr to distinguish them from plain
19299 // const variables (no __device__), which also get CVT_Both but
19300 // only have an implicit CUDADeviceAttr.
19301 (VarTarget == SemaCUDA::CVT_Both &&
19302 Var->hasAttr<CUDADeviceAttr>() &&
19303 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19304 !Var->hasAttr<CUDASharedAttr>() &&
19305 (UserTarget == CUDAFunctionTarget::Host ||
19306 UserTarget == CUDAFunctionTarget::HostDevice)) {
19307 // Record a CUDA/HIP device side variable if it is ODR-used
19308 // by host code. This is done conservatively, when the variable is
19309 // referenced in any of the following contexts:
19310 // - a non-function context
19311 // - a host function
19312 // - a host device function
19313 // This makes the ODR-use of the device side variable by host code to
19314 // be visible in the device compilation for the compiler to be able to
19315 // emit template variables instantiated by host code only and to
19316 // externalize the static device side variable ODR-used by host code.
19317 if (!Var->hasExternalStorage())
19319 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19320 (!FD || (!FD->getDescribedFunctionTemplate() &&
19324 }
19325 }
19326
19327 V->markUsed(SemaRef.Context);
19328}
19329
19331 SourceLocation Loc,
19332 unsigned CapturingScopeIndex) {
19333 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
19334}
19335
19337 SourceLocation loc,
19338 ValueDecl *var) {
19339 DeclContext *VarDC = var->getDeclContext();
19340
19341 // If the parameter still belongs to the translation unit, then
19342 // we're actually just using one parameter in the declaration of
19343 // the next.
19344 if (isa<ParmVarDecl>(var) &&
19346 return;
19347
19348 // For C code, don't diagnose about capture if we're not actually in code
19349 // right now; it's impossible to write a non-constant expression outside of
19350 // function context, so we'll get other (more useful) diagnostics later.
19351 //
19352 // For C++, things get a bit more nasty... it would be nice to suppress this
19353 // diagnostic for certain cases like using a local variable in an array bound
19354 // for a member of a local class, but the correct predicate is not obvious.
19355 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19356 return;
19357
19358 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
19359 unsigned ContextKind = 3; // unknown
19360 if (isa<CXXMethodDecl>(VarDC) &&
19361 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
19362 ContextKind = 2;
19363 } else if (isa<FunctionDecl>(VarDC)) {
19364 ContextKind = 0;
19365 } else if (isa<BlockDecl>(VarDC)) {
19366 ContextKind = 1;
19367 }
19368
19369 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
19370 << var << ValueKind << ContextKind << VarDC;
19371 S.Diag(var->getLocation(), diag::note_entity_declared_at)
19372 << var;
19373
19374 // FIXME: Add additional diagnostic info about class etc. which prevents
19375 // capture.
19376}
19377
19379 ValueDecl *Var,
19380 bool &SubCapturesAreNested,
19381 QualType &CaptureType,
19382 QualType &DeclRefType) {
19383 // Check whether we've already captured it.
19384 if (CSI->CaptureMap.count(Var)) {
19385 // If we found a capture, any subcaptures are nested.
19386 SubCapturesAreNested = true;
19387
19388 // Retrieve the capture type for this variable.
19389 CaptureType = CSI->getCapture(Var).getCaptureType();
19390
19391 // Compute the type of an expression that refers to this variable.
19392 DeclRefType = CaptureType.getNonReferenceType();
19393
19394 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19395 // are mutable in the sense that user can change their value - they are
19396 // private instances of the captured declarations.
19397 const Capture &Cap = CSI->getCapture(Var);
19398 // C++ [expr.prim.lambda]p10:
19399 // The type of such a data member is [...] an lvalue reference to the
19400 // referenced function type if the entity is a reference to a function.
19401 // [...]
19402 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19403 !(isa<LambdaScopeInfo>(CSI) &&
19404 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
19406 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19407 DeclRefType.addConst();
19408 return true;
19409 }
19410 return false;
19411}
19412
19413// Only block literals, captured statements, and lambda expressions can
19414// capture; other scopes don't work.
19416 ValueDecl *Var,
19417 SourceLocation Loc,
19418 const bool Diagnose,
19419 Sema &S) {
19422
19423 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19424 if (Underlying) {
19425 if (Underlying->hasLocalStorage() && Diagnose)
19427 }
19428 return nullptr;
19429}
19430
19431// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19432// certain types of variables (unnamed, variably modified types etc.)
19433// so check for eligibility.
19435 SourceLocation Loc, const bool Diagnose,
19436 Sema &S) {
19437
19438 assert((isa<VarDecl, BindingDecl>(Var)) &&
19439 "Only variables and structured bindings can be captured");
19440
19441 bool IsBlock = isa<BlockScopeInfo>(CSI);
19442 bool IsLambda = isa<LambdaScopeInfo>(CSI);
19443
19444 // Lambdas are not allowed to capture unnamed variables
19445 // (e.g. anonymous unions).
19446 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19447 // assuming that's the intent.
19448 if (IsLambda && !Var->getDeclName()) {
19449 if (Diagnose) {
19450 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19451 S.Diag(Var->getLocation(), diag::note_declared_at);
19452 }
19453 return false;
19454 }
19455
19456 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19457 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19458 if (Diagnose) {
19459 S.Diag(Loc, diag::err_ref_vm_type);
19460 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19461 }
19462 return false;
19463 }
19464 // Prohibit structs with flexible array members too.
19465 // We cannot capture what is in the tail end of the struct.
19466 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19467 VTD && VTD->hasFlexibleArrayMember()) {
19468 if (Diagnose) {
19469 if (IsBlock)
19470 S.Diag(Loc, diag::err_ref_flexarray_type);
19471 else
19472 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19473 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19474 }
19475 return false;
19476 }
19477 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19478 // Lambdas and captured statements are not allowed to capture __block
19479 // variables; they don't support the expected semantics.
19480 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19481 if (Diagnose) {
19482 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19483 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19484 }
19485 return false;
19486 }
19487 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19488 if (S.getLangOpts().OpenCL && IsBlock &&
19489 Var->getType()->isBlockPointerType()) {
19490 if (Diagnose)
19491 S.Diag(Loc, diag::err_opencl_block_ref_block);
19492 return false;
19493 }
19494
19495 if (isa<BindingDecl>(Var)) {
19496 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19497 if (Diagnose)
19499 return false;
19500 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19501 S.Diag(Loc, S.LangOpts.CPlusPlus20
19502 ? diag::warn_cxx17_compat_capture_binding
19503 : diag::ext_capture_binding)
19504 << Var;
19505 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19506 }
19507 }
19508
19509 return true;
19510}
19511
19512// Returns true if the capture by block was successful.
19514 SourceLocation Loc, const bool BuildAndDiagnose,
19515 QualType &CaptureType, QualType &DeclRefType,
19516 const bool Nested, Sema &S, bool Invalid) {
19517 bool ByRef = false;
19518
19519 // Blocks are not allowed to capture arrays, excepting OpenCL.
19520 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19521 // (decayed to pointers).
19522 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19523 if (BuildAndDiagnose) {
19524 S.Diag(Loc, diag::err_ref_array_type);
19525 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19526 Invalid = true;
19527 } else {
19528 return false;
19529 }
19530 }
19531
19532 // Forbid the block-capture of autoreleasing variables.
19533 if (!Invalid &&
19535 if (BuildAndDiagnose) {
19536 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19537 << /*block*/ 0;
19538 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19539 Invalid = true;
19540 } else {
19541 return false;
19542 }
19543 }
19544
19545 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19546 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19547 QualType PointeeTy = PT->getPointeeType();
19548
19549 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19551 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19552 if (BuildAndDiagnose) {
19553 SourceLocation VarLoc = Var->getLocation();
19554 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19555 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19556 }
19557 }
19558 }
19559
19560 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19561 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19562 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
19563 // Block capture by reference does not change the capture or
19564 // declaration reference types.
19565 ByRef = true;
19566 } else {
19567 // Block capture by copy introduces 'const'.
19568 CaptureType = CaptureType.getNonReferenceType().withConst();
19569 DeclRefType = CaptureType;
19570 }
19571
19572 // Actually capture the variable.
19573 if (BuildAndDiagnose)
19574 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19575 CaptureType, Invalid);
19576
19577 return !Invalid;
19578}
19579
19580/// Capture the given variable in the captured region.
19583 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19584 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19585 Sema &S, bool Invalid) {
19586 // By default, capture variables by reference.
19587 bool ByRef = true;
19588 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19589 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19590 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19591 // Using an LValue reference type is consistent with Lambdas (see below).
19592 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
19593 bool HasConst = DeclRefType.isConstQualified();
19594 DeclRefType = DeclRefType.getUnqualifiedType();
19595 // Don't lose diagnostics about assignments to const.
19596 if (HasConst)
19597 DeclRefType.addConst();
19598 }
19599 // Do not capture firstprivates in tasks.
19600 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
19601 RSI->OpenMPCaptureLevel) != OMPC_unknown)
19602 return true;
19603 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19604 RSI->OpenMPCaptureLevel);
19605 }
19606
19607 if (ByRef)
19608 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19609 else
19610 CaptureType = DeclRefType;
19611
19612 // Actually capture the variable.
19613 if (BuildAndDiagnose)
19614 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19615 Loc, SourceLocation(), CaptureType, Invalid);
19616
19617 return !Invalid;
19618}
19619
19620/// Capture the given variable in the lambda.
19622 SourceLocation Loc, const bool BuildAndDiagnose,
19623 QualType &CaptureType, QualType &DeclRefType,
19624 const bool RefersToCapturedVariable,
19625 const TryCaptureKind Kind,
19626 SourceLocation EllipsisLoc, const bool IsTopScope,
19627 Sema &S, bool Invalid) {
19628 // Determine whether we are capturing by reference or by value.
19629 bool ByRef = false;
19630 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19631 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19632 } else {
19633 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19634 }
19635
19636 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19638 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19639 Invalid = true;
19640 }
19641
19642 // Compute the type of the field that will capture this variable.
19643 if (ByRef) {
19644 // C++11 [expr.prim.lambda]p15:
19645 // An entity is captured by reference if it is implicitly or
19646 // explicitly captured but not captured by copy. It is
19647 // unspecified whether additional unnamed non-static data
19648 // members are declared in the closure type for entities
19649 // captured by reference.
19650 //
19651 // FIXME: It is not clear whether we want to build an lvalue reference
19652 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19653 // to do the former, while EDG does the latter. Core issue 1249 will
19654 // clarify, but for now we follow GCC because it's a more permissive and
19655 // easily defensible position.
19656 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19657 } else {
19658 // C++11 [expr.prim.lambda]p14:
19659 // For each entity captured by copy, an unnamed non-static
19660 // data member is declared in the closure type. The
19661 // declaration order of these members is unspecified. The type
19662 // of such a data member is the type of the corresponding
19663 // captured entity if the entity is not a reference to an
19664 // object, or the referenced type otherwise. [Note: If the
19665 // captured entity is a reference to a function, the
19666 // corresponding data member is also a reference to a
19667 // function. - end note ]
19668 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19669 if (!RefType->getPointeeType()->isFunctionType())
19670 CaptureType = RefType->getPointeeType();
19671 }
19672
19673 // Forbid the lambda copy-capture of autoreleasing variables.
19674 if (!Invalid &&
19676 if (BuildAndDiagnose) {
19677 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19678 S.Diag(Var->getLocation(), diag::note_previous_decl)
19679 << Var->getDeclName();
19680 Invalid = true;
19681 } else {
19682 return false;
19683 }
19684 }
19685
19686 // Make sure that by-copy captures are of a complete and non-abstract type.
19687 if (!Invalid && BuildAndDiagnose) {
19688 if (!CaptureType->isDependentType() &&
19690 Loc, CaptureType,
19691 diag::err_capture_of_incomplete_or_sizeless_type,
19692 Var->getDeclName()))
19693 Invalid = true;
19694 else if (S.RequireNonAbstractType(Loc, CaptureType,
19695 diag::err_capture_of_abstract_type))
19696 Invalid = true;
19697 }
19698 }
19699
19700 // Compute the type of a reference to this captured variable.
19701 if (ByRef)
19702 DeclRefType = CaptureType.getNonReferenceType();
19703 else {
19704 // C++ [expr.prim.lambda]p5:
19705 // The closure type for a lambda-expression has a public inline
19706 // function call operator [...]. This function call operator is
19707 // declared const (9.3.1) if and only if the lambda-expression's
19708 // parameter-declaration-clause is not followed by mutable.
19709 DeclRefType = CaptureType.getNonReferenceType();
19710 bool Const = LSI->lambdaCaptureShouldBeConst();
19711 // C++ [expr.prim.lambda]p10:
19712 // The type of such a data member is [...] an lvalue reference to the
19713 // referenced function type if the entity is a reference to a function.
19714 // [...]
19715 if (Const && !CaptureType->isReferenceType() &&
19716 !DeclRefType->isFunctionType())
19717 DeclRefType.addConst();
19718 }
19719
19720 // Add the capture.
19721 if (BuildAndDiagnose)
19722 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19723 Loc, EllipsisLoc, CaptureType, Invalid);
19724
19725 return !Invalid;
19726}
19727
19729 const ASTContext &Context) {
19730 // Offer a Copy fix even if the type is dependent.
19731 if (Var->getType()->isDependentType())
19732 return true;
19734 if (T.isTriviallyCopyableType(Context))
19735 return true;
19736 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19737
19738 if (!(RD = RD->getDefinition()))
19739 return false;
19740 if (RD->hasSimpleCopyConstructor())
19741 return true;
19742 if (RD->hasUserDeclaredCopyConstructor())
19743 for (CXXConstructorDecl *Ctor : RD->ctors())
19744 if (Ctor->isCopyConstructor())
19745 return !Ctor->isDeleted();
19746 }
19747 return false;
19748}
19749
19750/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19751/// default capture. Fixes may be omitted if they aren't allowed by the
19752/// standard, for example we can't emit a default copy capture fix-it if we
19753/// already explicitly copy capture capture another variable.
19755 ValueDecl *Var) {
19757 // Don't offer Capture by copy of default capture by copy fixes if Var is
19758 // known not to be copy constructible.
19759 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19760
19761 SmallString<32> FixBuffer;
19762 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19763 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19764 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19765 if (ShouldOfferCopyFix) {
19766 // Offer fixes to insert an explicit capture for the variable.
19767 // [] -> [VarName]
19768 // [OtherCapture] -> [OtherCapture, VarName]
19769 FixBuffer.assign({Separator, Var->getName()});
19770 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19771 << Var << /*value*/ 0
19772 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19773 }
19774 // As above but capture by reference.
19775 FixBuffer.assign({Separator, "&", Var->getName()});
19776 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19777 << Var << /*reference*/ 1
19778 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19779 }
19780
19781 // Only try to offer default capture if there are no captures excluding this
19782 // and init captures.
19783 // [this]: OK.
19784 // [X = Y]: OK.
19785 // [&A, &B]: Don't offer.
19786 // [A, B]: Don't offer.
19787 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19788 return !C.isThisCapture() && !C.isInitCapture();
19789 }))
19790 return;
19791
19792 // The default capture specifiers, '=' or '&', must appear first in the
19793 // capture body.
19794 SourceLocation DefaultInsertLoc =
19796
19797 if (ShouldOfferCopyFix) {
19798 bool CanDefaultCopyCapture = true;
19799 // [=, *this] OK since c++17
19800 // [=, this] OK since c++20
19801 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19802 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19804 : false;
19805 // We can't use default capture by copy if any captures already specified
19806 // capture by copy.
19807 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19808 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19809 })) {
19810 FixBuffer.assign({"=", Separator});
19811 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19812 << /*value*/ 0
19813 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19814 }
19815 }
19816
19817 // We can't use default capture by reference if any captures already specified
19818 // capture by reference.
19819 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19820 return !C.isInitCapture() && C.isReferenceCapture() &&
19821 !C.isThisCapture();
19822 })) {
19823 FixBuffer.assign({"&", Separator});
19824 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19825 << /*reference*/ 1
19826 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19827 }
19828}
19829
19831 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19832 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19833 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19834 // An init-capture is notionally from the context surrounding its
19835 // declaration, but its parent DC is the lambda class.
19836 DeclContext *VarDC =
19838 DeclContext *DC = CurContext;
19839
19840 // Skip past RequiresExprBodys because they don't constitute function scopes.
19841 while (DC->isRequiresExprBody() || DC->isExpansionStmt())
19842 DC = DC->getParent();
19843
19844 // tryCaptureVariable is called every time a DeclRef is formed,
19845 // it can therefore have non-negigible impact on performances.
19846 // For local variables and when there is no capturing scope,
19847 // we can bailout early.
19848 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19849 return true;
19850
19851 // Exception: Function parameters are not tied to the function's DeclContext
19852 // until we enter the function definition. Capturing them anyway would result
19853 // in an out-of-bounds error while traversing DC and its parents.
19854 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
19855 return true;
19856
19857 const auto *VD = dyn_cast<VarDecl>(Var);
19858 if (VD) {
19859 if (VD->isInitCapture())
19860 VarDC = VarDC->getParent();
19861 } else {
19863 }
19864 assert(VD && "Cannot capture a null variable");
19865
19866 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19867 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19868 // We need to sync up the Declaration Context with the
19869 // FunctionScopeIndexToStopAt
19870 if (FunctionScopeIndexToStopAt) {
19871 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19872 unsigned FSIndex = FunctionScopes.size() - 1;
19873 // When we're parsing the lambda parameter list, the current DeclContext is
19874 // NOT the lambda but its parent. So move away the current LSI before
19875 // aligning DC and FunctionScopeIndexToStopAt.
19876 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
19877 FSIndex && LSI && !LSI->AfterParameterList)
19878 --FSIndex;
19879 assert(MaxFunctionScopesIndex <= FSIndex &&
19880 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19881 "FunctionScopes.");
19882 while (FSIndex != MaxFunctionScopesIndex) {
19884 --FSIndex;
19885 }
19886 }
19887
19888 // Capture global variables if it is required to use private copy of this
19889 // variable.
19890 bool IsGlobal = !VD->hasLocalStorage();
19891 if (IsGlobal && !(LangOpts.OpenMP &&
19892 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19893 MaxFunctionScopesIndex)))
19894 return true;
19895
19896 if (isa<VarDecl>(Var))
19897 Var = cast<VarDecl>(Var->getCanonicalDecl());
19898
19899 // Walk up the stack to determine whether we can capture the variable,
19900 // performing the "simple" checks that don't depend on type. We stop when
19901 // we've either hit the declared scope of the variable or find an existing
19902 // capture of that variable. We start from the innermost capturing-entity
19903 // (the DC) and ensure that all intervening capturing-entities
19904 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19905 // declcontext can either capture the variable or have already captured
19906 // the variable.
19907 CaptureType = Var->getType();
19908 DeclRefType = CaptureType.getNonReferenceType();
19909 bool Nested = false;
19910 bool Explicit = (Kind != TryCaptureKind::Implicit);
19911 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19912 do {
19913
19914 LambdaScopeInfo *LSI = nullptr;
19915 if (!FunctionScopes.empty())
19916 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19917 FunctionScopes[FunctionScopesIndex]);
19918
19919 bool IsInScopeDeclarationContext =
19920 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19921
19922 if (LSI && !LSI->AfterParameterList) {
19923 // This allows capturing parameters from a default value which does not
19924 // seems correct
19925 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19926 return true;
19927 }
19928 // If the variable is declared in the current context, there is no need to
19929 // capture it.
19930 if (IsInScopeDeclarationContext &&
19931 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19932 return true;
19933
19934 // Only block literals, captured statements, and lambda expressions can
19935 // capture; other scopes don't work.
19936 DeclContext *ParentDC =
19937 !IsInScopeDeclarationContext
19938 ? DC->getParent()
19939 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19940 BuildAndDiagnose, *this);
19941 // We need to check for the parent *first* because, if we *have*
19942 // private-captured a global variable, we need to recursively capture it in
19943 // intermediate blocks, lambdas, etc.
19944 if (!ParentDC) {
19945 if (IsGlobal) {
19946 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19947 break;
19948 }
19949 return true;
19950 }
19951
19952 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19954
19955 // Check whether we've already captured it.
19956 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19957 DeclRefType)) {
19958 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19959 break;
19960 }
19961
19962 // When evaluating some attributes (like enable_if) we might refer to a
19963 // function parameter appertaining to the same declaration as that
19964 // attribute.
19965 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19966 Parm && Parm->getDeclContext() == DC)
19967 return true;
19968
19969 // If we are instantiating a generic lambda call operator body,
19970 // we do not want to capture new variables. What was captured
19971 // during either a lambdas transformation or initial parsing
19972 // should be used.
19974 if (BuildAndDiagnose) {
19977 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19978 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19979 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19980 buildLambdaCaptureFixit(*this, LSI, Var);
19981 } else
19983 }
19984 return true;
19985 }
19986
19987 // Try to capture variable-length arrays types.
19988 if (Var->getType()->isVariablyModifiedType()) {
19989 // We're going to walk down into the type and look for VLA
19990 // expressions.
19991 QualType QTy = Var->getType();
19992 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19993 QTy = PVD->getOriginalType();
19995 }
19996
19997 if (getLangOpts().OpenMP) {
19998 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19999 // OpenMP private variables should not be captured in outer scope, so
20000 // just break here. Similarly, global variables that are captured in a
20001 // target region should not be captured outside the scope of the region.
20002 if (RSI->CapRegionKind == CR_OpenMP) {
20003 // FIXME: We should support capturing structured bindings in OpenMP.
20004 if (isa<BindingDecl>(Var)) {
20005 if (BuildAndDiagnose) {
20006 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
20007 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
20008 }
20009 return true;
20010 }
20011 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
20012 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
20013 // If the variable is private (i.e. not captured) and has variably
20014 // modified type, we still need to capture the type for correct
20015 // codegen in all regions, associated with the construct. Currently,
20016 // it is captured in the innermost captured region only.
20017 if (IsOpenMPPrivateDecl != OMPC_unknown &&
20018 Var->getType()->isVariablyModifiedType()) {
20019 QualType QTy = Var->getType();
20020 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
20021 QTy = PVD->getOriginalType();
20022 for (int I = 1,
20023 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
20024 I < E; ++I) {
20025 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
20026 FunctionScopes[FunctionScopesIndex - I]);
20027 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
20028 "Wrong number of captured regions associated with the "
20029 "OpenMP construct.");
20030 captureVariablyModifiedType(Context, QTy, OuterRSI);
20031 }
20032 }
20033 bool IsTargetCap =
20034 IsOpenMPPrivateDecl != OMPC_private &&
20035 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
20036 RSI->OpenMPCaptureLevel);
20037 // Do not capture global if it is not privatized in outer regions.
20038 bool IsGlobalCap =
20039 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
20040 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
20041
20042 // When we detect target captures we are looking from inside the
20043 // target region, therefore we need to propagate the capture from the
20044 // enclosing region. Therefore, the capture is not initially nested.
20045 if (IsTargetCap)
20046 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
20047 RSI->OpenMPLevel);
20048
20049 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
20050 (IsGlobal && !IsGlobalCap)) {
20051 Nested = !IsTargetCap;
20052 bool HasConst = DeclRefType.isConstQualified();
20053 DeclRefType = DeclRefType.getUnqualifiedType();
20054 // Don't lose diagnostics about assignments to const.
20055 if (HasConst)
20056 DeclRefType.addConst();
20057 CaptureType = Context.getLValueReferenceType(DeclRefType);
20058 break;
20059 }
20060 }
20061 }
20062 }
20064 // No capture-default, and this is not an explicit capture
20065 // so cannot capture this variable.
20066 if (BuildAndDiagnose) {
20067 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
20068 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
20069 auto *LSI = cast<LambdaScopeInfo>(CSI);
20070 if (LSI->Lambda) {
20071 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
20072 buildLambdaCaptureFixit(*this, LSI, Var);
20073 }
20074 // FIXME: If we error out because an outer lambda can not implicitly
20075 // capture a variable that an inner lambda explicitly captures, we
20076 // should have the inner lambda do the explicit capture - because
20077 // it makes for cleaner diagnostics later. This would purely be done
20078 // so that the diagnostic does not misleadingly claim that a variable
20079 // can not be captured by a lambda implicitly even though it is captured
20080 // explicitly. Suggestion:
20081 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
20082 // at the function head
20083 // - cache the StartingDeclContext - this must be a lambda
20084 // - captureInLambda in the innermost lambda the variable.
20085 }
20086 return true;
20087 }
20088 Explicit = false;
20089 FunctionScopesIndex--;
20090 if (IsInScopeDeclarationContext)
20091 DC = ParentDC;
20092 } while (!VarDC->Equals(DC));
20093
20094 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
20095 // computing the type of the capture at each step, checking type-specific
20096 // requirements, and adding captures if requested.
20097 // If the variable had already been captured previously, we start capturing
20098 // at the lambda nested within that one.
20099 bool Invalid = false;
20100 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
20101 ++I) {
20103
20104 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
20105 // certain types of variables (unnamed, variably modified types etc.)
20106 // so check for eligibility.
20107 if (!Invalid)
20108 Invalid =
20109 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
20110
20111 // After encountering an error, if we're actually supposed to capture, keep
20112 // capturing in nested contexts to suppress any follow-on diagnostics.
20113 if (Invalid && !BuildAndDiagnose)
20114 return true;
20115
20116 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
20117 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20118 DeclRefType, Nested, *this, Invalid);
20119 Nested = true;
20120 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
20122 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
20123 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
20124 Nested = true;
20125 } else {
20127 Invalid =
20128 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20129 DeclRefType, Nested, Kind, EllipsisLoc,
20130 /*IsTopScope*/ I == N - 1, *this, Invalid);
20131 Nested = true;
20132 }
20133
20134 if (Invalid && !BuildAndDiagnose)
20135 return true;
20136 }
20137 return Invalid;
20138}
20139
20141 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20142 QualType CaptureType;
20143 QualType DeclRefType;
20144 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
20145 /*BuildAndDiagnose=*/true, CaptureType,
20146 DeclRefType, nullptr);
20147}
20148
20150 QualType CaptureType;
20151 QualType DeclRefType;
20152 return !tryCaptureVariable(
20154 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);
20155}
20156
20158 assert(Var && "Null value cannot be captured");
20159
20160 QualType CaptureType;
20161 QualType DeclRefType;
20162
20163 // Determine whether we can capture this variable.
20165 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20166 nullptr))
20167 return QualType();
20168
20169 return DeclRefType;
20170}
20171
20172namespace {
20173// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20174// The produced TemplateArgumentListInfo* points to data stored within this
20175// object, so should only be used in contexts where the pointer will not be
20176// used after the CopiedTemplateArgs object is destroyed.
20177class CopiedTemplateArgs {
20178 bool HasArgs;
20179 TemplateArgumentListInfo TemplateArgStorage;
20180public:
20181 template<typename RefExpr>
20182 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20183 if (HasArgs)
20184 E->copyTemplateArgumentsInto(TemplateArgStorage);
20185 }
20186 operator TemplateArgumentListInfo*()
20187#ifdef __has_cpp_attribute
20188#if __has_cpp_attribute(clang::lifetimebound)
20189 [[clang::lifetimebound]]
20190#endif
20191#endif
20192 {
20193 return HasArgs ? &TemplateArgStorage : nullptr;
20194 }
20195};
20196}
20197
20198/// Walk the set of potential results of an expression and mark them all as
20199/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20200///
20201/// \return A new expression if we found any potential results, ExprEmpty() if
20202/// not, and ExprError() if we diagnosed an error.
20204 NonOdrUseReason NOUR) {
20205 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20206 // an object that satisfies the requirements for appearing in a
20207 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20208 // is immediately applied." This function handles the lvalue-to-rvalue
20209 // conversion part.
20210 //
20211 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20212 // transform it into the relevant kind of non-odr-use node and rebuild the
20213 // tree of nodes leading to it.
20214 //
20215 // This is a mini-TreeTransform that only transforms a restricted subset of
20216 // nodes (and only certain operands of them).
20217
20218 // Rebuild a subexpression.
20219 auto Rebuild = [&](Expr *Sub) {
20220 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
20221 };
20222
20223 // Check whether a potential result satisfies the requirements of NOUR.
20224 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20225 // Any entity other than a VarDecl is always odr-used whenever it's named
20226 // in a potentially-evaluated expression.
20227 auto *VD = dyn_cast<VarDecl>(D);
20228 if (!VD)
20229 return true;
20230
20231 // C++2a [basic.def.odr]p4:
20232 // A variable x whose name appears as a potentially-evalauted expression
20233 // e is odr-used by e unless
20234 // -- x is a reference that is usable in constant expressions, or
20235 // -- x is a variable of non-reference type that is usable in constant
20236 // expressions and has no mutable subobjects, and e is an element of
20237 // the set of potential results of an expression of
20238 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20239 // conversion is applied, or
20240 // -- x is a variable of non-reference type, and e is an element of the
20241 // set of potential results of a discarded-value expression to which
20242 // the lvalue-to-rvalue conversion is not applied
20243 //
20244 // We check the first bullet and the "potentially-evaluated" condition in
20245 // BuildDeclRefExpr. We check the type requirements in the second bullet
20246 // in CheckLValueToRValueConversionOperand below.
20247 switch (NOUR) {
20248 case NOUR_None:
20249 case NOUR_Unevaluated:
20250 llvm_unreachable("unexpected non-odr-use-reason");
20251
20252 case NOUR_Constant:
20253 // Constant references were handled when they were built.
20254 if (VD->getType()->isReferenceType())
20255 return true;
20256 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20257 if (RD->hasDefinition() && RD->hasMutableFields())
20258 return true;
20259 if (!VD->isUsableInConstantExpressions(S.Context))
20260 return true;
20261 break;
20262
20263 case NOUR_Discarded:
20264 if (VD->getType()->isReferenceType())
20265 return true;
20266 break;
20267 }
20268 return false;
20269 };
20270
20271 // Check whether this expression may be odr-used in CUDA/HIP.
20272 auto MaybeCUDAODRUsed = [&]() -> bool {
20273 if (!S.LangOpts.CUDA)
20274 return false;
20275 LambdaScopeInfo *LSI = S.getCurLambda();
20276 if (!LSI)
20277 return false;
20278 auto *DRE = dyn_cast<DeclRefExpr>(E);
20279 if (!DRE)
20280 return false;
20281 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
20282 if (!VD)
20283 return false;
20284 return LSI->CUDAPotentialODRUsedVars.count(VD);
20285 };
20286
20287 // Mark that this expression does not constitute an odr-use.
20288 auto MarkNotOdrUsed = [&] {
20289 if (!MaybeCUDAODRUsed()) {
20290 S.MaybeODRUseExprs.remove(E);
20291 if (LambdaScopeInfo *LSI = S.getCurLambda())
20292 LSI->markVariableExprAsNonODRUsed(E);
20293 }
20294 };
20295
20296 // C++2a [basic.def.odr]p2:
20297 // The set of potential results of an expression e is defined as follows:
20298 switch (E->getStmtClass()) {
20299 // -- If e is an id-expression, ...
20300 case Expr::DeclRefExprClass: {
20301 auto *DRE = cast<DeclRefExpr>(E);
20302 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20303 break;
20304
20305 // Rebuild as a non-odr-use DeclRefExpr.
20306 MarkNotOdrUsed();
20307 return DeclRefExpr::Create(
20308 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
20309 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
20310 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
20311 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
20312 }
20313
20314 case Expr::FunctionParmPackExprClass: {
20315 auto *FPPE = cast<FunctionParmPackExpr>(E);
20316 // If any of the declarations in the pack is odr-used, then the expression
20317 // as a whole constitutes an odr-use.
20318 for (ValueDecl *D : *FPPE)
20319 if (IsPotentialResultOdrUsed(D))
20320 return ExprEmpty();
20321
20322 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20323 // nothing cares about whether we marked this as an odr-use, but it might
20324 // be useful for non-compiler tools.
20325 MarkNotOdrUsed();
20326 break;
20327 }
20328
20329 // -- If e is a subscripting operation with an array operand...
20330 case Expr::ArraySubscriptExprClass: {
20331 auto *ASE = cast<ArraySubscriptExpr>(E);
20332 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20333 if (!OldBase->getType()->isArrayType())
20334 break;
20335 ExprResult Base = Rebuild(OldBase);
20336 if (!Base.isUsable())
20337 return Base;
20338 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20339 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20340 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20341 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
20342 ASE->getRBracketLoc());
20343 }
20344
20345 case Expr::MemberExprClass: {
20346 auto *ME = cast<MemberExpr>(E);
20347 // -- If e is a class member access expression [...] naming a non-static
20348 // data member...
20349 if (isa<FieldDecl>(ME->getMemberDecl())) {
20350 ExprResult Base = Rebuild(ME->getBase());
20351 if (!Base.isUsable())
20352 return Base;
20353 return MemberExpr::Create(
20354 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
20355 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
20356 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
20357 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
20358 ME->getObjectKind(), ME->isNonOdrUse());
20359 }
20360
20361 if (ME->getMemberDecl()->isCXXInstanceMember())
20362 break;
20363
20364 // -- If e is a class member access expression naming a static data member,
20365 // ...
20366 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20367 break;
20368
20369 // Rebuild as a non-odr-use MemberExpr.
20370 MarkNotOdrUsed();
20371 return MemberExpr::Create(
20372 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
20373 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
20374 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
20375 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
20376 }
20377
20378 case Expr::BinaryOperatorClass: {
20379 auto *BO = cast<BinaryOperator>(E);
20380 Expr *LHS = BO->getLHS();
20381 Expr *RHS = BO->getRHS();
20382 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20383 if (BO->getOpcode() == BO_PtrMemD) {
20384 ExprResult Sub = Rebuild(LHS);
20385 if (!Sub.isUsable())
20386 return Sub;
20387 BO->setLHS(Sub.get());
20388 // -- If e is a comma expression, ...
20389 } else if (BO->getOpcode() == BO_Comma) {
20390 ExprResult Sub = Rebuild(RHS);
20391 if (!Sub.isUsable())
20392 return Sub;
20393 BO->setRHS(Sub.get());
20394 } else {
20395 break;
20396 }
20397 return ExprResult(BO);
20398 }
20399
20400 // -- If e has the form (e1)...
20401 case Expr::ParenExprClass: {
20402 auto *PE = cast<ParenExpr>(E);
20403 ExprResult Sub = Rebuild(PE->getSubExpr());
20404 if (!Sub.isUsable())
20405 return Sub;
20406 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20407 }
20408
20409 // -- If e is a glvalue conditional expression, ...
20410 // We don't apply this to a binary conditional operator. FIXME: Should we?
20411 case Expr::ConditionalOperatorClass: {
20412 auto *CO = cast<ConditionalOperator>(E);
20413 ExprResult LHS = Rebuild(CO->getLHS());
20414 if (LHS.isInvalid())
20415 return ExprError();
20416 ExprResult RHS = Rebuild(CO->getRHS());
20417 if (RHS.isInvalid())
20418 return ExprError();
20419 if (!LHS.isUsable() && !RHS.isUsable())
20420 return ExprEmpty();
20421 if (!LHS.isUsable())
20422 LHS = CO->getLHS();
20423 if (!RHS.isUsable())
20424 RHS = CO->getRHS();
20425 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20426 CO->getCond(), LHS.get(), RHS.get());
20427 }
20428
20429 // [Clang extension]
20430 // -- If e has the form __extension__ e1...
20431 case Expr::UnaryOperatorClass: {
20432 auto *UO = cast<UnaryOperator>(E);
20433 if (UO->getOpcode() != UO_Extension)
20434 break;
20435 ExprResult Sub = Rebuild(UO->getSubExpr());
20436 if (!Sub.isUsable())
20437 return Sub;
20438 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20439 Sub.get());
20440 }
20441
20442 // [Clang extension]
20443 // -- If e has the form _Generic(...), the set of potential results is the
20444 // union of the sets of potential results of the associated expressions.
20445 case Expr::GenericSelectionExprClass: {
20446 auto *GSE = cast<GenericSelectionExpr>(E);
20447
20448 SmallVector<Expr *, 4> AssocExprs;
20449 bool AnyChanged = false;
20450 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20451 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20452 if (AssocExpr.isInvalid())
20453 return ExprError();
20454 if (AssocExpr.isUsable()) {
20455 AssocExprs.push_back(AssocExpr.get());
20456 AnyChanged = true;
20457 } else {
20458 AssocExprs.push_back(OrigAssocExpr);
20459 }
20460 }
20461
20462 void *ExOrTy = nullptr;
20463 bool IsExpr = GSE->isExprPredicate();
20464 if (IsExpr)
20465 ExOrTy = GSE->getControllingExpr();
20466 else
20467 ExOrTy = GSE->getControllingType();
20468 return AnyChanged ? S.CreateGenericSelectionExpr(
20469 GSE->getGenericLoc(), GSE->getDefaultLoc(),
20470 GSE->getRParenLoc(), IsExpr, ExOrTy,
20471 GSE->getAssocTypeSourceInfos(), AssocExprs)
20472 : ExprEmpty();
20473 }
20474
20475 // [Clang extension]
20476 // -- If e has the form __builtin_choose_expr(...), the set of potential
20477 // results is the union of the sets of potential results of the
20478 // second and third subexpressions.
20479 case Expr::ChooseExprClass: {
20480 auto *CE = cast<ChooseExpr>(E);
20481
20482 ExprResult LHS = Rebuild(CE->getLHS());
20483 if (LHS.isInvalid())
20484 return ExprError();
20485
20486 ExprResult RHS = Rebuild(CE->getLHS());
20487 if (RHS.isInvalid())
20488 return ExprError();
20489
20490 if (!LHS.get() && !RHS.get())
20491 return ExprEmpty();
20492 if (!LHS.isUsable())
20493 LHS = CE->getLHS();
20494 if (!RHS.isUsable())
20495 RHS = CE->getRHS();
20496
20497 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20498 RHS.get(), CE->getRParenLoc());
20499 }
20500
20501 // Step through non-syntactic nodes.
20502 case Expr::ConstantExprClass: {
20503 auto *CE = cast<ConstantExpr>(E);
20504 ExprResult Sub = Rebuild(CE->getSubExpr());
20505 if (!Sub.isUsable())
20506 return Sub;
20507 return ConstantExpr::Create(S.Context, Sub.get());
20508 }
20509
20510 // We could mostly rely on the recursive rebuilding to rebuild implicit
20511 // casts, but not at the top level, so rebuild them here.
20512 case Expr::ImplicitCastExprClass: {
20513 auto *ICE = cast<ImplicitCastExpr>(E);
20514 // Only step through the narrow set of cast kinds we expect to encounter.
20515 // Anything else suggests we've left the region in which potential results
20516 // can be found.
20517 switch (ICE->getCastKind()) {
20518 case CK_NoOp:
20519 case CK_DerivedToBase:
20520 case CK_UncheckedDerivedToBase: {
20521 ExprResult Sub = Rebuild(ICE->getSubExpr());
20522 if (!Sub.isUsable())
20523 return Sub;
20524 CXXCastPath Path(ICE->path());
20525 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20526 ICE->getValueKind(), &Path);
20527 }
20528
20529 default:
20530 break;
20531 }
20532 break;
20533 }
20534
20535 default:
20536 break;
20537 }
20538
20539 // Can't traverse through this node. Nothing to do.
20540 return ExprEmpty();
20541}
20542
20544 // Check whether the operand is or contains an object of non-trivial C union
20545 // type.
20546 if (E->getType().isVolatileQualified() &&
20552
20553 // C++2a [basic.def.odr]p4:
20554 // [...] an expression of non-volatile-qualified non-class type to which
20555 // the lvalue-to-rvalue conversion is applied [...]
20556 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20557 return E;
20558
20561 if (Result.isInvalid())
20562 return ExprError();
20563 return Result.get() ? Result : E;
20564}
20565
20567 if (!Res.isUsable())
20568 return Res;
20569
20570 // If a constant-expression is a reference to a variable where we delay
20571 // deciding whether it is an odr-use, just assume we will apply the
20572 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20573 // (a non-type template argument), we have special handling anyway.
20575}
20576
20578 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20579 // call.
20580 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20581 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20582
20583 for (Expr *E : LocalMaybeODRUseExprs) {
20584 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20585 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20586 DRE->getLocation(), *this);
20587 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20588 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20589 *this);
20590 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20591 for (ValueDecl *VD : *FP)
20592 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20593 } else {
20594 llvm_unreachable("Unexpected expression");
20595 }
20596 }
20597
20598 assert(MaybeODRUseExprs.empty() &&
20599 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20600}
20601
20603 ValueDecl *Var, Expr *E) {
20605 if (!VD)
20606 return;
20607
20608 const bool RefersToEnclosingScope =
20609 (SemaRef.CurContext != VD->getDeclContext() &&
20611 if (RefersToEnclosingScope) {
20612 LambdaScopeInfo *const LSI =
20613 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20614 if (LSI && (!LSI->CallOperator ||
20615 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20616 // If a variable could potentially be odr-used, defer marking it so
20617 // until we finish analyzing the full expression for any
20618 // lvalue-to-rvalue
20619 // or discarded value conversions that would obviate odr-use.
20620 // Add it to the list of potential captures that will be analyzed
20621 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20622 // unless the variable is a reference that was initialized by a constant
20623 // expression (this will never need to be captured or odr-used).
20624 //
20625 // FIXME: We can simplify this a lot after implementing P0588R1.
20626 assert(E && "Capture variable should be used in an expression.");
20627 if (!Var->getType()->isReferenceType() ||
20630 }
20631 }
20632}
20633
20635 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20636 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20637 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20639 "Invalid Expr argument to DoMarkVarDeclReferenced");
20640 Var->setReferenced();
20641
20642 if (Var->isInvalidDecl())
20643 return;
20644
20645 auto *MSI = Var->getMemberSpecializationInfo();
20646 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20648
20649 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20650 bool UsableInConstantExpr =
20652
20653 // Only track variables with internal linkage or local scope.
20654 // Use canonical decl so in-class declarations and out-of-class definitions
20655 // of static data members in anonymous namespaces are tracked as a single
20656 // entry.
20657 const VarDecl *CanonVar = Var->getCanonicalDecl();
20658 if ((CanonVar->isLocalVarDeclOrParm() ||
20659 CanonVar->isInternalLinkageFileVar()) &&
20660 !CanonVar->hasExternalStorage()) {
20661 RefsMinusAssignments.insert({CanonVar, 0}).first->getSecond()++;
20662 }
20663
20664 // C++20 [expr.const]p12:
20665 // A variable [...] is needed for constant evaluation if it is [...] a
20666 // variable whose name appears as a potentially constant evaluated
20667 // expression that is either a contexpr variable or is of non-volatile
20668 // const-qualified integral type or of reference type
20669 bool NeededForConstantEvaluation =
20670 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20671
20672 bool NeedDefinition =
20673 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20674 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20675 Var->getType()->isUndeducedType());
20676
20678 "Can't instantiate a partial template specialization.");
20679
20680 // If this might be a member specialization of a static data member, check
20681 // the specialization is visible. We already did the checks for variable
20682 // template specializations when we created them.
20683 if (NeedDefinition && TSK != TSK_Undeclared &&
20686
20687 // Perform implicit instantiation of static data members, static data member
20688 // templates of class templates, and variable template specializations. Delay
20689 // instantiations of variable templates, except for those that could be used
20690 // in a constant expression.
20691 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20692 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20693 // instantiation declaration if a variable is usable in a constant
20694 // expression (among other cases).
20695 bool TryInstantiating =
20697 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20698
20699 if (TryInstantiating) {
20700 SourceLocation PointOfInstantiation =
20701 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20702 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20703 if (FirstInstantiation) {
20704 PointOfInstantiation = Loc;
20705 if (MSI)
20706 MSI->setPointOfInstantiation(PointOfInstantiation);
20707 // FIXME: Notify listener.
20708 else
20709 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20710 }
20711
20712 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20713 // Do not defer instantiations of variables that could be used in a
20714 // constant expression.
20715 // The type deduction also needs a complete initializer.
20716 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20717 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20718 });
20719
20720 // The size of an incomplete array type can be updated by
20721 // instantiating the initializer. The DeclRefExpr's type should be
20722 // updated accordingly too, or users of it would be confused!
20723 if (E)
20725
20726 // Re-set the member to trigger a recomputation of the dependence bits
20727 // for the expression.
20728 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20729 DRE->setDecl(DRE->getDecl());
20730 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20731 ME->setMemberDecl(ME->getMemberDecl());
20732 } else if (FirstInstantiation) {
20734 .push_back(std::make_pair(Var, PointOfInstantiation));
20735 } else {
20736 bool Inserted = false;
20737 for (auto &I : SemaRef.SavedPendingInstantiations) {
20738 auto Iter = llvm::find_if(
20739 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20740 return P.first == Var;
20741 });
20742 if (Iter != I.end()) {
20743 SemaRef.PendingInstantiations.push_back(*Iter);
20744 I.erase(Iter);
20745 Inserted = true;
20746 break;
20747 }
20748 }
20749
20750 // FIXME: For a specialization of a variable template, we don't
20751 // distinguish between "declaration and type implicitly instantiated"
20752 // and "implicit instantiation of definition requested", so we have
20753 // no direct way to avoid enqueueing the pending instantiation
20754 // multiple times.
20755 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20757 .push_back(std::make_pair(Var, PointOfInstantiation));
20758 }
20759 }
20760 }
20761
20762 // C++2a [basic.def.odr]p4:
20763 // A variable x whose name appears as a potentially-evaluated expression e
20764 // is odr-used by e unless
20765 // -- x is a reference that is usable in constant expressions
20766 // -- x is a variable of non-reference type that is usable in constant
20767 // expressions and has no mutable subobjects [FIXME], and e is an
20768 // element of the set of potential results of an expression of
20769 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20770 // conversion is applied
20771 // -- x is a variable of non-reference type, and e is an element of the set
20772 // of potential results of a discarded-value expression to which the
20773 // lvalue-to-rvalue conversion is not applied [FIXME]
20774 //
20775 // We check the first part of the second bullet here, and
20776 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20777 // FIXME: To get the third bullet right, we need to delay this even for
20778 // variables that are not usable in constant expressions.
20779
20780 // If we already know this isn't an odr-use, there's nothing more to do.
20781 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20782 if (DRE->isNonOdrUse())
20783 return;
20784 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20785 if (ME->isNonOdrUse())
20786 return;
20787
20788 switch (OdrUse) {
20789 case OdrUseContext::None:
20790 // In some cases, a variable may not have been marked unevaluated, if it
20791 // appears in a defaukt initializer.
20792 assert((!E || isa<FunctionParmPackExpr>(E) ||
20794 "missing non-odr-use marking for unevaluated decl ref");
20795 break;
20796
20797 case OdrUseContext::FormallyOdrUsed:
20798 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20799 // behavior.
20800 break;
20801
20802 case OdrUseContext::Used:
20803 // If we might later find that this expression isn't actually an odr-use,
20804 // delay the marking.
20806 SemaRef.MaybeODRUseExprs.insert(E);
20807 else
20808 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20809 break;
20810
20811 case OdrUseContext::Dependent:
20812 // If this is a dependent context, we don't need to mark variables as
20813 // odr-used, but we may still need to track them for lambda capture.
20814 // FIXME: Do we also need to do this inside dependent typeid expressions
20815 // (which are modeled as unevaluated at this point)?
20816 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20817 break;
20818 }
20819}
20820
20822 BindingDecl *BD, Expr *E) {
20823 BD->setReferenced();
20824
20825 if (BD->isInvalidDecl())
20826 return;
20827
20828 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20829 if (OdrUse == OdrUseContext::Used) {
20830 QualType CaptureType, DeclRefType;
20832 /*EllipsisLoc*/ SourceLocation(),
20833 /*BuildAndDiagnose*/ true, CaptureType,
20834 DeclRefType,
20835 /*FunctionScopeIndexToStopAt*/ nullptr);
20836 } else if (OdrUse == OdrUseContext::Dependent) {
20837 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20838 }
20839}
20840
20842 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20843}
20844
20845// C++ [temp.dep.expr]p3:
20846// An id-expression is type-dependent if it contains:
20847// - an identifier associated by name lookup with an entity captured by copy
20848// in a lambda-expression that has an explicit object parameter whose type
20849// is dependent ([dcl.fct]),
20851 Sema &SemaRef, ValueDecl *D, Expr *E) {
20852 auto *ID = dyn_cast<DeclRefExpr>(E);
20853 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20854 return;
20855
20856 // If any enclosing lambda with a dependent explicit object parameter either
20857 // explicitly captures the variable by value, or has a capture default of '='
20858 // and does not capture the variable by reference, then the type of the DRE
20859 // is dependent on the type of that lambda's explicit object parameter.
20860 auto IsDependent = [&]() {
20861 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
20862 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
20863 if (!LSI)
20864 continue;
20865
20866 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
20867 LSI->AfterParameterList)
20868 return false;
20869
20870 const auto *MD = LSI->CallOperator;
20871 if (MD->getType().isNull())
20872 continue;
20873
20874 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20875 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20876 !Ty->getParamType(0)->isDependentType())
20877 continue;
20878
20879 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
20880 if (C->isCopyCapture())
20881 return true;
20882 continue;
20883 }
20884
20885 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20886 return true;
20887 }
20888 return false;
20889 }();
20890
20891 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20892 IsDependent, SemaRef.getASTContext());
20893}
20894
20895static void
20897 bool MightBeOdrUse,
20898 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20901
20902 if (SemaRef.getLangOpts().OpenACC)
20903 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20904
20905 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20907 if (SemaRef.getLangOpts().CPlusPlus)
20909 Var, E);
20910 return;
20911 }
20912
20913 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20915 if (SemaRef.getLangOpts().CPlusPlus)
20917 Decl, E);
20918 return;
20919 }
20920 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20921
20922 // If this is a call to a method via a cast, also mark the method in the
20923 // derived class used in case codegen can devirtualize the call.
20924 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20925 if (!ME)
20926 return;
20927 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20928 if (!MD)
20929 return;
20930 // Only attempt to devirtualize if this is truly a virtual call.
20931 bool IsVirtualCall = MD->isVirtual() &&
20933 if (!IsVirtualCall)
20934 return;
20935
20936 // If it's possible to devirtualize the call, mark the called function
20937 // referenced.
20939 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20940 if (DM)
20941 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20942}
20943
20945 // [basic.def.odr] (CWG 1614)
20946 // A function is named by an expression or conversion [...]
20947 // unless it is a pure virtual function and either the expression is not an
20948 // id-expression naming the function with an explicitly qualified name or
20949 // the expression forms a pointer to member
20950 bool OdrUse = true;
20951 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20952 if (Method->isVirtual() &&
20953 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20954 OdrUse = false;
20955
20956 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20960 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20961 !FD->isDependentContext())
20962 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20963 }
20964 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20966}
20967
20969 // C++11 [basic.def.odr]p2:
20970 // A non-overloaded function whose name appears as a potentially-evaluated
20971 // expression or a member of a set of candidate functions, if selected by
20972 // overload resolution when referred to from a potentially-evaluated
20973 // expression, is odr-used, unless it is a pure virtual function and its
20974 // name is not explicitly qualified.
20975 bool MightBeOdrUse = true;
20977 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20978 if (Method->isPureVirtual())
20979 MightBeOdrUse = false;
20980 }
20981 SourceLocation Loc =
20982 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20983 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20985}
20986
20992
20993/// Perform marking for a reference to an arbitrary declaration. It
20994/// marks the declaration referenced, and performs odr-use checking for
20995/// functions and variables. This method should not be used when building a
20996/// normal expression which refers to a variable.
20998 bool MightBeOdrUse) {
20999 if (MightBeOdrUse) {
21000 if (auto *VD = dyn_cast<VarDecl>(D)) {
21001 MarkVariableReferenced(Loc, VD);
21002 return;
21003 }
21004 }
21005 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
21006 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
21007 return;
21008 }
21009 D->setReferenced();
21010}
21011
21012namespace {
21013 // Mark all of the declarations used by a type as referenced.
21014 // FIXME: Not fully implemented yet! We need to have a better understanding
21015 // of when we're entering a context we should not recurse into.
21016 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
21017 // TreeTransforms rebuilding the type in a new context. Rather than
21018 // duplicating the TreeTransform logic, we should consider reusing it here.
21019 // Currently that causes problems when rebuilding LambdaExprs.
21020class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
21021 Sema &S;
21022 SourceLocation Loc;
21023
21024public:
21025 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
21026
21027 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
21028};
21029}
21030
21031bool MarkReferencedDecls::TraverseTemplateArgument(
21032 const TemplateArgument &Arg) {
21033 {
21034 // A non-type template argument is a constant-evaluated context.
21035 EnterExpressionEvaluationContext Evaluated(
21038 if (Decl *D = Arg.getAsDecl())
21039 S.MarkAnyDeclReferenced(Loc, D, true);
21040 } else if (Arg.getKind() == TemplateArgument::Expression) {
21042 }
21043 }
21044
21046}
21047
21049 MarkReferencedDecls Marker(*this, Loc);
21050 Marker.TraverseType(T);
21051}
21052
21053namespace {
21054/// Helper class that marks all of the declarations referenced by
21055/// potentially-evaluated subexpressions as "referenced".
21056class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
21057public:
21058 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
21059 bool SkipLocalVariables;
21061
21062 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
21064 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
21065
21066 void visitUsedDecl(SourceLocation Loc, Decl *D) {
21068 }
21069
21070 void Visit(Expr *E) {
21071 if (llvm::is_contained(StopAt, E))
21072 return;
21073 Inherited::Visit(E);
21074 }
21075
21076 void VisitConstantExpr(ConstantExpr *E) {
21077 // Don't mark declarations within a ConstantExpression, as this expression
21078 // will be evaluated and folded to a value.
21079 }
21080
21081 void VisitDeclRefExpr(DeclRefExpr *E) {
21082 // If we were asked not to visit local variables, don't.
21083 if (SkipLocalVariables) {
21084 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
21085 if (VD->hasLocalStorage())
21086 return;
21087 }
21088
21089 // FIXME: This can trigger the instantiation of the initializer of a
21090 // variable, which can cause the expression to become value-dependent
21091 // or error-dependent. Do we need to propagate the new dependence bits?
21093 }
21094
21095 void VisitMemberExpr(MemberExpr *E) {
21097 Visit(E->getBase());
21098 }
21099};
21100} // namespace
21101
21103 bool SkipLocalVariables,
21104 ArrayRef<const Expr*> StopAt) {
21105 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
21106}
21107
21108/// Emit a diagnostic when statements are reachable.
21110 const PartialDiagnostic &PD) {
21111 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
21112 // The initializer of a constexpr variable or of the first declaration of a
21113 // static data member is not syntactically a constant evaluated constant,
21114 // but nonetheless is always required to be a constant expression, so we
21115 // can skip diagnosing.
21116 if (Decl &&
21117 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
21118 Decl->isFirstDecl() && !Decl->isInline())))
21119 return false;
21120
21121 if (Stmts.empty()) {
21122 Diag(Loc, PD);
21123 return true;
21124 }
21125
21126 if (getCurFunction()) {
21127 // This queue flushes after the function is analyzed, by which time an
21128 // ignore-all-warnings region live here is gone, so sample it now. A note
21129 // is not error-class either, so this also drops the notes that accompany a
21130 // skipped warning. They arrive on their own call, out of reach of the
21131 // engine's rule that drops a note whose warning was ignored.
21132 if (Diags.getIgnoreAllWarnings() &&
21133 Diags.getDiagnosticIDs()->isWarningOrExtension(PD.getDiagID()))
21134 return false;
21135 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21136 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21137 return true;
21138 }
21139
21140 // For non-constexpr file-scope variables with reachability context (non-empty
21141 // Stmts), build a CFG for the initializer and check whether the context in
21142 // question is reachable.
21143 if (Decl && Decl->isFileVarDecl()) {
21144 AnalysisWarnings.registerVarDeclWarning(
21145 Decl, sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21146 return true;
21147 }
21148
21149 Diag(Loc, PD);
21150 return true;
21151}
21152
21153/// Emit a diagnostic that describes an effect on the run-time behavior
21154/// of the program being compiled.
21155///
21156/// This routine emits the given diagnostic when the code currently being
21157/// type-checked is "potentially evaluated", meaning that there is a
21158/// possibility that the code will actually be executable. Code in sizeof()
21159/// expressions, code used only during overload resolution, etc., are not
21160/// potentially evaluated. This routine will suppress such diagnostics or,
21161/// in the absolutely nutty case of potentially potentially evaluated
21162/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21163/// later.
21164///
21165/// This routine should be used for all diagnostics that describe the run-time
21166/// behavior of a program, such as passing a non-POD value through an ellipsis.
21167/// Failure to do so will likely result in spurious diagnostics or failures
21168/// during overload resolution or within sizeof/alignof/typeof/typeid.
21170 const PartialDiagnostic &PD) {
21171
21172 if (ExprEvalContexts.back().isDiscardedStatementContext())
21173 return false;
21174
21175 switch (ExprEvalContexts.back().Context) {
21180 // The argument will never be evaluated, so don't complain.
21181 break;
21182
21185 // Relevant diagnostics should be produced by constant evaluation.
21186 break;
21187
21190 return DiagIfReachable(Loc, Stmts, PD);
21191 }
21192
21193 return false;
21194}
21195
21197 const PartialDiagnostic &PD) {
21198 return DiagRuntimeBehavior(
21199 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21200 PD);
21201}
21202
21204 CallExpr *CE, FunctionDecl *FD) {
21205 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21206 return false;
21207
21208 // If we're inside a decltype's expression, don't check for a valid return
21209 // type or construct temporaries until we know whether this is the last call.
21210 if (ExprEvalContexts.back().ExprContext ==
21212 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
21213 return false;
21214 }
21215
21216 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21217 FunctionDecl *FD;
21218 CallExpr *CE;
21219
21220 public:
21221 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21222 : FD(FD), CE(CE) { }
21223
21224 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21225 if (!FD) {
21226 S.Diag(Loc, diag::err_call_incomplete_return)
21227 << T << CE->getSourceRange();
21228 return;
21229 }
21230
21231 S.Diag(Loc, diag::err_call_function_incomplete_return)
21232 << CE->getSourceRange() << FD << T;
21233 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
21234 << FD->getDeclName();
21235 }
21236 } Diagnoser(FD, CE);
21237
21238 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
21239 return true;
21240
21241 return false;
21242}
21243
21244// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21245// will prevent this condition from triggering, which is what we want.
21247 SourceLocation Loc;
21248
21249 unsigned diagnostic = diag::warn_condition_is_assignment;
21250 bool IsOrAssign = false;
21251
21252 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
21253 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21254 return;
21255
21256 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21257
21258 // Greylist some idioms by putting them into a warning subcategory.
21259 if (ObjCMessageExpr *ME
21260 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
21261 Selector Sel = ME->getSelector();
21262
21263 // self = [<foo> init...]
21264 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21265 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21266
21267 // <foo> = [<bar> nextObject]
21268 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
21269 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21270 }
21271
21272 Loc = Op->getOperatorLoc();
21273 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
21274 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21275 return;
21276
21277 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21278 Loc = Op->getOperatorLoc();
21279 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
21280 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
21281 else {
21282 // Not an assignment.
21283 return;
21284 }
21285
21286 Diag(Loc, diagnostic) << E->getSourceRange();
21287
21290 Diag(Loc, diag::note_condition_assign_silence)
21292 << FixItHint::CreateInsertion(Close, ")");
21293
21294 if (IsOrAssign)
21295 Diag(Loc, diag::note_condition_or_assign_to_comparison)
21296 << FixItHint::CreateReplacement(Loc, "!=");
21297 else
21298 Diag(Loc, diag::note_condition_assign_to_comparison)
21299 << FixItHint::CreateReplacement(Loc, "==");
21300}
21301
21303 // Don't warn if the parens came from a macro.
21304 SourceLocation parenLoc = ParenE->getBeginLoc();
21305 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21306 return;
21307 // Don't warn for dependent expressions.
21308 if (ParenE->isTypeDependent())
21309 return;
21310
21311 Expr *E = ParenE->IgnoreParens();
21312 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21313 return;
21314
21315 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
21316 if (opE->getOpcode() == BO_EQ &&
21317 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
21318 == Expr::MLV_Valid) {
21319 SourceLocation Loc = opE->getOperatorLoc();
21320
21321 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
21322 SourceRange ParenERange = ParenE->getSourceRange();
21323 Diag(Loc, diag::note_equality_comparison_silence)
21324 << FixItHint::CreateRemoval(ParenERange.getBegin())
21325 << FixItHint::CreateRemoval(ParenERange.getEnd());
21326 Diag(Loc, diag::note_equality_comparison_to_assign)
21327 << FixItHint::CreateReplacement(Loc, "=");
21328 }
21329}
21330
21332 bool IsConstexpr) {
21334 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
21336
21337 ExprResult result = CheckPlaceholderExpr(E);
21338 if (result.isInvalid()) return ExprError();
21339 E = result.get();
21340
21341 if (!E->isTypeDependent()) {
21342 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21344
21345 if (getLangOpts().CPlusPlus)
21346 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
21347
21349 if (ERes.isInvalid())
21350 return ExprError();
21351 E = ERes.get();
21352
21353 QualType T = E->getType();
21354 if (!T->isScalarType()) { // C99 6.8.4.1p1
21355 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
21356 << T << E->getSourceRange();
21357 return ExprError();
21358 }
21359 CheckBoolLikeConversion(E, Loc);
21360 }
21361
21362 return E;
21363}
21364
21366 Expr *SubExpr, ConditionKind CK,
21367 bool MissingOK) {
21368 // MissingOK indicates whether having no condition expression is valid
21369 // (for loop) or invalid (e.g. while loop).
21370 if (!SubExpr)
21371 return MissingOK ? ConditionResult() : ConditionError();
21372
21374 switch (CK) {
21376 Cond = CheckBooleanCondition(Loc, SubExpr);
21377 break;
21378
21380 // Note: this might produce a FullExpr
21381 Cond = CheckBooleanCondition(Loc, SubExpr, true);
21382 break;
21383
21385 Cond = CheckSwitchCondition(Loc, SubExpr);
21386 break;
21387 }
21388 if (Cond.isInvalid()) {
21389 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
21390 {SubExpr}, PreferredConditionType(CK));
21391 if (!Cond.get())
21392 return ConditionError();
21393 } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))
21394 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
21395
21396 if (!Cond.isUsable())
21397 return ConditionError();
21398
21399 return ConditionResult(*this, nullptr, Cond,
21401}
21402
21403namespace {
21404 /// A visitor for rebuilding a call to an __unknown_any expression
21405 /// to have an appropriate type.
21406 struct RebuildUnknownAnyFunction
21407 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21408
21409 Sema &S;
21410
21411 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21412
21413 ExprResult VisitStmt(Stmt *S) {
21414 llvm_unreachable("unexpected statement!");
21415 }
21416
21417 ExprResult VisitExpr(Expr *E) {
21418 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21419 << E->getSourceRange();
21420 return ExprError();
21421 }
21422
21423 /// Rebuild an expression which simply semantically wraps another
21424 /// expression which it shares the type and value kind of.
21425 template <class T> ExprResult rebuildSugarExpr(T *E) {
21426 ExprResult SubResult = Visit(E->getSubExpr());
21427 if (SubResult.isInvalid()) return ExprError();
21428
21429 Expr *SubExpr = SubResult.get();
21430 E->setSubExpr(SubExpr);
21431 E->setType(SubExpr->getType());
21432 E->setValueKind(SubExpr->getValueKind());
21433 assert(E->getObjectKind() == OK_Ordinary);
21434 return E;
21435 }
21436
21437 ExprResult VisitParenExpr(ParenExpr *E) {
21438 return rebuildSugarExpr(E);
21439 }
21440
21441 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21442 return rebuildSugarExpr(E);
21443 }
21444
21445 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21446 ExprResult SubResult = Visit(E->getSubExpr());
21447 if (SubResult.isInvalid()) return ExprError();
21448
21449 Expr *SubExpr = SubResult.get();
21450 E->setSubExpr(SubExpr);
21451 E->setType(S.Context.getPointerType(SubExpr->getType()));
21452 assert(E->isPRValue());
21453 assert(E->getObjectKind() == OK_Ordinary);
21454 return E;
21455 }
21456
21457 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21458 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21459
21460 E->setType(VD->getType());
21461
21462 assert(E->isPRValue());
21463 if (S.getLangOpts().CPlusPlus &&
21464 !(isa<CXXMethodDecl>(VD) &&
21465 cast<CXXMethodDecl>(VD)->isInstance()))
21467
21468 return E;
21469 }
21470
21471 ExprResult VisitMemberExpr(MemberExpr *E) {
21472 return resolveDecl(E, E->getMemberDecl());
21473 }
21474
21475 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21476 return resolveDecl(E, E->getDecl());
21477 }
21478 };
21479}
21480
21481/// Given a function expression of unknown-any type, try to rebuild it
21482/// to have a function type.
21484 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21485 if (Result.isInvalid()) return ExprError();
21486 return S.DefaultFunctionArrayConversion(Result.get());
21487}
21488
21489namespace {
21490 /// A visitor for rebuilding an expression of type __unknown_anytype
21491 /// into one which resolves the type directly on the referring
21492 /// expression. Strict preservation of the original source
21493 /// structure is not a goal.
21494 struct RebuildUnknownAnyExpr
21495 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21496
21497 Sema &S;
21498
21499 /// The current destination type.
21500 QualType DestType;
21501
21502 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21503 : S(S), DestType(CastType) {}
21504
21505 ExprResult VisitStmt(Stmt *S) {
21506 llvm_unreachable("unexpected statement!");
21507 }
21508
21509 ExprResult VisitExpr(Expr *E) {
21510 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21511 << E->getSourceRange();
21512 return ExprError();
21513 }
21514
21515 ExprResult VisitCallExpr(CallExpr *E);
21516 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21517
21518 /// Rebuild an expression which simply semantically wraps another
21519 /// expression which it shares the type and value kind of.
21520 template <class T> ExprResult rebuildSugarExpr(T *E) {
21521 ExprResult SubResult = Visit(E->getSubExpr());
21522 if (SubResult.isInvalid()) return ExprError();
21523 Expr *SubExpr = SubResult.get();
21524 E->setSubExpr(SubExpr);
21525 E->setType(SubExpr->getType());
21526 E->setValueKind(SubExpr->getValueKind());
21527 assert(E->getObjectKind() == OK_Ordinary);
21528 return E;
21529 }
21530
21531 ExprResult VisitParenExpr(ParenExpr *E) {
21532 return rebuildSugarExpr(E);
21533 }
21534
21535 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21536 return rebuildSugarExpr(E);
21537 }
21538
21539 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21540 const PointerType *Ptr = DestType->getAs<PointerType>();
21541 if (!Ptr) {
21542 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21543 << E->getSourceRange();
21544 return ExprError();
21545 }
21546
21547 if (isa<CallExpr>(E->getSubExpr())) {
21548 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21549 << E->getSourceRange();
21550 return ExprError();
21551 }
21552
21553 assert(E->isPRValue());
21554 assert(E->getObjectKind() == OK_Ordinary);
21555 E->setType(DestType);
21556
21557 // Build the sub-expression as if it were an object of the pointee type.
21558 DestType = Ptr->getPointeeType();
21559 ExprResult SubResult = Visit(E->getSubExpr());
21560 if (SubResult.isInvalid()) return ExprError();
21561 E->setSubExpr(SubResult.get());
21562 return E;
21563 }
21564
21565 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21566
21567 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21568
21569 ExprResult VisitMemberExpr(MemberExpr *E) {
21570 return resolveDecl(E, E->getMemberDecl());
21571 }
21572
21573 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21574 return resolveDecl(E, E->getDecl());
21575 }
21576 };
21577}
21578
21579/// Rebuilds a call expression which yielded __unknown_anytype.
21580ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21581 Expr *CalleeExpr = E->getCallee();
21582
21583 enum FnKind {
21584 FK_MemberFunction,
21585 FK_FunctionPointer,
21586 FK_BlockPointer
21587 };
21588
21589 FnKind Kind;
21590 QualType CalleeType = CalleeExpr->getType();
21591 if (CalleeType == S.Context.BoundMemberTy) {
21593 Kind = FK_MemberFunction;
21594 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21595 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21596 CalleeType = Ptr->getPointeeType();
21597 Kind = FK_FunctionPointer;
21598 } else {
21599 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21600 Kind = FK_BlockPointer;
21601 }
21602 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21603
21604 // Verify that this is a legal result type of a function.
21605 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21606 DestType->isFunctionType()) {
21607 unsigned diagID = diag::err_func_returning_array_function;
21608 if (Kind == FK_BlockPointer)
21609 diagID = diag::err_block_returning_array_function;
21610
21611 S.Diag(E->getExprLoc(), diagID)
21612 << DestType->isFunctionType() << DestType;
21613 return ExprError();
21614 }
21615
21616 // Otherwise, go ahead and set DestType as the call's result.
21617 E->setType(DestType.getNonLValueExprType(S.Context));
21619 assert(E->getObjectKind() == OK_Ordinary);
21620
21621 // Rebuild the function type, replacing the result type with DestType.
21622 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21623 if (Proto) {
21624 // __unknown_anytype(...) is a special case used by the debugger when
21625 // it has no idea what a function's signature is.
21626 //
21627 // We want to build this call essentially under the K&R
21628 // unprototyped rules, but making a FunctionNoProtoType in C++
21629 // would foul up all sorts of assumptions. However, we cannot
21630 // simply pass all arguments as variadic arguments, nor can we
21631 // portably just call the function under a non-variadic type; see
21632 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21633 // However, it turns out that in practice it is generally safe to
21634 // call a function declared as "A foo(B,C,D);" under the prototype
21635 // "A foo(B,C,D,...);". The only known exception is with the
21636 // Windows ABI, where any variadic function is implicitly cdecl
21637 // regardless of its normal CC. Therefore we change the parameter
21638 // types to match the types of the arguments.
21639 //
21640 // This is a hack, but it is far superior to moving the
21641 // corresponding target-specific code from IR-gen to Sema/AST.
21642
21643 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21644 SmallVector<QualType, 8> ArgTypes;
21645 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21646 ArgTypes.reserve(E->getNumArgs());
21647 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21648 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21649 }
21650 ParamTypes = ArgTypes;
21651 }
21652 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21653 Proto->getExtProtoInfo());
21654 } else {
21655 DestType = S.Context.getFunctionNoProtoType(DestType,
21656 FnType->getExtInfo());
21657 }
21658
21659 // Rebuild the appropriate pointer-to-function type.
21660 switch (Kind) {
21661 case FK_MemberFunction:
21662 // Nothing to do.
21663 break;
21664
21665 case FK_FunctionPointer:
21666 DestType = S.Context.getPointerType(DestType);
21667 break;
21668
21669 case FK_BlockPointer:
21670 DestType = S.Context.getBlockPointerType(DestType);
21671 break;
21672 }
21673
21674 // Finally, we can recurse.
21675 ExprResult CalleeResult = Visit(CalleeExpr);
21676 if (!CalleeResult.isUsable()) return ExprError();
21677 E->setCallee(CalleeResult.get());
21678
21679 // Bind a temporary if necessary.
21680 return S.MaybeBindToTemporary(E);
21681}
21682
21683ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21684 // Verify that this is a legal result type of a call.
21685 if (DestType->isArrayType() || DestType->isFunctionType()) {
21686 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21687 << DestType->isFunctionType() << DestType;
21688 return ExprError();
21689 }
21690
21691 // Rewrite the method result type if available.
21692 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21693 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21694 Method->setReturnType(DestType);
21695 }
21696
21697 // Change the type of the message.
21698 E->setType(DestType.getNonReferenceType());
21700
21701 return S.MaybeBindToTemporary(E);
21702}
21703
21704ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21705 // The only case we should ever see here is a function-to-pointer decay.
21706 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21707 assert(E->isPRValue());
21708 assert(E->getObjectKind() == OK_Ordinary);
21709
21710 E->setType(DestType);
21711
21712 // Rebuild the sub-expression as the pointee (function) type.
21713 DestType = DestType->castAs<PointerType>()->getPointeeType();
21714
21715 ExprResult Result = Visit(E->getSubExpr());
21716 if (!Result.isUsable()) return ExprError();
21717
21718 E->setSubExpr(Result.get());
21719 return E;
21720 } else if (E->getCastKind() == CK_LValueToRValue) {
21721 assert(E->isPRValue());
21722 assert(E->getObjectKind() == OK_Ordinary);
21723
21724 assert(isa<BlockPointerType>(E->getType()));
21725
21726 E->setType(DestType);
21727
21728 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21729 DestType = S.Context.getLValueReferenceType(DestType);
21730
21731 ExprResult Result = Visit(E->getSubExpr());
21732 if (!Result.isUsable()) return ExprError();
21733
21734 E->setSubExpr(Result.get());
21735 return E;
21736 } else {
21737 llvm_unreachable("Unhandled cast type!");
21738 }
21739}
21740
21741ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21742 ExprValueKind ValueKind = VK_LValue;
21743 QualType Type = DestType;
21744
21745 // We know how to make this work for certain kinds of decls:
21746
21747 // - functions
21748 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21749 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21750 DestType = Ptr->getPointeeType();
21751 ExprResult Result = resolveDecl(E, VD);
21752 if (Result.isInvalid()) return ExprError();
21753 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21754 VK_PRValue);
21755 }
21756
21757 if (!Type->isFunctionType()) {
21758 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21759 << VD << E->getSourceRange();
21760 return ExprError();
21761 }
21762 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21763 // We must match the FunctionDecl's type to the hack introduced in
21764 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21765 // type. See the lengthy commentary in that routine.
21766 QualType FDT = FD->getType();
21767 const FunctionType *FnType = FDT->castAs<FunctionType>();
21768 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21769 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21770 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21771 SourceLocation Loc = FD->getLocation();
21772 FunctionDecl *NewFD = FunctionDecl::Create(
21773 S.Context, FD->getDeclContext(), Loc, Loc,
21774 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21776 false /*isInlineSpecified*/, FD->hasPrototype(),
21777 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21778
21779 if (FD->getQualifier())
21780 NewFD->setQualifierInfo(FD->getQualifierLoc());
21781
21782 SmallVector<ParmVarDecl*, 16> Params;
21783 for (const auto &AI : FT->param_types()) {
21784 ParmVarDecl *Param =
21785 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21786 Param->setScopeInfo(0, Params.size());
21787 Params.push_back(Param);
21788 }
21789 NewFD->setParams(Params);
21790 DRE->setDecl(NewFD);
21791 VD = DRE->getDecl();
21792 }
21793 }
21794
21795 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21796 if (MD->isInstance()) {
21797 ValueKind = VK_PRValue;
21799 }
21800
21801 // Function references aren't l-values in C.
21802 if (!S.getLangOpts().CPlusPlus)
21803 ValueKind = VK_PRValue;
21804
21805 // - variables
21806 } else if (isa<VarDecl>(VD)) {
21807 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21808 Type = RefTy->getPointeeType();
21809 } else if (Type->isFunctionType()) {
21810 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21811 << VD << E->getSourceRange();
21812 return ExprError();
21813 }
21814
21815 // - nothing else
21816 } else {
21817 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21818 << VD << E->getSourceRange();
21819 return ExprError();
21820 }
21821
21822 // Modifying the declaration like this is friendly to IR-gen but
21823 // also really dangerous.
21824 VD->setType(DestType);
21825 E->setType(Type);
21826 E->setValueKind(ValueKind);
21827 return E;
21828}
21829
21832 ExprValueKind &VK, CXXCastPath &Path) {
21833 // The type we're casting to must be either void or complete.
21834 if (!CastType->isVoidType() &&
21836 diag::err_typecheck_cast_to_incomplete))
21837 return ExprError();
21838
21839 // Rewrite the casted expression from scratch.
21840 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21841 if (!result.isUsable()) return ExprError();
21842
21843 CastExpr = result.get();
21845 CastKind = CK_NoOp;
21846
21847 return CastExpr;
21848}
21849
21851 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21852}
21853
21855 Expr *arg, QualType &paramType) {
21856 // If the syntactic form of the argument is not an explicit cast of
21857 // any sort, just do default argument promotion.
21858 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21859 if (!castArg) {
21861 if (result.isInvalid()) return ExprError();
21862 paramType = result.get()->getType();
21863 return result;
21864 }
21865
21866 // Otherwise, use the type that was written in the explicit cast.
21867 assert(!arg->hasPlaceholderType());
21868 paramType = castArg->getTypeAsWritten();
21869
21870 // Copy-initialize a parameter of that type.
21871 InitializedEntity entity =
21873 /*consumed*/ false);
21874 return PerformCopyInitialization(entity, callLoc, arg);
21875}
21876
21878 Expr *orig = E;
21879 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21880 while (true) {
21881 E = E->IgnoreParenImpCasts();
21882 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21883 E = call->getCallee();
21884 diagID = diag::err_uncasted_call_of_unknown_any;
21885 } else {
21886 break;
21887 }
21888 }
21889
21890 SourceLocation loc;
21891 NamedDecl *d;
21892 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21893 loc = ref->getLocation();
21894 d = ref->getDecl();
21895 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21896 loc = mem->getMemberLoc();
21897 d = mem->getMemberDecl();
21898 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21899 diagID = diag::err_uncasted_call_of_unknown_any;
21900 loc = msg->getSelectorStartLoc();
21901 d = msg->getMethodDecl();
21902 if (!d) {
21903 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21904 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21905 << orig->getSourceRange();
21906 return ExprError();
21907 }
21908 } else {
21909 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21910 << E->getSourceRange();
21911 return ExprError();
21912 }
21913
21914 S.Diag(loc, diagID) << d << orig->getSourceRange();
21915
21916 // Never recoverable.
21917 return ExprError();
21918}
21919
21921 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21922 if (!placeholderType) return E;
21923
21924 switch (placeholderType->getKind()) {
21925 case BuiltinType::UnresolvedTemplate: {
21926 auto *ULE = cast<UnresolvedLookupExpr>(E->IgnoreParens());
21927 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21928 // There's only one FoundDecl for UnresolvedTemplate type. See
21929 // BuildTemplateIdExpr.
21930 NamedDecl *Temp = *ULE->decls_begin();
21931 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
21932
21933 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21934 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21935 // as it models only the unqualified-id case, where this case can clearly be
21936 // qualified. Thus we can't just qualify an assumed template.
21937 TemplateName TN;
21938 if (auto *TD = dyn_cast<TemplateDecl>(Temp))
21939 TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),
21940 TemplateName(TD));
21941 else
21942 TN = Context.getAssumedTemplateName(NameInfo.getName());
21943
21944 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21945 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21946 Diag(Temp->getLocation(), diag::note_referenced_type_template)
21947 << IsTypeAliasTemplateDecl;
21948
21949 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21950 bool HasAnyDependentTA = false;
21951 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21952 HasAnyDependentTA |= Arg.getArgument().isDependent();
21953 TAL.addArgument(Arg);
21954 }
21955
21956 QualType TST;
21957 {
21958 SFINAETrap Trap(*this);
21959 TST = CheckTemplateIdType(
21960 ElaboratedTypeKeyword::None, TN, NameInfo.getBeginLoc(), TAL,
21961 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21962 }
21963 if (TST.isNull())
21964 TST = Context.getTemplateSpecializationType(
21965 ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),
21966 /*CanonicalArgs=*/{},
21967 HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21968 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},
21969 TST);
21970 }
21971
21972 // Overloaded expressions.
21973 case BuiltinType::Overload: {
21974 // Try to resolve a single function template specialization.
21975 // This is obligatory.
21976 ExprResult Result = E;
21978 return Result;
21979
21980 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21981 // leaves Result unchanged on failure.
21982 Result = E;
21984 return Result;
21985
21986 // If that failed, try to recover with a call.
21987 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21988 /*complain*/ true);
21989 return Result;
21990 }
21991
21992 // Bound member functions.
21993 case BuiltinType::BoundMember: {
21994 ExprResult result = E;
21995 const Expr *BME = E->IgnoreParens();
21996 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21997 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21999 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
22000 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
22001 if (ME->getMemberNameInfo().getName().getNameKind() ==
22003 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
22004 }
22005 tryToRecoverWithCall(result, PD,
22006 /*complain*/ true);
22007 return result;
22008 }
22009
22010 // ARC unbridged casts.
22011 case BuiltinType::ARCUnbridgedCast: {
22012 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
22013 ObjC().diagnoseARCUnbridgedCast(realCast);
22014 return realCast;
22015 }
22016
22017 // Expressions of unknown type.
22018 case BuiltinType::UnknownAny:
22019 return diagnoseUnknownAnyExpr(*this, E);
22020
22021 // Pseudo-objects.
22022 case BuiltinType::PseudoObject:
22023 return PseudoObject().checkRValue(E);
22024
22025 case BuiltinType::BuiltinFn: {
22026 // Accept __noop without parens by implicitly converting it to a call expr.
22027 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
22028 if (DRE) {
22029 auto *FD = cast<FunctionDecl>(DRE->getDecl());
22030 unsigned BuiltinID = FD->getBuiltinID();
22031 if (BuiltinID == Builtin::BI__noop) {
22032 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
22033 CK_BuiltinFnToFnPtr)
22034 .get();
22035 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
22038 }
22039
22040 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
22041 // Any use of these other than a direct call is ill-formed as of C++20,
22042 // because they are not addressable functions. In earlier language
22043 // modes, warn and force an instantiation of the real body.
22044 Diag(E->getBeginLoc(),
22046 ? diag::err_use_of_unaddressable_function
22047 : diag::warn_cxx20_compat_use_of_unaddressable_function);
22048 if (FD->isImplicitlyInstantiable()) {
22049 // Require a definition here because a normal attempt at
22050 // instantiation for a builtin will be ignored, and we won't try
22051 // again later. We assume that the definition of the template
22052 // precedes this use.
22054 /*Recursive=*/false,
22055 /*DefinitionRequired=*/true,
22056 /*AtEndOfTU=*/false);
22057 }
22058 // Produce a properly-typed reference to the function.
22059 CXXScopeSpec SS;
22060 SS.Adopt(DRE->getQualifierLoc());
22061 TemplateArgumentListInfo TemplateArgs;
22062 DRE->copyTemplateArgumentsInto(TemplateArgs);
22063 return BuildDeclRefExpr(
22064 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
22065 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
22066 DRE->getTemplateKeywordLoc(),
22067 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
22068 }
22069 }
22070
22071 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
22072 return ExprError();
22073 }
22074
22075 case BuiltinType::IncompleteMatrixIdx: {
22076 auto *MS = cast<MatrixSubscriptExpr>(E->IgnoreParens());
22077 // At this point, we know there was no second [] to complete the operator.
22078 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
22079 if (getLangOpts().HLSL) {
22081 MS->getBase(), MS->getRowIdx(), E->getExprLoc());
22082 }
22083 Diag(MS->getRowIdx()->getBeginLoc(), diag::err_matrix_incomplete_index);
22084 return ExprError();
22085 }
22086
22087 // Expressions of unknown type.
22088 case BuiltinType::ArraySection:
22089 // If we've already diagnosed something on the array section type, we
22090 // shouldn't need to do any further diagnostic here.
22091 if (!E->containsErrors())
22092 Diag(E->getBeginLoc(), diag::err_array_section_use)
22093 << cast<ArraySectionExpr>(E->IgnoreParens())->isOMPArraySection();
22094 return ExprError();
22095
22096 // Expressions of unknown type.
22097 case BuiltinType::OMPArrayShaping:
22098 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
22099
22100 case BuiltinType::OMPIterator:
22101 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
22102
22103 // Everything else should be impossible.
22104#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
22105 case BuiltinType::Id:
22106#include "clang/Basic/OpenCLImageTypes.def"
22107#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
22108 case BuiltinType::Id:
22109#include "clang/Basic/OpenCLExtensionTypes.def"
22110#define SVE_TYPE(Name, Id, SingletonId) \
22111 case BuiltinType::Id:
22112#include "clang/Basic/AArch64ACLETypes.def"
22113#define PPC_VECTOR_TYPE(Name, Id, Size) \
22114 case BuiltinType::Id:
22115#include "clang/Basic/PPCTypes.def"
22116#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22117#include "clang/Basic/RISCVVTypes.def"
22118#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22119#include "clang/Basic/WebAssemblyReferenceTypes.def"
22120#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
22121#include "clang/Basic/AMDGPUTypes.def"
22122#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22123#include "clang/Basic/HLSLIntangibleTypes.def"
22124#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22125#include "clang/Basic/SPIRVTypes.def"
22126#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
22127#define PLACEHOLDER_TYPE(Id, SingletonId)
22128#include "clang/AST/BuiltinTypes.def"
22129 break;
22130 }
22131
22132 llvm_unreachable("invalid placeholder type!");
22133}
22134
22136 if (E->isTypeDependent())
22137 return true;
22139 return E->getType()->isIntegralOrEnumerationType();
22140 return false;
22141}
22142
22144 ArrayRef<Expr *> SubExprs, QualType T) {
22145 if (!Context.getLangOpts().RecoveryAST)
22146 return ExprError();
22147
22148 if (isSFINAEContext())
22149 return ExprError();
22150
22151 if (T.isNull() || T->isUndeducedType() ||
22152 !Context.getLangOpts().RecoveryASTType)
22153 // We don't know the concrete type, fallback to dependent type.
22154 T = Context.DependentTy;
22155
22156 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
22157}
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
static bool isObjCPointer(const MemRegion *R)
Defines enumerations for traits support.
Defines enum values for all the target-independent builtin functions.
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
Token Tok
The Token.
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
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 QualType getUnderlyingType(const SubRegion *R)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis for CUDA constructs.
CastType
Definition SemaCast.cpp:50
static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy, SourceLocation OpLoc)
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, ArrayRef< Expr * > Args, SourceLocation LitEndLoc)
BuildCookedLiteralOperatorCall - A user-defined literal was found.
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.
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...
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
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...
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
static Decl * getPredefinedExprDecl(Sema &S, DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
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...
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, bool AcceptInvalid)
Diagnoses obvious problems with the use of the given declaration as an expression.
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
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",...
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.
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn)
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
@ NCCK_Block
@ NCCK_None
@ NCCK_Lambda
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...
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
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,...
static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
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.
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, SourceLocation OpLoc, bool IsBuiltin)
DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
diagnoseStringPlusInt - Emit a warning when adding an integer to a string literal.
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
static bool checkForArray(const Expr *E)
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
static bool areTypesCompatibleForGeneric(ASTContext &Ctx, QualType T, QualType U)
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
static bool MayBeFunctionType(const ASTContext &Context, const Expr *E)
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.
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
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...
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, BinaryOperatorKind Opc, QualType ResultTy, ExprValueKind VK, ExprObjectKind OK, bool IsCompAssign, SourceLocation OpLoc, FPOptionsOverride FPFeatures)
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
@ ConstUnknown
@ ConstVariable
@ NestedConstMember
@ ConstMember
@ ConstFunction
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.
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.
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS, Expr *RHS, SourceLocation Loc, ArithConvKind ACK)
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...
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...
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
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.
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
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...
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition SemaExpr.cpp:150
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, const TryCaptureKind Kind, SourceLocation EllipsisLoc, const bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the lambda.
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 ...
static void MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Emit a warning when adding a char literal to a string.
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
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:166
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...
static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Returns false if the pointers are converted to a composite type, true otherwise.
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle conversions with GCC complex int extension.
static AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, SourceLocation Loc)
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
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...
static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc, const ExprResult &LHS, const ExprResult &RHS, BinaryOperatorKind Opc)
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition SemaExpr.cpp:565
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
static OdrUseContext isOdrUseContext(Sema &SemaRef)
Are we within a context in which references to resolved functions or to variables result in odr-use?
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...
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
static void CheckSufficientAllocSize(Sema &S, QualType DestType, const Expr *E)
Check that a call to alloc_size function specifies sufficient space for the destination type.
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
static QualType handleOverflowBehaviorTypeConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
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...
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
OriginalExprKind
@ OEK_Variable
@ OEK_LValue
@ OEK_Member
static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S, bool Invalid)
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
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.
static FieldDecl * FindFieldDeclInstantiationPattern(const ASTContext &Ctx, FieldDecl *Field)
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
static bool IsReadonlyMessage(Expr *E, Sema &S)
static std::optional< bool > isTautologicalBoundsCheck(Sema &S, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opc)
Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a pointer and size is an unsigne...
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.
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the captured region.
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
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,...
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
static bool IsArithmeticOp(BinaryOperatorKind Opc)
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...
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, SourceLocation OpLoc)
Check if a bitwise-& is performed on an Objective-C pointer.
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition SemaExpr.cpp:590
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn)
Given a function expression of unknown-any type, try to rebuild it to have a function type.
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, ExprResult &IntExpr, QualType FloatTy, QualType IntTy, bool ConvertFloat, bool ConvertInt)
Handle arithmetic conversion from integer to float.
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
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...
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind)
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition SemaExpr.cpp:112
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, QualType RHSTy)
handleFixedPointConversion - Fixed point operations between fixed point types and integers or other f...
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, QualType ResultTy, Expr *E0, Expr *E1=nullptr)
Returns true if conversion between vectors of halfs and vectors of floats is needed.
static bool isObjCObjectLiteral(ExprResult &E)
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
static QualType checkConditionalBlockPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both block pointers.
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
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...
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
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 ...
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
static bool isScopedEnumerationType(QualType T)
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Check the validity of a binary arithmetic operation w.r.t.
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis routines for OpenCL.
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.
C Language Family Type Representation.
@ Open
The standard open() call: int open(const char *path, int oflag, ...);.
a trap message and trap category.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
APSInt & getInt()
Definition APValue.h:511
bool hasValue() const
Definition APValue.h:486
bool isInt() const
Definition APValue.h:488
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:993
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
unsigned getIntWidth(QualType T) const
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.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:812
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) 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 getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
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
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
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
IdentifierTable & Idents
Definition ASTContext.h:808
const LangOptions & getLangOpts() const
Definition ASTContext.h:965
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition ASTContext.h:930
bool typesAreBlockPointerCompatible(QualType, QualType)
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::SetVector< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
llvm::SetVector< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType getCorrespondingSaturatedType(QualType Ty) const
CanQualType BoundMemberTy
CanQualType CharTy
CanQualType IntTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
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.
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnknownAnyTy
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
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.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
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
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:927
QualType getOverflowBehaviorType(const OverflowBehaviorAttr *Attr, QualType Wrapped) const
std::optional< CharUnits > getTypeSizeInCharsIfKnown(QualType Ty) const
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
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 ...
unsigned getTargetAddressSpace(LangAS AS) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
CanQualType HalfTy
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition Expr.h:4556
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2727
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:2782
Wrapper for source info for arrays.
Definition TypeLoc.h:1808
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3833
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3847
QualType getElementType() const
Definition TypeBase.h:3845
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition Expr.h:6745
Attr - This represents one attribute.
Definition Attr.h:46
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4459
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
Expr * getLHS() const
Definition Expr.h:4094
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4138
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2189
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4144
StringRef getOpcodeStr() const
Definition Expr.h:4110
bool isRelationalOp() const
Definition Expr.h:4139
SourceLocation getOperatorLoc() const
Definition Expr.h:4086
bool isMultiplicativeOp() const
Definition Expr.h:4129
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2142
bool isShiftOp() const
Definition Expr.h:4133
Expr * getRHS() const
Definition Expr.h:4096
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:5108
bool isBitwiseOp() const
Definition Expr.h:4136
bool isAdditiveOp() const
Definition Expr.h:4131
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4180
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4185
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:2214
Opcode getOpcode() const
Definition Expr.h:4089
bool isAssignmentOp() const
Definition Expr.h:4183
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2151
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4141
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4135
BinaryOperatorKind Opcode
Definition Expr.h:4049
A binding in a decomposition declaration.
Definition DeclCXX.h:4206
A class which contains all the information about a particular captured value.
Definition Decl.h:4722
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4716
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.cpp:5446
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition Decl.h:4798
void setBlockMissingReturnType(bool val=true)
Definition Decl.h:4855
void setIsVariadic(bool value)
Definition Decl.h:4792
SourceLocation getCaretLocation() const
Definition Decl.h:4789
void setBody(CompoundStmt *B)
Definition Decl.h:4796
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:4802
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition Decl.cpp:5457
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5650
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6684
Pointer to a block type.
Definition TypeBase.h:3653
This class is used for builtin types like 'int'.
Definition TypeBase.h:3238
bool isSVEBool() const
Definition TypeBase.h:3318
Kind getKind() const
Definition TypeBase.h:3289
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:1966
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...
const RecordType * getDetectedVirtual() const
The virtual base discovered on the path (if we are merely detecting virtuals).
CXXBasePath & front()
Represents a call to a C++ constructor.
Definition ExprCXX.h:1551
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1614
Represents a C++ constructor within a class.
Definition DeclCXX.h:2633
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2968
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition DeclCXX.cpp:3297
Represents a C++ base or member initializer.
Definition DeclCXX.h:2398
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1273
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition ExprCXX.cpp:1046
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1380
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:1100
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1112
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:1557
Represents a C++ destructor within a class.
Definition DeclCXX.h:2898
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
bool isVirtual() const
Definition DeclCXX.h:2200
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2284
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:2524
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:84
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition ExprCXX.h:155
SourceRange getSourceRange() const
Definition ExprCXX.h:167
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition ExprCXX.cpp:1997
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition ExprCXX.h:2748
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
Definition DeclCXX.h:1230
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition DeclCXX.cpp:606
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1023
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition DeclCXX.cpp:2087
bool hasDefinition() const
Definition DeclCXX.h:561
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
static CXXReflectExpr * Create(ASTContext &C, SourceLocation OperatorLoc, TypeSourceInfo *TL)
Definition ExprCXX.cpp:1942
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:183
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
void MakeTrivial(ASTContext &Context, NestedNameSpecifier Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition DeclSpec.cpp:97
SourceRange getRange() const
Definition DeclSpec.h:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
Represents the this expression in C++.
Definition ExprCXX.h:1157
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3166
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:1523
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3132
Expr * getCallee()
Definition Expr.h:3096
void computeDependence()
Compute and set dependence bits.
Definition Expr.h:3172
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3140
void setCallee(Expr *F)
Definition Expr.h:3098
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:3682
CastKind getCastKind() const
Definition Expr.h:3726
const char * getCastKindName() const
Definition Expr.h:3730
void setSubExpr(Expr *E)
Definition Expr.h:3734
Expr * getSubExpr()
Definition Expr.h:3732
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Represents a byte-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
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
unsigned getValue() const
Definition Expr.h:1635
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4854
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3352
QualType getElementType() const
Definition TypeBase.h:3362
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:5130
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3611
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1749
bool body_empty() const
Definition Stmt.h:1793
Stmt * body_back()
Definition Stmt.h:1817
ConditionalOperator - The ?
Definition Expr.h:4397
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3871
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3927
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3947
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1088
static ConstantResultStorageKind getStorageKind(const APValue &Value)
Definition Expr.cpp:308
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition Expr.cpp:384
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1138
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
bool isImmediateInvocation() const
Definition Expr.h:1160
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4498
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4517
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4514
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
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:1505
Represents a pointer type decayed from an array or function type.
Definition TypeBase.h:3636
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2259
bool isRequiresExprBody() const
Definition DeclBase.h:2211
DeclContextLookupResult lookup_result
Definition DeclBase.h:2607
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isRecord() const
Definition DeclBase.h:2206
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
bool isFunctionOrMethod() const
Definition DeclBase.h:2178
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
DeclContext * getEnclosingNonExpansionStatementContext()
Retrieve the innermost enclosing context that doesn't belong to an expansion statement.
bool isExpansionStmt() const
Definition DeclBase.h:2215
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition Expr.h:1387
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition Expr.h:1431
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1377
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1480
void setDecl(ValueDecl *NewD)
Definition Expr.cpp:550
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition Expr.h:1435
DeclarationNameInfo getNameInfo() const
Definition Expr.h:1348
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition Expr.h:1403
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:494
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition Expr.h:1365
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1369
ValueDecl * getDecl()
Definition Expr.h:1344
SourceLocation getBeginLoc() const
Definition Expr.h:1355
SourceLocation getLocation() const
Definition Expr.h:1352
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:581
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition DeclBase.cpp:779
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:594
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition DeclBase.h:1087
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
void setReferenced(bool R=true)
Definition DeclBase.h:631
DeclContext * getDeclContext()
Definition DeclBase.h:456
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:995
Kind getKind() const
Definition DeclBase.h:450
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.
NameKind getNameKind() const
Determine what kind of name this is.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:2017
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:2001
DeclaratorContext getContext() const
Definition DeclSpec.h:2173
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2184
bool isInvalidType() const
Definition DeclSpec.h:2815
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2431
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:549
Designation - Represent a full designation, which is a sequence of designators.
Definition Designator.h:221
const Designator & getDesignator(unsigned Idx) const
Definition Designator.h:232
unsigned getNumDesignators() const
Definition Designator.h:231
Designator - A designator in a C99 designated initializer.
Definition Designator.h:38
bool isArrayDesignator() const
Definition Designator.h:108
SourceLocation getEndLoc() const
Returns the end location of this designator.
Definition Designator.h:147
bool isArrayRangeDesignator() const
Definition Designator.h:109
bool isFieldDesignator() const
Definition Designator.h:107
const IdentifierInfo * getFieldDecl() const
Definition Designator.h:123
SourceLocation getBeginLoc() const
Returns the start location of this designator.
Definition Designator.h:140
Expr * getArrayIndex() const
Definition Designator.h:162
A little helper class used to produce diagnostics.
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:972
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:741
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
Represents a reference to emded data.
Definition Expr.h:5141
RAII object that enters a new expression evaluation context.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4228
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3934
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3961
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1471
This represents one expression.
Definition Expr.h:112
LValueClassification
Definition Expr.h:289
@ LV_ArrayTemporary
Definition Expr.h:300
@ LV_ClassTemporary
Definition Expr.h:299
@ LV_MemberFunction
Definition Expr.h:297
@ LV_IncompleteVoidType
Definition Expr.h:292
@ LV_Valid
Definition Expr.h:290
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 isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:287
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:3128
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...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
Definition Expr.h:681
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition Expr.cpp:3057
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:3106
void setType(QualType t)
Definition Expr.h:145
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:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition Expr.h:241
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3101
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3089
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition Expr.cpp:3110
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3097
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3350
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:837
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:833
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:841
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
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:3700
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:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:808
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:817
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:820
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition Expr.h:823
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:810
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:4081
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:272
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:464
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
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:4333
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:467
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
isModifiableLvalueResult
Definition Expr.h:305
@ MLV_DuplicateVectorComponents
Definition Expr.h:309
@ MLV_LValueCast
Definition Expr.h:312
@ MLV_InvalidMessageExpression
Definition Expr.h:321
@ MLV_DuplicateMatrixComponents
Definition Expr.h:310
@ MLV_ConstQualifiedField
Definition Expr.h:315
@ MLV_InvalidExpression
Definition Expr.h:311
@ MLV_IncompleteType
Definition Expr.h:313
@ MLV_Valid
Definition Expr.h:306
@ MLV_ConstQualified
Definition Expr.h:314
@ MLV_NoSetterProperty
Definition Expr.h:318
@ MLV_ArrayTemporary
Definition Expr.h:323
@ MLV_SubObjCPropertySetting
Definition Expr.h:320
@ MLV_ConstAddrSpace
Definition Expr.h:316
@ MLV_MemberFunction
Definition Expr.h:319
@ MLV_NotObjectType
Definition Expr.h:307
@ MLV_ArrayType
Definition Expr.h:317
@ MLV_ClassTemporary
Definition Expr.h:322
@ MLV_IncompleteVoidType
Definition Expr.h:308
QualType getType() const
Definition Expr.h:144
bool isOrdinaryOrBitFieldObject() const
Definition Expr.h:458
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:437
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:138
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6622
ExtVectorType - Extended vector type.
Definition TypeBase.h:4378
Represents difference between two FPOptions values.
bool isFPConstrained() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3204
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3307
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3384
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3440
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:81
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:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
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:105
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:1003
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1082
const Expr * getSubExpr() const
Definition Expr.h:1068
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:2029
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, const AssociatedConstraint &TrailingRequiresClause={})
Definition Decl.h:2225
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2837
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3827
bool isImmediateFunction() const
Definition Decl.cpp:3320
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4004
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3742
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3845
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2961
QualType getReturnType() const
Definition Decl.h:2885
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2814
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2479
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3598
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isImmediateEscalating() const
Definition Decl.cpp:3291
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2973
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4110
bool isConsteval() const
Definition Decl.h:2518
size_t param_size() const
Definition Decl.h:2830
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3179
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition Decl.cpp:4020
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition Decl.h:2921
Represents a reference to a function parameter pack, init-capture pack, or binding pack that has been...
Definition ExprCXX.h:4840
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4869
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5418
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5922
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5725
bool isParamConsumed(unsigned I) const
Definition TypeBase.h:5936
unsigned getNumParams() const
Definition TypeBase.h:5696
QualType getParamType(unsigned i) const
Definition TypeBase.h:5698
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5822
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5707
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5703
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5858
Declaration of a template function.
unsigned getNumParams() const
Definition TypeLoc.h:1747
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1753
SourceLocation getLocalRangeEnd() const
Definition TypeLoc.h:1699
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1756
SourceLocation getLocalRangeBegin() const
Definition TypeLoc.h:1691
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4725
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4796
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4653
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4614
ExtInfo getExtInfo() const
Definition TypeBase.h:4970
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:4962
bool getCFIUncheckedCalleeAttr() const
Determine whether this is a function prototype that includes the cfi_unchecked_callee attribute.
Definition Type.cpp:3706
QualType getReturnType() const
Definition TypeBase.h:4954
bool getCmseNSCallAttr() const
Definition TypeBase.h:4968
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4982
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4929
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:4729
One of these records is kept for each identifier that is lexed.
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:1737
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3859
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2081
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:622
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3511
Describes an C or C++ initializer list.
Definition Expr.h:5314
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.
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.
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:981
Represents the declaration of a label.
Definition Decl.h:524
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1971
CXXMethodDecl * getCallOperator() const
Retrieve the function call operator associated with this lambda expression.
Definition ExprCXX.cpp:1411
FPEvalMethodKind
Possible float expression evaluation method choices.
@ FEM_Extended
Use extended type for fp arithmetic.
@ FEM_Double
Use the type double for fp arithmetic.
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
@ FEM_Source
Use the declared type for fp arithmetic.
@ CX_Promoted
Implementation of complex division using algebraic formulas at higher precision.
@ 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...
clang::ObjCRuntime ObjCRuntime
bool isSignedOverflowDefined() const
bool allowArrayReturnTypes() const
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
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:1075
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:407
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:320
Represents the results of name lookup.
Definition Lookup.h:147
DeclClass * getAsSingle() const
Definition Lookup.h:558
A global _GUID constant.
Definition DeclCXX.h:4424
MS property subscript expression.
Definition ExprCXX.h:1009
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...
MatrixSingleSubscriptExpr - Matrix single subscript expression for the MatrixType extension when you ...
Definition Expr.h:2801
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition Expr.h:2871
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4448
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4462
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3559
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
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:1758
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3588
Expr * getBase() const
Definition Expr.h:3447
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1802
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1683
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
bool isExternallyVisible() const
Definition Decl.h:433
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:397
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier, or null.
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:1160
bool hasDefinition() const
Determine whether this class has been defined.
Definition DeclObjC.h:1534
ivar_iterator ivar_begin() const
Definition DeclObjC.h:1459
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:349
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8063
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition ExprObjC.h:1531
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1958
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:582
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprObjC.h:628
SourceLocation getLocation() const
Definition ExprObjC.h:625
SourceLocation getOpLoc() const
Definition ExprObjC.h:633
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:612
bool isArrow() const
Definition ExprObjC.h:620
SourceLocation getEndLoc() const LLVM_READONLY
Definition ExprObjC.h:631
const Expr * getBase() const
Definition ExprObjC.h:616
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:973
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1397
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
ImplicitParamDecl * getSelfDecl() const
Definition DeclObjC.h:421
bool isClassMethod() const
Definition DeclObjC.h:437
Represents a pointer to an Objective C object.
Definition TypeBase.h:8119
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1889
qual_range quals() const
Definition TypeBase.h:8238
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:734
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2090
bool allowsSizeofAlignof() const
Does this runtime allow sizeof or alignof on object types?
bool allowsPointerArithmetic() const
Does this runtime allow pointer arithmetic on objects?
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr * > exprs, SourceLocation RParenLoc)
Definition Expr.cpp:1661
Helper class for OffsetOfExpr.
Definition Expr.h:2427
void * getAsOpaquePtr() const
Definition Ownership.h:91
static OpaquePtr getFromOpaquePtr(void *P)
Definition Ownership.h:92
PtrTy get() const
Definition Ownership.h:81
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1184
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
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:3131
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3192
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2188
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2209
const Expr * getSubExpr() const
Definition Expr.h:2205
bool isProducedByFoldExpansion() const
Definition Expr.h:2230
Expr * getExpr(unsigned Init)
Definition Expr.h:6124
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:4980
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition Expr.h:6122
SourceLocation getLParenLoc() const
Definition Expr.h:6141
SourceLocation getRParenLoc() const
Definition Expr.h:6142
Represents a parameter to a function.
Definition Decl.h:1819