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 Expr *E0, Expr *E1 = nullptr) {
15508 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType)
15509 return false;
15510
15511 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15512 QualType Ty = E->IgnoreImplicit()->getType();
15513
15514 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15515 // to vectors of floats. Although the element type of the vectors is __fp16,
15516 // the vectors shouldn't be treated as storage-only types. See the
15517 // discussion here: https://reviews.llvm.org/rG825235c140e7
15518 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15519 if (VT->getVectorKind() == VectorKind::Neon)
15520 return false;
15521 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15522 }
15523 return false;
15524 };
15525
15526 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15527}
15528
15530 BinaryOperatorKind Opc, Expr *LHSExpr,
15531 Expr *RHSExpr, bool ForFoldExpression) {
15532 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15533 // The syntax only allows initializer lists on the RHS of assignment,
15534 // so we don't need to worry about accepting invalid code for
15535 // non-assignment operators.
15536 // C++11 5.17p9:
15537 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15538 // of x = {} is x = T().
15540 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15541 InitializedEntity Entity =
15543 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15544 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15545 if (Init.isInvalid())
15546 return Init;
15547 RHSExpr = Init.get();
15548 }
15549
15550 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15551 QualType ResultTy; // Result type of the binary operator.
15552 // The following two variables are used for compound assignment operators
15553 QualType CompLHSTy; // Type of LHS after promotions for computation
15554 QualType CompResultTy; // Type of computation result
15557 bool ConvertHalfVec = false;
15558
15559 if (!LHS.isUsable() || !RHS.isUsable())
15560 return ExprError();
15561
15562 if (getLangOpts().OpenCL) {
15563 QualType LHSTy = LHSExpr->getType();
15564 QualType RHSTy = RHSExpr->getType();
15565 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15566 // the ATOMIC_VAR_INIT macro.
15567 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15568 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15569 if (BO_Assign == Opc)
15570 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15571 else
15572 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15573 return ExprError();
15574 }
15575
15576 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15577 // only with a builtin functions and therefore should be disallowed here.
15578 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15579 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15580 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15581 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15582 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15583 return ExprError();
15584 }
15585 }
15586
15587 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15588 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15589
15590 switch (Opc) {
15591 case BO_Assign:
15592 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15593 if (getLangOpts().CPlusPlus &&
15594 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15595 VK = LHS.get()->getValueKind();
15596 OK = LHS.get()->getObjectKind();
15597 }
15598 if (!ResultTy.isNull()) {
15599 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15600 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15601
15602 // Avoid copying a block to the heap if the block is assigned to a local
15603 // auto variable that is declared in the same scope as the block. This
15604 // optimization is unsafe if the local variable is declared in an outer
15605 // scope. For example:
15606 //
15607 // BlockTy b;
15608 // {
15609 // b = ^{...};
15610 // }
15611 // // It is unsafe to invoke the block here if it wasn't copied to the
15612 // // heap.
15613 // b();
15614
15615 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15616 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15617 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15618 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15619 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15620
15622 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15624 }
15625 RecordModifiableNonNullParam(*this, LHS.get());
15626 break;
15627 case BO_PtrMemD:
15628 case BO_PtrMemI:
15629 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15630 Opc == BO_PtrMemI);
15631 break;
15632 case BO_Mul:
15633 case BO_Div:
15634 ConvertHalfVec = true;
15635 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15636 break;
15637 case BO_Rem:
15638 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15639 break;
15640 case BO_Add:
15641 ConvertHalfVec = true;
15642 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15643 break;
15644 case BO_Sub:
15645 ConvertHalfVec = true;
15646 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);
15647 break;
15648 case BO_Shl:
15649 case BO_Shr:
15650 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15651 break;
15652 case BO_LE:
15653 case BO_LT:
15654 case BO_GE:
15655 case BO_GT:
15656 ConvertHalfVec = true;
15657 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15658
15659 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
15660 !ForFoldExpression && BI && BI->isComparisonOp())
15661 Diag(OpLoc, diag::warn_consecutive_comparison)
15662 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
15663
15664 break;
15665 case BO_EQ:
15666 case BO_NE:
15667 ConvertHalfVec = true;
15668 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15669 break;
15670 case BO_Cmp:
15671 ConvertHalfVec = true;
15672 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15673 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15674 break;
15675 case BO_And:
15676 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15677 [[fallthrough]];
15678 case BO_Xor:
15679 case BO_Or:
15680 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15681 break;
15682 case BO_LAnd:
15683 case BO_LOr:
15684 ConvertHalfVec = true;
15685 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15686 break;
15687 case BO_MulAssign:
15688 case BO_DivAssign:
15689 ConvertHalfVec = true;
15690 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15691 CompLHSTy = CompResultTy;
15692 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15693 ResultTy =
15694 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15695 break;
15696 case BO_RemAssign:
15697 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
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_AddAssign:
15704 ConvertHalfVec = true;
15705 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15706 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15707 ResultTy =
15708 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15709 break;
15710 case BO_SubAssign:
15711 ConvertHalfVec = true;
15712 CompResultTy = CheckSubtractionOperands(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_ShlAssign:
15718 case BO_ShrAssign:
15719 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15720 CompLHSTy = CompResultTy;
15721 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15722 ResultTy =
15723 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15724 break;
15725 case BO_AndAssign:
15726 case BO_OrAssign: // fallthrough
15727 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15728 [[fallthrough]];
15729 case BO_XorAssign:
15730 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15731 CompLHSTy = CompResultTy;
15732 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15733 ResultTy =
15734 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15735 break;
15736 case BO_Comma:
15737 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15738 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15739 VK = RHS.get()->getValueKind();
15740 OK = RHS.get()->getObjectKind();
15741 }
15742 break;
15743 }
15744 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15745 return ExprError();
15746
15747 // Some of the binary operations require promoting operands of half vector to
15748 // float vectors and truncating the result back to half vector. For now, we do
15749 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15750 // arm64).
15751 assert(
15752 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15753 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15754 "both sides are half vectors or neither sides are");
15755 ConvertHalfVec =
15756 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15757
15758 // Check for array bounds violations for both sides of the BinaryOperator
15759 CheckArrayAccess(LHS.get());
15760 CheckArrayAccess(RHS.get());
15761
15762 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15763 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15764 &Context.Idents.get("object_setClass"),
15766 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15767 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15768 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15770 "object_setClass(")
15771 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15772 ",")
15773 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15774 }
15775 else
15776 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15777 }
15778 else if (const ObjCIvarRefExpr *OIRE =
15779 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15780 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15781
15782 // Opc is not a compound assignment if CompResultTy is null.
15783 if (CompResultTy.isNull()) {
15784 if (ConvertHalfVec)
15785 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15786 OpLoc, CurFPFeatureOverrides());
15787 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15788 VK, OK, OpLoc, CurFPFeatureOverrides());
15789 }
15790
15791 // Handle compound assignments.
15792 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15794 VK = VK_LValue;
15795 OK = LHS.get()->getObjectKind();
15796 }
15797
15798 // The LHS is not converted to the result type for fixed-point compound
15799 // assignment as the common type is computed on demand. Reset the CompLHSTy
15800 // to the LHS type we would have gotten after unary conversions.
15801 if (CompResultTy->isFixedPointType())
15802 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15803
15804 if (ConvertHalfVec)
15805 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15806 OpLoc, CurFPFeatureOverrides());
15807
15809 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15810 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15811}
15812
15813/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15814/// operators are mixed in a way that suggests that the programmer forgot that
15815/// comparison operators have higher precedence. The most typical example of
15816/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15818 SourceLocation OpLoc, Expr *LHSExpr,
15819 Expr *RHSExpr) {
15820 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15821 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15822
15823 // Check that one of the sides is a comparison operator and the other isn't.
15824 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15825 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15826 if (isLeftComp == isRightComp)
15827 return;
15828
15829 // Bitwise operations are sometimes used as eager logical ops.
15830 // Don't diagnose this.
15831 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15832 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15833 if (isLeftBitwise || isRightBitwise)
15834 return;
15835
15836 SourceRange DiagRange = isLeftComp
15837 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15838 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15839 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15840 SourceRange ParensRange =
15841 isLeftComp
15842 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15843 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15844
15845 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15846 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15847 SuggestParentheses(Self, OpLoc,
15848 Self.PDiag(diag::note_precedence_silence) << OpStr,
15849 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15850 SuggestParentheses(Self, OpLoc,
15851 Self.PDiag(diag::note_precedence_bitwise_first)
15853 ParensRange);
15854}
15855
15856/// It accepts a '&&' expr that is inside a '||' one.
15857/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15858/// in parentheses.
15859static void
15861 BinaryOperator *Bop) {
15862 assert(Bop->getOpcode() == BO_LAnd);
15863 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15864 << Bop->getSourceRange() << OpLoc;
15866 Self.PDiag(diag::note_precedence_silence)
15867 << Bop->getOpcodeStr(),
15868 Bop->getSourceRange());
15869}
15870
15871/// Look for '&&' in the left hand of a '||' expr.
15873 Expr *LHSExpr, Expr *RHSExpr) {
15874 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15875 if (Bop->getOpcode() == BO_LAnd) {
15876 // If it's "string_literal && a || b" don't warn since the precedence
15877 // doesn't matter.
15878 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15879 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15880 } else if (Bop->getOpcode() == BO_LOr) {
15881 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15882 // If it's "a || b && string_literal || c" we didn't warn earlier for
15883 // "a || b && string_literal", but warn now.
15884 if (RBop->getOpcode() == BO_LAnd &&
15885 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15886 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15887 }
15888 }
15889 }
15890}
15891
15892/// Look for '&&' in the right hand of a '||' expr.
15894 Expr *LHSExpr, Expr *RHSExpr) {
15895 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15896 if (Bop->getOpcode() == BO_LAnd) {
15897 // If it's "a || b && string_literal" don't warn since the precedence
15898 // doesn't matter.
15899 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15900 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15901 }
15902 }
15903}
15904
15905/// Look for bitwise op in the left or right hand of a bitwise op with
15906/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15907/// the '&' expression in parentheses.
15909 SourceLocation OpLoc, Expr *SubExpr) {
15910 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15911 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15912 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15913 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15914 << Bop->getSourceRange() << OpLoc;
15915 SuggestParentheses(S, Bop->getOperatorLoc(),
15916 S.PDiag(diag::note_precedence_silence)
15917 << Bop->getOpcodeStr(),
15918 Bop->getSourceRange());
15919 }
15920 }
15921}
15922
15924 Expr *SubExpr, StringRef Shift) {
15925 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15926 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15927 StringRef Op = Bop->getOpcodeStr();
15928 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15929 << Bop->getSourceRange() << OpLoc << Shift << Op;
15930 SuggestParentheses(S, Bop->getOperatorLoc(),
15931 S.PDiag(diag::note_precedence_silence) << Op,
15932 Bop->getSourceRange());
15933 }
15934 }
15935}
15936
15938 Expr *LHSExpr, Expr *RHSExpr) {
15939 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15940 if (!OCE)
15941 return;
15942
15943 FunctionDecl *FD = OCE->getDirectCallee();
15944 if (!FD || !FD->isOverloadedOperator())
15945 return;
15946
15948 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15949 return;
15950
15951 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15952 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15953 << (Kind == OO_LessLess);
15955 S.PDiag(diag::note_precedence_silence)
15956 << (Kind == OO_LessLess ? "<<" : ">>"),
15957 OCE->getSourceRange());
15959 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15960 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15961}
15962
15963/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15964/// precedence.
15966 SourceLocation OpLoc, Expr *LHSExpr,
15967 Expr *RHSExpr){
15968 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15970 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15971
15972 // Diagnose "arg1 & arg2 | arg3"
15973 if ((Opc == BO_Or || Opc == BO_Xor) &&
15974 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15975 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15976 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15977 }
15978
15979 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15980 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15981 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15982 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15983 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15984 }
15985
15986 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15987 || Opc == BO_Shr) {
15988 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15989 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15990 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15991 }
15992
15993 // Warn on overloaded shift operators and comparisons, such as:
15994 // cout << 5 == 4;
15996 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15997}
15998
16000 tok::TokenKind Kind,
16001 Expr *LHSExpr, Expr *RHSExpr) {
16002 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
16003 assert(LHSExpr && "ActOnBinOp(): missing left expression");
16004 assert(RHSExpr && "ActOnBinOp(): missing right expression");
16005
16006 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16007 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
16008
16012
16013 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
16014 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
16015
16016 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
16017}
16018
16020 UnresolvedSetImpl &Functions) {
16022 if (OverOp != OO_None && OverOp != OO_Equal)
16023 LookupOverloadedOperatorName(OverOp, S, Functions);
16024
16025 // In C++20 onwards, we may have a second operator to look up.
16026 if (getLangOpts().CPlusPlus20) {
16028 LookupOverloadedOperatorName(ExtraOp, S, Functions);
16029 }
16030}
16031
16032/// Build an overloaded binary operator expression in the given scope.
16035 Expr *LHS, Expr *RHS) {
16036 switch (Opc) {
16037 case BO_Assign:
16038 // In the non-overloaded case, we warn about self-assignment (x = x) for
16039 // both simple assignment and certain compound assignments where algebra
16040 // tells us the operation yields a constant result. When the operator is
16041 // overloaded, we can't do the latter because we don't want to assume that
16042 // those algebraic identities still apply; for example, a path-building
16043 // library might use operator/= to append paths. But it's still reasonable
16044 // to assume that simple assignment is just moving/copying values around
16045 // and so self-assignment is likely a bug.
16046 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
16047 [[fallthrough]];
16048 case BO_DivAssign:
16049 case BO_RemAssign:
16050 case BO_SubAssign:
16051 case BO_AndAssign:
16052 case BO_OrAssign:
16053 case BO_XorAssign:
16054 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
16055 break;
16056 default:
16057 break;
16058 }
16059
16060 // Find all of the overloaded operators visible from this point.
16061 UnresolvedSet<16> Functions;
16062 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
16063
16064 // Build the (potentially-overloaded, potentially-dependent)
16065 // binary operation.
16066 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
16067}
16068
16070 BinaryOperatorKind Opc, Expr *LHSExpr,
16071 Expr *RHSExpr, bool ForFoldExpression) {
16072 if (!LHSExpr || !RHSExpr)
16073 return ExprError();
16074
16075 // We want to end up calling one of SemaPseudoObject::checkAssignment
16076 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16077 // both expressions are overloadable or either is type-dependent),
16078 // or CreateBuiltinBinOp (in any other case). We also want to get
16079 // any placeholder types out of the way.
16080
16081 // Handle pseudo-objects in the LHS.
16082 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16083 // Assignments with a pseudo-object l-value need special analysis.
16084 if (pty->getKind() == BuiltinType::PseudoObject &&
16086 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
16087
16088 // Don't resolve overloads if the other type is overloadable.
16089 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16090 // We can't actually test that if we still have a placeholder,
16091 // though. Fortunately, none of the exceptions we see in that
16092 // code below are valid when the LHS is an overload set. Note
16093 // that an overload set can be dependently-typed, but it never
16094 // instantiates to having an overloadable type.
16095 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16096 if (resolvedRHS.isInvalid()) return ExprError();
16097 RHSExpr = resolvedRHS.get();
16098
16099 if (RHSExpr->isTypeDependent() ||
16100 RHSExpr->getType()->isOverloadableType())
16101 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16102 }
16103
16104 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16105 // template, diagnose the missing 'template' keyword instead of diagnosing
16106 // an invalid use of a bound member function.
16107 //
16108 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16109 // to C++1z [over.over]/1.4, but we already checked for that case above.
16110 if (Opc == BO_LT && inTemplateInstantiation() &&
16111 (pty->getKind() == BuiltinType::BoundMember ||
16112 pty->getKind() == BuiltinType::Overload)) {
16113 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
16114 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16115 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
16116 return isa<FunctionTemplateDecl>(ND);
16117 })) {
16118 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16119 : OE->getNameLoc(),
16120 diag::err_template_kw_missing)
16121 << OE->getName().getAsIdentifierInfo();
16122 return ExprError();
16123 }
16124 }
16125
16126 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
16127 if (LHS.isInvalid()) return ExprError();
16128 LHSExpr = LHS.get();
16129 }
16130
16131 // Handle pseudo-objects in the RHS.
16132 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16133 // An overload in the RHS can potentially be resolved by the type
16134 // being assigned to.
16135 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16136 if (getLangOpts().CPlusPlus &&
16137 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16138 LHSExpr->getType()->isOverloadableType()))
16139 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16140
16141 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16142 ForFoldExpression);
16143 }
16144
16145 // Don't resolve overloads if the other type is overloadable.
16146 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16147 LHSExpr->getType()->isOverloadableType())
16148 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16149
16150 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16151 if (!resolvedRHS.isUsable()) return ExprError();
16152 RHSExpr = resolvedRHS.get();
16153 }
16154
16155 if (getLangOpts().HLSL) {
16156 if (LHSExpr->getType()->isHLSLResourceRecord() ||
16157 LHSExpr->getType()->isHLSLResourceRecordArray()) {
16158 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, OpLoc))
16159 return ExprError();
16160 } else if (RHSExpr->getType()->isHLSLResourceRecord()) {
16161 std::optional<ExprResult> ConvRHS =
16163 if (ConvRHS && Context.hasSameUnqualifiedType(
16164 LHSExpr->getType(), ConvRHS->get()->getType())) {
16165 assert(!ConvRHS->isInvalid());
16166 RHSExpr = ConvRHS->get();
16167 }
16168 }
16169 }
16170
16171 if (getLangOpts().CPlusPlus) {
16172 bool CanOverloadBinOp =
16173 !getLangOpts().HLSL ||
16174 HLSL().canHaveOverloadedBinOp(LHSExpr->getType(), Opc) ||
16175 HLSL().canHaveOverloadedBinOp(RHSExpr->getType(), Opc);
16176 bool TypeDependent =
16177 LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent();
16178 bool Overloadable = LHSExpr->getType()->isOverloadableType() ||
16179 RHSExpr->getType()->isOverloadableType();
16180 if (CanOverloadBinOp && (TypeDependent || Overloadable))
16181 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16182 }
16183
16184 if (getLangOpts().RecoveryAST &&
16185 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16186 assert(!getLangOpts().CPlusPlus);
16187 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16188 "Should only occur in error-recovery path.");
16190 // C [6.15.16] p3:
16191 // An assignment expression has the value of the left operand after the
16192 // assignment, but is not an lvalue.
16194 Context, LHSExpr, RHSExpr, Opc,
16196 OpLoc, CurFPFeatureOverrides());
16197 QualType ResultType;
16198 switch (Opc) {
16199 case BO_Assign:
16200 ResultType = LHSExpr->getType().getUnqualifiedType();
16201 break;
16202 case BO_LT:
16203 case BO_GT:
16204 case BO_LE:
16205 case BO_GE:
16206 case BO_EQ:
16207 case BO_NE:
16208 case BO_LAnd:
16209 case BO_LOr:
16210 // These operators have a fixed result type regardless of operands.
16211 ResultType = Context.IntTy;
16212 break;
16213 case BO_Comma:
16214 ResultType = RHSExpr->getType();
16215 break;
16216 default:
16217 ResultType = Context.DependentTy;
16218 break;
16219 }
16220 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
16221 VK_PRValue, OK_Ordinary, OpLoc,
16223 }
16224
16225 // Build a built-in binary operation.
16226 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16227}
16228
16230 if (T.isNull() || T->isDependentType())
16231 return false;
16232
16233 if (!Ctx.isPromotableIntegerType(T))
16234 return true;
16235
16236 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
16237}
16238
16240 UnaryOperatorKind Opc, Expr *InputExpr,
16241 bool IsAfterAmp) {
16242 ExprResult Input = InputExpr;
16245 QualType resultType;
16246 bool CanOverflow = false;
16247
16248 bool ConvertHalfVec = false;
16249 if (getLangOpts().OpenCL) {
16250 QualType Ty = InputExpr->getType();
16251 // The only legal unary operation for atomics is '&'.
16252 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16253 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16254 // only with a builtin functions and therefore should be disallowed here.
16255 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16256 || Ty->isBlockPointerType())) {
16257 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16258 << InputExpr->getType()
16259 << Input.get()->getSourceRange());
16260 }
16261 }
16262
16263 if (getLangOpts().HLSL && OpLoc.isValid()) {
16264 if (Opc == UO_AddrOf)
16265 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
16266 if (Opc == UO_Deref)
16267 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
16268 }
16269
16270 if (InputExpr->isTypeDependent() &&
16271 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
16272 resultType = Context.DependentTy;
16273 } else {
16274 switch (Opc) {
16275 case UO_PreInc:
16276 case UO_PreDec:
16277 case UO_PostInc:
16278 case UO_PostDec:
16279 resultType =
16280 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
16281 Opc == UO_PreInc || Opc == UO_PostInc,
16282 Opc == UO_PreInc || Opc == UO_PreDec);
16283 CanOverflow = isOverflowingIntegerType(Context, resultType);
16284 break;
16285 case UO_AddrOf:
16286 resultType = CheckAddressOfOperand(Input, OpLoc);
16287 CheckAddressOfNoDeref(InputExpr);
16288 RecordModifiableNonNullParam(*this, InputExpr);
16289 break;
16290 case UO_Deref: {
16292 if (Input.isInvalid())
16293 return ExprError();
16294 resultType =
16295 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
16296 break;
16297 }
16298 case UO_Plus:
16299 case UO_Minus:
16300 CanOverflow = Opc == UO_Minus &&
16302 Input = UsualUnaryConversions(Input.get());
16303 if (Input.isInvalid())
16304 return ExprError();
16305 // Unary plus and minus require promoting an operand of half vector to a
16306 // float vector and truncating the result back to a half vector. For now,
16307 // we do this only when HalfArgsAndReturns is set (that is, when the
16308 // target is arm or arm64).
16309 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
16310
16311 // If the operand is a half vector, promote it to a float vector.
16312 if (ConvertHalfVec)
16313 Input = convertVector(Input.get(), Context.FloatTy, *this);
16314 resultType = Input.get()->getType();
16315 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16316 break;
16317 else if (resultType->isVectorType() &&
16318 // The z vector extensions don't allow + or - with bool vectors.
16319 (!Context.getLangOpts().ZVector ||
16320 resultType->castAs<VectorType>()->getVectorKind() !=
16322 break;
16323 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16324 break;
16325 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16326 Opc == UO_Plus && resultType->isPointerType())
16327 break;
16328
16329 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16330 << resultType << Input.get()->getSourceRange());
16331
16332 case UO_Not: // bitwise complement
16333 Input = UsualUnaryConversions(Input.get());
16334 if (Input.isInvalid())
16335 return ExprError();
16336 resultType = Input.get()->getType();
16337 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16338 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16339 // C99 does not support '~' for complex conjugation.
16340 Diag(OpLoc, diag::ext_integer_complement_complex)
16341 << resultType << Input.get()->getSourceRange();
16342 else if (resultType->hasIntegerRepresentation())
16343 break;
16344 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16345 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16346 // on vector float types.
16347 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16348 if (!T->isIntegerType())
16349 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16350 << resultType << Input.get()->getSourceRange());
16351 } else {
16352 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16353 << resultType << Input.get()->getSourceRange());
16354 }
16355 break;
16356
16357 case UO_LNot: // logical negation
16358 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16360 if (Input.isInvalid())
16361 return ExprError();
16362 resultType = Input.get()->getType();
16363
16364 // Though we still have to promote half FP to float...
16365 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16366 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
16367 .get();
16368 resultType = Context.FloatTy;
16369 }
16370
16371 // WebAsembly tables can't be used in unary expressions.
16372 if (resultType->isPointerType() &&
16374 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16375 << resultType << Input.get()->getSourceRange());
16376 }
16377
16378 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16379 // C99 6.5.3.3p1: ok, fallthrough;
16380 if (Context.getLangOpts().CPlusPlus) {
16381 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16382 // operand contextually converted to bool.
16383 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16384 ScalarTypeToBooleanCastKind(resultType));
16385 } else if (Context.getLangOpts().OpenCL &&
16386 Context.getLangOpts().OpenCLVersion < 120) {
16387 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16388 // operate on scalar float types.
16389 if (!resultType->isIntegerType() && !resultType->isPointerType())
16390 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16391 << resultType << Input.get()->getSourceRange());
16392 }
16393 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16394 !resultType->hasBooleanRepresentation()) {
16395 // HLSL unary logical 'not' behaves like C++, which states that the
16396 // operand is converted to bool and the result is bool, however HLSL
16397 // extends this property to vectors.
16398 const VectorType *VTy = resultType->castAs<VectorType>();
16399 resultType =
16400 Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
16401
16402 Input = ImpCastExprToType(
16403 Input.get(), resultType,
16405 .get();
16406 break;
16407 } else if (resultType->isExtVectorType()) {
16408 if (Context.getLangOpts().OpenCL &&
16409 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16410 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16411 // operate on vector float types.
16412 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16413 if (!T->isIntegerType())
16414 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16415 << resultType << Input.get()->getSourceRange());
16416 }
16417 // Vector logical not returns the signed variant of the operand type.
16418 resultType = GetSignedVectorType(resultType);
16419 break;
16420 } else if (Context.getLangOpts().CPlusPlus &&
16421 resultType->isVectorType()) {
16422 const VectorType *VTy = resultType->castAs<VectorType>();
16423 if (VTy->getVectorKind() != VectorKind::Generic)
16424 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16425 << resultType << Input.get()->getSourceRange());
16426
16427 // Vector logical not returns the signed variant of the operand type.
16428 resultType = GetSignedVectorType(resultType);
16429 break;
16430 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16431 resultType = Context.getLogicalOperationType();
16432 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(InputExpr);
16433 break;
16434 } else {
16435 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16436 << resultType << Input.get()->getSourceRange());
16437 }
16438
16439 // LNot always has type int. C99 6.5.3.3p5.
16440 // In C++, it's bool. C++ 5.3.1p8
16441 resultType = Context.getLogicalOperationType();
16442 break;
16443 case UO_Real:
16444 case UO_Imag:
16445 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16446 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16447 // ordinary complex l-values to ordinary l-values and all other values to
16448 // r-values.
16449 if (Input.isInvalid())
16450 return ExprError();
16451 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16452 if (Input.get()->isGLValue() &&
16453 Input.get()->getObjectKind() == OK_Ordinary)
16454 VK = Input.get()->getValueKind();
16455 } else if (!getLangOpts().CPlusPlus) {
16456 // In C, a volatile scalar is read by __imag. In C++, it is not.
16457 Input = DefaultLvalueConversion(Input.get());
16458 }
16459 break;
16460 case UO_Extension:
16461 resultType = Input.get()->getType();
16462 VK = Input.get()->getValueKind();
16463 OK = Input.get()->getObjectKind();
16464 break;
16465 case UO_Coawait:
16466 // It's unnecessary to represent the pass-through operator co_await in the
16467 // AST; just return the input expression instead.
16468 assert(!Input.get()->getType()->isDependentType() &&
16469 "the co_await expression must be non-dependant before "
16470 "building operator co_await");
16471 return Input;
16472 }
16473 }
16474 if (resultType.isNull() || Input.isInvalid())
16475 return ExprError();
16476
16477 // Check for array bounds violations in the operand of the UnaryOperator,
16478 // except for the '*' and '&' operators that have to be handled specially
16479 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16480 // that are explicitly defined as valid by the standard).
16481 if (Opc != UO_AddrOf && Opc != UO_Deref)
16482 CheckArrayAccess(Input.get());
16483
16484 auto *UO =
16485 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16486 OpLoc, CanOverflow, CurFPFeatureOverrides());
16487
16488 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16489 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16491 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16492
16493 // Convert the result back to a half vector.
16494 if (ConvertHalfVec)
16495 return convertVector(UO, Context.HalfTy, *this);
16496 return UO;
16497}
16498
16500 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16501 if (!DRE->getQualifier())
16502 return false;
16503
16504 ValueDecl *VD = DRE->getDecl();
16505 if (!VD->isCXXClassMember())
16506 return false;
16507
16509 return true;
16510 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16511 return Method->isImplicitObjectMemberFunction();
16512
16513 return false;
16514 }
16515
16516 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16517 if (!ULE->getQualifier())
16518 return false;
16519
16520 for (NamedDecl *D : ULE->decls()) {
16521 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16522 if (Method->isImplicitObjectMemberFunction())
16523 return true;
16524 } else {
16525 // Overload set does not contain methods.
16526 break;
16527 }
16528 }
16529
16530 return false;
16531 }
16532
16533 return false;
16534}
16535
16537 UnaryOperatorKind Opc, Expr *Input,
16538 bool IsAfterAmp) {
16539 // First things first: handle placeholders so that the
16540 // overloaded-operator check considers the right type.
16541 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16542 // Increment and decrement of pseudo-object references.
16543 if (pty->getKind() == BuiltinType::PseudoObject &&
16545 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
16546
16547 // extension is always a builtin operator.
16548 if (Opc == UO_Extension)
16549 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16550
16551 // & gets special logic for several kinds of placeholder.
16552 // The builtin code knows what to do.
16553 if (Opc == UO_AddrOf &&
16554 (pty->getKind() == BuiltinType::Overload ||
16555 pty->getKind() == BuiltinType::UnknownAny ||
16556 pty->getKind() == BuiltinType::BoundMember))
16557 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16558
16559 // Anything else needs to be handled now.
16561 if (Result.isInvalid()) return ExprError();
16562 Input = Result.get();
16563 }
16564
16565 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16567 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16568 // Find all of the overloaded operators visible from this point.
16569 UnresolvedSet<16> Functions;
16571 if (S && OverOp != OO_None)
16572 LookupOverloadedOperatorName(OverOp, S, Functions);
16573
16574 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16575 }
16576
16577 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16578}
16579
16581 Expr *Input, bool IsAfterAmp) {
16582 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16583 IsAfterAmp);
16584}
16585
16587 LabelDecl *TheDecl) {
16588 TheDecl->markUsed(Context);
16589 // Create the AST node. The address of a label always has type 'void*'.
16590 auto *Res = new (Context) AddrLabelExpr(
16591 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16592
16593 if (getCurFunction())
16594 getCurFunction()->AddrLabels.push_back(Res);
16595
16596 return Res;
16597}
16598
16601 // Make sure we diagnose jumping into a statement expression.
16603}
16604
16606 // Note that function is also called by TreeTransform when leaving a
16607 // StmtExpr scope without rebuilding anything.
16608
16611}
16612
16614 SourceLocation RPLoc) {
16615 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16616}
16617
16619 SourceLocation RPLoc, unsigned TemplateDepth) {
16620 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16621 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16622
16625 assert(!Cleanup.exprNeedsCleanups() &&
16626 "cleanups within StmtExpr not correctly bound!");
16628
16629 // FIXME: there are a variety of strange constraints to enforce here, for
16630 // example, it is not possible to goto into a stmt expression apparently.
16631 // More semantic analysis is needed.
16632
16633 // If there are sub-stmts in the compound stmt, take the type of the last one
16634 // as the type of the stmtexpr.
16635 QualType Ty = Context.VoidTy;
16636 bool StmtExprMayBindToTemp = false;
16637 if (!Compound->body_empty()) {
16638 if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
16639 if (const Expr *Value = LastStmt->getExprStmt()) {
16640 StmtExprMayBindToTemp = true;
16641 Ty = Value->getType();
16642 }
16643 }
16644 }
16645
16646 // FIXME: Check that expression type is complete/non-abstract; statement
16647 // expressions are not lvalues.
16648 Expr *ResStmtExpr =
16649 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16650 if (StmtExprMayBindToTemp)
16651 return MaybeBindToTemporary(ResStmtExpr);
16652 return ResStmtExpr;
16653}
16654
16656 if (ER.isInvalid())
16657 return ExprError();
16658
16659 // Do function/array conversion on the last expression, but not
16660 // lvalue-to-rvalue. However, initialize an unqualified type.
16662 if (ER.isInvalid())
16663 return ExprError();
16664 Expr *E = ER.get();
16665
16666 if (E->isTypeDependent())
16667 return E;
16668
16669 // In ARC, if the final expression ends in a consume, splice
16670 // the consume out and bind it later. In the alternate case
16671 // (when dealing with a retainable type), the result
16672 // initialization will create a produce. In both cases the
16673 // result will be +1, and we'll need to balance that out with
16674 // a bind.
16675 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16676 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16677 return Cast->getSubExpr();
16678
16679 // FIXME: Provide a better location for the initialization.
16683 SourceLocation(), E);
16684}
16685
16687 TypeSourceInfo *TInfo,
16688 const Designation &Desig,
16689 SourceLocation RParenLoc) {
16690 QualType ArgTy = TInfo->getType();
16691 bool Dependent = ArgTy->isDependentType();
16692 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16693
16694 // We must have at least one component that refers to the type, and the first
16695 // one is known to be a field designator. Verify that the ArgTy represents
16696 // a struct/union/class.
16697 if (!Dependent && !ArgTy->isRecordType())
16698 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16699 << ArgTy << TypeRange);
16700
16701 // Type must be complete per C99 7.17p3 because a declaring a variable
16702 // with an incomplete type would be ill-formed.
16703 if (!Dependent
16704 && RequireCompleteType(BuiltinLoc, ArgTy,
16705 diag::err_offsetof_incomplete_type, TypeRange))
16706 return ExprError();
16707
16708 bool DidWarnAboutNonPOD = false;
16709 QualType CurrentType = ArgTy;
16712 for (unsigned I = 0, N = Desig.getNumDesignators(); I != N; ++I) {
16713 const Designator &D = Desig.getDesignator(I);
16714 assert(!D.isArrayRangeDesignator());
16715 if (D.isArrayDesignator()) {
16716 // Offset of an array sub-field. TODO: Should we allow vector elements?
16717 if (!CurrentType->isDependentType()) {
16718 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16719 if(!AT)
16720 return ExprError(Diag(D.getEndLoc(), diag::err_offsetof_array_type)
16721 << CurrentType);
16722 CurrentType = AT->getElementType();
16723 } else
16724 CurrentType = Context.DependentTy;
16725
16727 if (IdxRval.isInvalid())
16728 return ExprError();
16729 Expr *Idx = IdxRval.get();
16730
16731 // The expression must be an integral expression.
16732 // FIXME: An integral constant expression?
16733 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16734 !Idx->getType()->isIntegerType())
16735 return ExprError(
16736 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16737 << Idx->getSourceRange());
16738
16739 // Record this array index.
16740 Comps.push_back(
16741 OffsetOfNode(D.getBeginLoc(), Exprs.size(), D.getEndLoc()));
16742 Exprs.push_back(Idx);
16743 continue;
16744 }
16745
16746 assert(D.isFieldDesignator());
16747 const IdentifierInfo *Name = D.getFieldDecl();
16748
16749 // Offset of a field.
16750 if (CurrentType->isDependentType()) {
16751 // We have the offset of a field, but we can't look into the dependent
16752 // type. Just record the identifier of the field.
16753 Comps.push_back(OffsetOfNode(D.getBeginLoc(), Name, D.getEndLoc()));
16754 CurrentType = Context.DependentTy;
16755 continue;
16756 }
16757
16758 // We need to have a complete type to look into.
16759 if (RequireCompleteType(D.getBeginLoc(), CurrentType,
16760 diag::err_offsetof_incomplete_type))
16761 return ExprError();
16762
16763 // Look for the designated field.
16764 auto *RD = CurrentType->getAsRecordDecl();
16765 if (!RD)
16766 return ExprError(Diag(D.getEndLoc(), diag::err_offsetof_record_type)
16767 << CurrentType);
16768
16769 // C++ [lib.support.types]p5:
16770 // The macro offsetof accepts a restricted set of type arguments in this
16771 // International Standard. type shall be a POD structure or a POD union
16772 // (clause 9).
16773 // C++11 [support.types]p4:
16774 // If type is not a standard-layout class (Clause 9), the results are
16775 // undefined.
16776 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16777 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16778 unsigned DiagID =
16779 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16780 : diag::ext_offsetof_non_pod_type;
16781
16782 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16783 Diag(BuiltinLoc, DiagID)
16785 << CurrentType;
16786 DidWarnAboutNonPOD = true;
16787 }
16788 }
16789
16790 // Look for the field.
16791 LookupResult R(*this, Name, D.getBeginLoc(), LookupMemberName);
16792 LookupQualifiedName(R, RD);
16793 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16794 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16795 if (!MemberDecl) {
16796 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16797 MemberDecl = IndirectMemberDecl->getAnonField();
16798 }
16799
16800 if (!MemberDecl) {
16801 // Lookup could be ambiguous when looking up a placeholder variable
16802 // __builtin_offsetof(S, _).
16803 // In that case we would already have emitted a diagnostic
16804 if (!R.isAmbiguous())
16805 Diag(BuiltinLoc, diag::err_no_member)
16806 << Name << RD << SourceRange(D.getBeginLoc(), D.getEndLoc());
16807 return ExprError();
16808 }
16809
16810 // C99 7.17p3:
16811 // (If the specified member is a bit-field, the behavior is undefined.)
16812 //
16813 // We diagnose this as an error.
16814 if (MemberDecl->isBitField()) {
16815 Diag(D.getEndLoc(), diag::err_offsetof_bitfield)
16816 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
16817 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16818 return ExprError();
16819 }
16820
16821 RecordDecl *Parent = MemberDecl->getParent();
16822 if (IndirectMemberDecl)
16823 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16824
16825 // If the member was found in a base class, introduce OffsetOfNodes for
16826 // the base class indirections.
16827 CXXBasePaths Paths;
16828 if (IsDerivedFrom(D.getBeginLoc(), CurrentType,
16829 Context.getCanonicalTagType(Parent), Paths)) {
16830 if (Paths.getDetectedVirtual()) {
16831 Diag(D.getEndLoc(), diag::err_offsetof_field_of_virtual_base)
16832 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
16833 return ExprError();
16834 }
16835
16836 CXXBasePath &Path = Paths.front();
16837 for (const CXXBasePathElement &B : Path)
16838 Comps.push_back(OffsetOfNode(B.Base));
16839 }
16840
16841 if (IndirectMemberDecl) {
16842 for (auto *FI : IndirectMemberDecl->chain()) {
16843 assert(isa<FieldDecl>(FI));
16844 Comps.push_back(
16846 }
16847 } else
16848 Comps.push_back(OffsetOfNode(D.getBeginLoc(), MemberDecl, D.getEndLoc()));
16849
16850 CurrentType = MemberDecl->getType().getNonReferenceType();
16851 }
16852
16853 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16854 Comps, Exprs, RParenLoc);
16855}
16856
16859 ParsedType ParsedArgTy,
16860 const Designation &Desig,
16861 SourceLocation RParenLoc) {
16862
16863 TypeSourceInfo *ArgTInfo;
16864 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16865 if (ArgTy.isNull())
16866 return ExprError();
16867
16868 if (!ArgTInfo)
16869 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16870
16871 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Desig, RParenLoc);
16872}
16873
16875 Expr *CondExpr,
16876 Expr *LHSExpr, Expr *RHSExpr,
16877 SourceLocation RPLoc) {
16878 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16879
16882 QualType resType;
16883 bool CondIsTrue = false;
16884 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16885 resType = Context.DependentTy;
16886 } else {
16887 // The conditional expression is required to be a constant expression.
16888 llvm::APSInt condEval(32);
16890 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16891 if (CondICE.isInvalid())
16892 return ExprError();
16893 CondExpr = CondICE.get();
16894 CondIsTrue = condEval.getZExtValue();
16895
16896 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16897 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16898
16899 resType = ActiveExpr->getType();
16900 VK = ActiveExpr->getValueKind();
16901 OK = ActiveExpr->getObjectKind();
16902 }
16903
16904 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16905 resType, VK, OK, RPLoc, CondIsTrue);
16906}
16907
16908//===----------------------------------------------------------------------===//
16909// Clang Extensions.
16910//===----------------------------------------------------------------------===//
16911
16912void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16914
16915 if (LangOpts.CPlusPlus) {
16917 Decl *ManglingContextDecl;
16918 std::tie(MCtx, ManglingContextDecl) =
16919 getCurrentMangleNumberContext(Block->getDeclContext());
16920 if (MCtx) {
16921 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16922 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16923 }
16924 }
16925
16926 PushBlockScope(CurScope, Block);
16927 CurContext->addDecl(Block);
16928 if (CurScope)
16929 PushDeclContext(CurScope, Block);
16930 else
16931 CurContext = Block;
16932
16934
16935 // Enter a new evaluation context to insulate the block from any
16936 // cleanups from the enclosing full-expression.
16939}
16940
16942 Scope *CurScope) {
16943 assert(ParamInfo.getIdentifier() == nullptr &&
16944 "block-id should have no identifier!");
16945 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16946 BlockScopeInfo *CurBlock = getCurBlock();
16947
16948 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16949 QualType T = Sig->getType();
16951
16952 // GetTypeForDeclarator always produces a function type for a block
16953 // literal signature. Furthermore, it is always a FunctionProtoType
16954 // unless the function was written with a typedef.
16955 assert(T->isFunctionType() &&
16956 "GetTypeForDeclarator made a non-function block signature");
16957
16958 // Look for an explicit signature in that function type.
16959 FunctionProtoTypeLoc ExplicitSignature;
16960
16961 if ((ExplicitSignature = Sig->getTypeLoc()
16963
16964 // Check whether that explicit signature was synthesized by
16965 // GetTypeForDeclarator. If so, don't save that as part of the
16966 // written signature.
16967 if (ExplicitSignature.getLocalRangeBegin() ==
16968 ExplicitSignature.getLocalRangeEnd()) {
16969 // This would be much cheaper if we stored TypeLocs instead of
16970 // TypeSourceInfos.
16971 TypeLoc Result = ExplicitSignature.getReturnLoc();
16972 unsigned Size = Result.getFullDataSize();
16973 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16974 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16975
16976 ExplicitSignature = FunctionProtoTypeLoc();
16977 }
16978 }
16979
16980 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16981 CurBlock->FunctionType = T;
16982
16983 const auto *Fn = T->castAs<FunctionType>();
16984 QualType RetTy = Fn->getReturnType();
16985 bool isVariadic =
16986 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16987
16988 CurBlock->TheDecl->setIsVariadic(isVariadic);
16989
16990 // Context.DependentTy is used as a placeholder for a missing block
16991 // return type. TODO: what should we do with declarators like:
16992 // ^ * { ... }
16993 // If the answer is "apply template argument deduction"....
16994 if (RetTy != Context.DependentTy) {
16995 CurBlock->ReturnType = RetTy;
16996 CurBlock->TheDecl->setBlockMissingReturnType(false);
16997 CurBlock->HasImplicitReturnType = false;
16998 }
16999
17000 // Push block parameters from the declarator if we had them.
17002 if (ExplicitSignature) {
17003 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
17004 ParmVarDecl *Param = ExplicitSignature.getParam(I);
17005 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
17006 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
17007 // Diagnose this as an extension in C17 and earlier.
17008 if (!getLangOpts().C23)
17009 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
17010 }
17011 Params.push_back(Param);
17012 }
17013
17014 // Fake up parameter variables if we have a typedef, like
17015 // ^ fntype { ... }
17016 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
17017 for (const auto &I : Fn->param_types()) {
17019 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
17020 Params.push_back(Param);
17021 }
17022 }
17023
17024 // Set the parameters on the block decl.
17025 if (!Params.empty()) {
17026 CurBlock->TheDecl->setParams(Params);
17028 /*CheckParameterNames=*/false);
17029 }
17030
17031 // Finally we can process decl attributes.
17032 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
17033
17034 // Put the parameter variables in scope.
17035 for (auto *AI : CurBlock->TheDecl->parameters()) {
17036 AI->setOwningFunction(CurBlock->TheDecl);
17037
17038 // If this has an identifier, add it to the scope stack.
17039 if (AI->getIdentifier()) {
17040 CheckShadow(CurBlock->TheScope, AI);
17041
17042 PushOnScopeChains(AI, CurBlock->TheScope);
17043 }
17044
17045 if (AI->isInvalidDecl())
17046 CurBlock->TheDecl->setInvalidDecl();
17047 }
17048}
17049
17050void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17051 // Leave the expression-evaluation context.
17054
17055 // Pop off CurBlock, handle nested blocks.
17058}
17059
17061 Stmt *Body, Scope *CurScope) {
17062 // If blocks are disabled, emit an error.
17063 if (!LangOpts.Blocks)
17064 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
17065
17066 // Leave the expression-evaluation context.
17069 assert(!Cleanup.exprNeedsCleanups() &&
17070 "cleanups within block not correctly bound!");
17072
17074 BlockDecl *BD = BSI->TheDecl;
17075
17077
17078 if (BSI->HasImplicitReturnType)
17080
17081 QualType RetTy = Context.VoidTy;
17082 if (!BSI->ReturnType.isNull())
17083 RetTy = BSI->ReturnType;
17084
17085 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17086 QualType BlockTy;
17087
17088 // If the user wrote a function type in some form, try to use that.
17089 if (!BSI->FunctionType.isNull()) {
17090 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17091
17092 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17093 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
17094
17095 // Turn protoless block types into nullary block types.
17096 if (isa<FunctionNoProtoType>(FTy)) {
17098 EPI.ExtInfo = Ext;
17099 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17100
17101 // Otherwise, if we don't need to change anything about the function type,
17102 // preserve its sugar structure.
17103 } else if (FTy->getReturnType() == RetTy &&
17104 (!NoReturn || FTy->getNoReturnAttr())) {
17105 BlockTy = BSI->FunctionType;
17106
17107 // Otherwise, make the minimal modifications to the function type.
17108 } else {
17111 EPI.TypeQuals = Qualifiers();
17112 EPI.ExtInfo = Ext;
17113 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
17114 }
17115
17116 // If we don't have a function type, just build one from nothing.
17117 } else {
17119 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
17120 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17121 }
17122
17124 BlockTy = Context.getBlockPointerType(BlockTy);
17125
17126 // If needed, diagnose invalid gotos and switches in the block.
17127 if (getCurFunction()->NeedsScopeChecking() &&
17128 !PP.isCodeCompletionEnabled())
17130
17131 BD->setBody(cast<CompoundStmt>(Body));
17132
17133 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17135
17136 // Try to apply the named return value optimization. We have to check again
17137 // if we can do this, though, because blocks keep return statements around
17138 // to deduce an implicit return type.
17139 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17140 !BD->isDependentContext())
17141 computeNRVO(Body, BSI);
17142
17148
17150
17151 // Set the captured variables on the block.
17153 for (Capture &Cap : BSI->Captures) {
17154 if (Cap.isInvalid() || Cap.isThisCapture())
17155 continue;
17156 // Cap.getVariable() is always a VarDecl because
17157 // blocks cannot capture structured bindings or other ValueDecl kinds.
17158 auto *Var = cast<VarDecl>(Cap.getVariable());
17159 Expr *CopyExpr = nullptr;
17160 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17161 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17162 // The capture logic needs the destructor, so make sure we mark it.
17163 // Usually this is unnecessary because most local variables have
17164 // their destructors marked at declaration time, but parameters are
17165 // an exception because it's technically only the call site that
17166 // actually requires the destructor.
17167 if (isa<ParmVarDecl>(Var))
17169
17170 // Enter a separate potentially-evaluated context while building block
17171 // initializers to isolate their cleanups from those of the block
17172 // itself.
17173 // FIXME: Is this appropriate even when the block itself occurs in an
17174 // unevaluated operand?
17177
17178 SourceLocation Loc = Cap.getLocation();
17179
17181 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
17182
17183 // According to the blocks spec, the capture of a variable from
17184 // the stack requires a const copy constructor. This is not true
17185 // of the copy/move done to move a __block variable to the heap.
17186 if (!Result.isInvalid() &&
17187 !Result.get()->getType().isConstQualified()) {
17189 Result.get()->getType().withConst(),
17190 CK_NoOp, VK_LValue);
17191 }
17192
17193 if (!Result.isInvalid()) {
17195 InitializedEntity::InitializeBlock(Var->getLocation(),
17196 Cap.getCaptureType()),
17197 Loc, Result.get());
17198 }
17199
17200 // Build a full-expression copy expression if initialization
17201 // succeeded and used a non-trivial constructor. Recover from
17202 // errors by pretending that the copy isn't necessary.
17203 if (!Result.isInvalid() &&
17204 !cast<CXXConstructExpr>(Result.get())->getConstructor()
17205 ->isTrivial()) {
17207 CopyExpr = Result.get();
17208 }
17209 }
17210 }
17211
17212 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17213 CopyExpr);
17214 Captures.push_back(NewCap);
17215 }
17216 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
17217
17218 // Pop the block scope now but keep it alive to the end of this function.
17220 AnalysisWarnings.getPolicyInEffectAt(Body->getEndLoc());
17221 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
17222
17223 BlockExpr *Result = new (Context)
17224 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17225
17226 // If the block isn't obviously global, i.e. it captures anything at
17227 // all, then we need to do a few things in the surrounding context:
17228 if (Result->getBlockDecl()->hasCaptures()) {
17229 // First, this expression has a new cleanup object.
17230 ExprCleanupObjects.push_back(Result->getBlockDecl());
17231 Cleanup.setExprNeedsCleanups(true);
17232
17233 // It also gets a branch-protected scope if any of the captured
17234 // variables needs destruction.
17235 for (const auto &CI : Result->getBlockDecl()->captures()) {
17236 const VarDecl *var = CI.getVariable();
17237 if (var->getType().isDestructedType() != QualType::DK_none) {
17239 break;
17240 }
17241 }
17242 }
17243
17244 if (getCurFunction())
17245 getCurFunction()->addBlock(BD);
17246
17247 // This can happen if the block's return type is deduced, but
17248 // the return expression is invalid.
17249 if (BD->isInvalidDecl())
17250 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
17251 {Result}, Result->getType());
17252 return Result;
17253}
17254
17256 SourceLocation RPLoc) {
17257 TypeSourceInfo *TInfo;
17258 GetTypeFromParser(Ty, &TInfo);
17259 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17260}
17261
17263 Expr *E, TypeSourceInfo *TInfo,
17264 SourceLocation RPLoc) {
17265 Expr *OrigExpr = E;
17267
17268 // CUDA device global function does not support varargs.
17269 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17270 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
17273 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
17274 }
17275 }
17276
17277 // NVPTX does not support va_arg expression.
17278 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17279 Context.getTargetInfo().getTriple().isNVPTX())
17280 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
17281
17282 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17283 // as Microsoft ABI on an actual Microsoft platform, where
17284 // __builtin_ms_va_list and __builtin_va_list are the same.)
17285 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17286 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17287 QualType MSVaListType = Context.getBuiltinMSVaListType();
17288 if (Context.hasSameType(MSVaListType, E->getType())) {
17289 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
17290 return ExprError();
17291 VAKind = VAArgExpr::VA_MS;
17292 }
17293 }
17294
17295 // Get the va_list type
17296 QualType VaListType = Context.getBuiltinVaListType();
17297
17298 // It might be a __builtin_zos_va_list!
17299 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinZOSVaList()) {
17300 // E->getType() can be:
17301 // - va_list: equal to array (char*)[2] (inside function)
17302 // - char **: decayed array (va_list passed as parameter)
17303 // We need to check for both cases.
17304 QualType ZOSVaListType = Context.getBuiltinZOSVaListType();
17305 assert(ZOSVaListType->isArrayType() &&
17306 "__builtin_zos_va_list must be an array type");
17307 QualType DecayedType = Context.getArrayDecayedType(ZOSVaListType);
17308 if (Context.hasSameType(ZOSVaListType, E->getType()) ||
17309 Context.hasSameType(DecayedType, E->getType())) {
17310 VAKind = VAArgExpr::VA_ZOS;
17311 VaListType = ZOSVaListType;
17312 }
17313 }
17314
17315 if (VAKind != VAArgExpr::VA_MS) {
17316 if (VaListType->isArrayType()) {
17317 // Deal with implicit array decay; for example, on x86-64,
17318 // va_list is an array, but it's supposed to decay to
17319 // a pointer for va_arg.
17320 VaListType = Context.getArrayDecayedType(VaListType);
17321 // Make sure the input expression also decays appropriately.
17323 if (Result.isInvalid())
17324 return ExprError();
17325 E = Result.get();
17326 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17327 // If va_list is a record type and we are compiling in C++ mode,
17328 // check the argument using reference binding.
17330 Context, Context.getLValueReferenceType(VaListType), false);
17332 if (Init.isInvalid())
17333 return ExprError();
17334 E = Init.getAs<Expr>();
17335 } else {
17336 // Otherwise, the va_list argument must be an l-value because
17337 // it is modified by va_arg.
17338 if (!E->isTypeDependent() &&
17339 CheckForModifiableLvalue(E, BuiltinLoc, *this))
17340 return ExprError();
17341 }
17342 }
17343
17344 if ((VAKind != VAArgExpr::VA_MS) && !E->isTypeDependent() &&
17345 !Context.hasSameType(VaListType, E->getType()))
17346 return ExprError(
17347 Diag(E->getBeginLoc(),
17348 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17349 << OrigExpr->getType() << E->getSourceRange());
17350
17351 if (!TInfo->getType()->isDependentType()) {
17352 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17353 diag::err_second_parameter_to_va_arg_incomplete,
17354 TInfo->getTypeLoc()))
17355 return ExprError();
17356
17358 TInfo->getType(),
17359 diag::err_second_parameter_to_va_arg_abstract,
17360 TInfo->getTypeLoc()))
17361 return ExprError();
17362
17363 if (!TInfo->getType().isPODType(Context)) {
17364 Diag(TInfo->getTypeLoc().getBeginLoc(),
17365 TInfo->getType()->isObjCLifetimeType()
17366 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17367 : diag::warn_second_parameter_to_va_arg_not_pod)
17368 << TInfo->getType()
17369 << TInfo->getTypeLoc().getSourceRange();
17370 }
17371
17372 if (TInfo->getType()->isArrayType()) {
17374 PDiag(diag::warn_second_parameter_to_va_arg_array)
17375 << TInfo->getType()
17376 << TInfo->getTypeLoc().getSourceRange());
17377 }
17378
17379 // Check for va_arg where arguments of the given type will be promoted
17380 // (i.e. this va_arg is guaranteed to have undefined behavior).
17381 QualType PromoteType;
17382 if (Context.isPromotableIntegerType(TInfo->getType())) {
17383 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17384 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17385 // and C23 7.16.1.1p2 says, in part:
17386 // If type is not compatible with the type of the actual next argument
17387 // (as promoted according to the default argument promotions), the
17388 // behavior is undefined, except for the following cases:
17389 // - both types are pointers to qualified or unqualified versions of
17390 // compatible types;
17391 // - one type is compatible with a signed integer type, the other
17392 // type is compatible with the corresponding unsigned integer type,
17393 // and the value is representable in both types;
17394 // - one type is pointer to qualified or unqualified void and the
17395 // other is a pointer to a qualified or unqualified character type;
17396 // - or, the type of the next argument is nullptr_t and type is a
17397 // pointer type that has the same representation and alignment
17398 // requirements as a pointer to a character type.
17399 // Given that type compatibility is the primary requirement (ignoring
17400 // qualifications), you would think we could call typesAreCompatible()
17401 // directly to test this. However, in C++, that checks for *same type*,
17402 // which causes false positives when passing an enumeration type to
17403 // va_arg. Instead, get the underlying type of the enumeration and pass
17404 // that.
17405 QualType UnderlyingType = TInfo->getType();
17406 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17407 UnderlyingType = ED->getIntegerType();
17408 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17409 /*CompareUnqualified*/ true))
17410 PromoteType = QualType();
17411
17412 // If the types are still not compatible, we need to test whether the
17413 // promoted type and the underlying type are the same except for
17414 // signedness. Ask the AST for the correctly corresponding type and see
17415 // if that's compatible.
17416 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17417 PromoteType->isUnsignedIntegerType() !=
17418 UnderlyingType->isUnsignedIntegerType()) {
17419 UnderlyingType =
17420 UnderlyingType->isUnsignedIntegerType()
17421 ? Context.getCorrespondingSignedType(UnderlyingType)
17422 : Context.getCorrespondingUnsignedType(UnderlyingType);
17423 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17424 /*CompareUnqualified*/ true))
17425 PromoteType = QualType();
17426 }
17427 }
17428 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17429 PromoteType = Context.DoubleTy;
17430 if (!PromoteType.isNull())
17432 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17433 << TInfo->getType()
17434 << PromoteType
17435 << TInfo->getTypeLoc().getSourceRange());
17436 }
17437
17439 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, VAKind);
17440}
17441
17443 // The type of __null will be int or long, depending on the size of
17444 // pointers on the target.
17445 QualType Ty;
17446 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17447 if (pw == Context.getTargetInfo().getIntWidth())
17448 Ty = Context.IntTy;
17449 else if (pw == Context.getTargetInfo().getLongWidth())
17450 Ty = Context.LongTy;
17451 else if (pw == Context.getTargetInfo().getLongLongWidth())
17452 Ty = Context.LongLongTy;
17453 else {
17454 llvm_unreachable("I don't know size of pointer!");
17455 }
17456
17457 return new (Context) GNUNullExpr(Ty, TokenLoc);
17458}
17459
17461 CXXRecordDecl *ImplDecl = nullptr;
17462
17463 // Fetch the std::source_location::__impl decl.
17464 if (NamespaceDecl *Std = S.getStdNamespace()) {
17465 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17467 if (S.LookupQualifiedName(ResultSL, Std)) {
17468 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17469 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17471 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17472 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17473 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17474 }
17475 }
17476 }
17477 }
17478
17479 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17480 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17481 return nullptr;
17482 }
17483
17484 // Verify that __impl is a trivial struct type, with no base classes, and with
17485 // only the four expected fields.
17486 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17487 ImplDecl->getNumBases() != 0) {
17488 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17489 return nullptr;
17490 }
17491
17492 unsigned Count = 0;
17493 for (FieldDecl *F : ImplDecl->fields()) {
17494 StringRef Name = F->getName();
17495
17496 if (Name == "_M_file_name") {
17497 if (F->getType() !=
17499 break;
17500 Count++;
17501 } else if (Name == "_M_function_name") {
17502 if (F->getType() !=
17504 break;
17505 Count++;
17506 } else if (Name == "_M_line") {
17507 if (!F->getType()->isIntegerType())
17508 break;
17509 Count++;
17510 } else if (Name == "_M_column") {
17511 if (!F->getType()->isIntegerType())
17512 break;
17513 Count++;
17514 } else {
17515 Count = 100; // invalid
17516 break;
17517 }
17518 }
17519 if (Count != 4) {
17520 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17521 return nullptr;
17522 }
17523
17524 return ImplDecl;
17525}
17526
17528 SourceLocation BuiltinLoc,
17529 SourceLocation RPLoc) {
17530 QualType ResultTy;
17531 switch (Kind) {
17536 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17537 ResultTy =
17538 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17539 break;
17540 }
17543 ResultTy = Context.UnsignedIntTy;
17544 break;
17548 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17550 return ExprError();
17551 }
17552 ResultTy = Context.getPointerType(
17553 Context.getCanonicalTagType(StdSourceLocationImplDecl).withConst());
17554 break;
17555 }
17556
17557 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17558}
17559
17561 SourceLocation BuiltinLoc,
17562 SourceLocation RPLoc,
17563 DeclContext *ParentContext) {
17564 return new (Context)
17565 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17566}
17567
17569 StringLiteral *BinaryData, StringRef FileName) {
17571 Data->BinaryData = BinaryData;
17572 Data->FileName = FileName;
17573 return new (Context)
17574 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17575 Data->getDataElementCount());
17576}
17577
17579 const Expr *SrcExpr) {
17580 if (!DstType->isFunctionPointerType() ||
17581 !SrcExpr->getType()->isFunctionType())
17582 return false;
17583
17584 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17585 if (!DRE)
17586 return false;
17587
17588 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17589 if (!FD)
17590 return false;
17591
17593 /*Complain=*/true,
17594 SrcExpr->getBeginLoc());
17595}
17596
17598 SourceLocation Loc,
17599 QualType DstType, QualType SrcType,
17600 Expr *SrcExpr, AssignmentAction Action,
17601 bool *Complained) {
17602 if (Complained)
17603 *Complained = false;
17604
17605 // Decode the result (notice that AST's are still created for extensions).
17606 bool CheckInferredResultType = false;
17607 bool isInvalid = false;
17608 unsigned DiagKind = 0;
17609 ConversionFixItGenerator ConvHints;
17610 bool MayHaveConvFixit = false;
17611 bool MayHaveFunctionDiff = false;
17612 const ObjCInterfaceDecl *IFace = nullptr;
17613 const ObjCProtocolDecl *PDecl = nullptr;
17614
17615 switch (ConvTy) {
17617 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17618 return false;
17620 // Still a valid conversion, but we may want to diagnose for C++
17621 // compatibility reasons.
17622 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17623 break;
17625 if (getLangOpts().CPlusPlus) {
17626 DiagKind = diag::err_typecheck_convert_pointer_int;
17627 isInvalid = true;
17628 } else {
17629 DiagKind = diag::ext_typecheck_convert_pointer_int;
17630 }
17631 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17632 MayHaveConvFixit = true;
17633 break;
17635 if (getLangOpts().CPlusPlus) {
17636 DiagKind = diag::err_typecheck_convert_int_pointer;
17637 isInvalid = true;
17638 } else {
17639 DiagKind = diag::ext_typecheck_convert_int_pointer;
17640 }
17641 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17642 MayHaveConvFixit = true;
17643 break;
17645 DiagKind =
17646 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17647 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17648 MayHaveConvFixit = true;
17649 break;
17651 if (getLangOpts().CPlusPlus) {
17652 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17653 isInvalid = true;
17654 } else {
17655 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17656 }
17657 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17658 MayHaveConvFixit = true;
17659 break;
17662 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17663 } else if (getLangOpts().CPlusPlus) {
17664 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17665 isInvalid = true;
17666 } else {
17667 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17668 }
17669 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17670 SrcType->isObjCObjectPointerType();
17671 if (CheckInferredResultType) {
17672 SrcType = SrcType.getUnqualifiedType();
17673 DstType = DstType.getUnqualifiedType();
17674 } else {
17675 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17676 }
17677 MayHaveConvFixit = true;
17678 break;
17680 if (getLangOpts().CPlusPlus) {
17681 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17682 isInvalid = true;
17683 } else {
17684 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17685 }
17686 break;
17688 if (getLangOpts().CPlusPlus) {
17689 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17690 isInvalid = true;
17691 } else {
17692 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17693 }
17694 break;
17696 // Perform decay if necessary.
17697 if (SrcType->canDecayToPointerType())
17698 SrcType = Context.getDecayedType(SrcType);
17699
17700 isInvalid = true;
17701
17702 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17703 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17704 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17705 DiagKind = diag::err_typecheck_incompatible_address_space;
17706 break;
17707 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17708 DiagKind = diag::err_typecheck_incompatible_ownership;
17709 break;
17710 } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {
17711 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17712 break;
17713 }
17714
17715 llvm_unreachable("unknown error case for discarding qualifiers!");
17716 // fallthrough
17717 }
17719 if (SrcType->isArrayType())
17720 SrcType = Context.getArrayDecayedType(SrcType);
17721
17722 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17723 break;
17725 // If the qualifiers lost were because we were applying the
17726 // (deprecated) C++ conversion from a string literal to a char*
17727 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17728 // Ideally, this check would be performed in
17729 // checkPointerTypesForAssignment. However, that would require a
17730 // bit of refactoring (so that the second argument is an
17731 // expression, rather than a type), which should be done as part
17732 // of a larger effort to fix checkPointerTypesForAssignment for
17733 // C++ semantics.
17734 if (getLangOpts().CPlusPlus &&
17736 return false;
17737 if (getLangOpts().CPlusPlus) {
17738 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17739 isInvalid = true;
17740 } else {
17741 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17742 }
17743
17744 break;
17746 if (getLangOpts().CPlusPlus) {
17747 isInvalid = true;
17748 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17749 } else {
17750 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17751 }
17752 break;
17754 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17755 isInvalid = true;
17756 break;
17758 DiagKind = diag::err_int_to_block_pointer;
17759 isInvalid = true;
17760 break;
17762 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17763 isInvalid = true;
17764 break;
17766 if (SrcType->isObjCQualifiedIdType()) {
17767 const ObjCObjectPointerType *srcOPT =
17768 SrcType->castAs<ObjCObjectPointerType>();
17769 for (auto *srcProto : srcOPT->quals()) {
17770 PDecl = srcProto;
17771 break;
17772 }
17773 if (const ObjCInterfaceType *IFaceT =
17775 IFace = IFaceT->getDecl();
17776 }
17777 else if (DstType->isObjCQualifiedIdType()) {
17778 const ObjCObjectPointerType *dstOPT =
17779 DstType->castAs<ObjCObjectPointerType>();
17780 for (auto *dstProto : dstOPT->quals()) {
17781 PDecl = dstProto;
17782 break;
17783 }
17784 if (const ObjCInterfaceType *IFaceT =
17786 IFace = IFaceT->getDecl();
17787 }
17788 if (getLangOpts().CPlusPlus) {
17789 DiagKind = diag::err_incompatible_qualified_id;
17790 isInvalid = true;
17791 } else {
17792 DiagKind = diag::warn_incompatible_qualified_id;
17793 }
17794 break;
17795 }
17797 if (getLangOpts().CPlusPlus) {
17798 DiagKind = diag::err_incompatible_vectors;
17799 isInvalid = true;
17800 } else {
17801 DiagKind = diag::warn_incompatible_vectors;
17802 }
17803 break;
17805 DiagKind = diag::err_arc_weak_unavailable_assign;
17806 isInvalid = true;
17807 break;
17809 return false;
17811 assert(!SrcType->isFunctionType() &&
17812 "Unexpected function type found in IncompatibleOBTKinds assignment");
17813 if (SrcType->canDecayToPointerType())
17814 SrcType = Context.getDecayedType(SrcType);
17815
17816 auto getOBTKindName = [](QualType Ty) -> StringRef {
17817 if (Ty->isPointerType())
17818 Ty = Ty->getPointeeType();
17819 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
17820 return OBT->getBehaviorKind() ==
17821 OverflowBehaviorType::OverflowBehaviorKind::Trap
17822 ? "__ob_trap"
17823 : "__ob_wrap";
17824 }
17825 llvm_unreachable("OBT kind unhandled");
17826 };
17827
17828 Diag(Loc, diag::err_incompatible_obt_kinds_assignment)
17829 << DstType << SrcType << getOBTKindName(DstType)
17830 << getOBTKindName(SrcType);
17831 isInvalid = true;
17832 return true;
17833 }
17835 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17836 if (Complained)
17837 *Complained = true;
17838 return true;
17839 }
17840
17841 DiagKind = diag::err_typecheck_convert_incompatible;
17842 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17843 MayHaveConvFixit = true;
17844 isInvalid = true;
17845 MayHaveFunctionDiff = true;
17846 break;
17847 }
17848
17849 QualType FirstType, SecondType;
17850 switch (Action) {
17853 // The destination type comes first.
17854 FirstType = DstType;
17855 SecondType = SrcType;
17856 break;
17857
17864 // The source type comes first.
17865 FirstType = SrcType;
17866 SecondType = DstType;
17867 break;
17868 }
17869
17870 PartialDiagnostic FDiag = PDiag(DiagKind);
17871 AssignmentAction ActionForDiag = Action;
17873 ActionForDiag = AssignmentAction::Passing;
17874
17875 FDiag << FirstType << SecondType << ActionForDiag
17876 << SrcExpr->getSourceRange();
17877
17878 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17879 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17880 auto isPlainChar = [](const clang::Type *Type) {
17881 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17882 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17883 };
17884 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17885 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17886 }
17887
17888 // If we can fix the conversion, suggest the FixIts.
17889 if (!ConvHints.isNull()) {
17890 for (FixItHint &H : ConvHints.Hints)
17891 FDiag << H;
17892 }
17893
17894 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17895
17896 if (MayHaveFunctionDiff)
17897 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17898
17899 Diag(Loc, FDiag);
17900 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17901 DiagKind == diag::err_incompatible_qualified_id) &&
17902 PDecl && IFace && !IFace->hasDefinition())
17903 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17904 << IFace << PDecl;
17905
17906 if (SecondType == Context.OverloadTy)
17908 FirstType, /*TakingAddress=*/true);
17909
17910 if (CheckInferredResultType)
17912
17913 if (Action == AssignmentAction::Returning &&
17916
17917 if (Complained)
17918 *Complained = true;
17919 return isInvalid;
17920}
17921
17923 llvm::APSInt *Result,
17924 AllowFoldKind CanFold) {
17925 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17926 public:
17927 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17928 QualType T) override {
17929 return S.Diag(Loc, diag::err_ice_not_integral)
17930 << T << S.LangOpts.CPlusPlus;
17931 }
17932 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17933 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17934 }
17935 } Diagnoser;
17936
17937 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17938}
17939
17941 llvm::APSInt *Result,
17942 unsigned DiagID,
17943 AllowFoldKind CanFold) {
17944 class IDDiagnoser : public VerifyICEDiagnoser {
17945 unsigned DiagID;
17946
17947 public:
17948 IDDiagnoser(unsigned DiagID)
17949 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17950
17951 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17952 return S.Diag(Loc, DiagID);
17953 }
17954 } Diagnoser(DiagID);
17955
17956 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17957}
17958
17964
17967 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17968}
17969
17972 VerifyICEDiagnoser &Diagnoser,
17973 AllowFoldKind CanFold) {
17974 SourceLocation DiagLoc = E->getBeginLoc();
17975
17976 if (getLangOpts().CPlusPlus11) {
17977 // C++11 [expr.const]p5:
17978 // If an expression of literal class type is used in a context where an
17979 // integral constant expression is required, then that class type shall
17980 // have a single non-explicit conversion function to an integral or
17981 // unscoped enumeration type
17982 ExprResult Converted;
17983 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17984 VerifyICEDiagnoser &BaseDiagnoser;
17985 public:
17986 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17987 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17988 BaseDiagnoser.Suppress, true),
17989 BaseDiagnoser(BaseDiagnoser) {}
17990
17991 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17992 QualType T) override {
17993 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17994 }
17995
17996 SemaDiagnosticBuilder diagnoseIncomplete(
17997 Sema &S, SourceLocation Loc, QualType T) override {
17998 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17999 }
18000
18001 SemaDiagnosticBuilder diagnoseExplicitConv(
18002 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18003 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
18004 }
18005
18006 SemaDiagnosticBuilder noteExplicitConv(
18007 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18008 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18009 << ConvTy->isEnumeralType() << ConvTy;
18010 }
18011
18012 SemaDiagnosticBuilder diagnoseAmbiguous(
18013 Sema &S, SourceLocation Loc, QualType T) override {
18014 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
18015 }
18016
18017 SemaDiagnosticBuilder noteAmbiguous(
18018 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18019 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18020 << ConvTy->isEnumeralType() << ConvTy;
18021 }
18022
18023 SemaDiagnosticBuilder diagnoseConversion(
18024 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18025 llvm_unreachable("conversion functions are permitted");
18026 }
18027 } ConvertDiagnoser(Diagnoser);
18028
18029 Converted = PerformContextualImplicitConversion(DiagLoc, E,
18030 ConvertDiagnoser);
18031 if (Converted.isInvalid())
18032 return Converted;
18033 E = Converted.get();
18034 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
18035 // don't try to evaluate it later. We also don't want to return the
18036 // RecoveryExpr here, as it results in this call succeeding, thus callers of
18037 // this function will attempt to use 'Value'.
18038 if (isa<RecoveryExpr>(E))
18039 return ExprError();
18041 return ExprError();
18042 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
18043 // An ICE must be of integral or unscoped enumeration type.
18044 if (!Diagnoser.Suppress)
18045 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
18046 << E->getSourceRange();
18047 return ExprError();
18048 }
18049
18050 ExprResult RValueExpr = DefaultLvalueConversion(E);
18051 if (RValueExpr.isInvalid())
18052 return ExprError();
18053
18054 E = RValueExpr.get();
18055
18056 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18057 // in the non-ICE case.
18060 if (Result)
18062 if (!isa<ConstantExpr>(E))
18065
18066 if (Notes.empty())
18067 return E;
18068
18069 // If our only note is the usual "invalid subexpression" note, just point
18070 // the caret at its location rather than producing an essentially
18071 // redundant note.
18072 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18073 diag::note_invalid_subexpr_in_const_expr) {
18074 DiagLoc = Notes[0].first;
18075 Notes.clear();
18076 }
18077
18078 if (getLangOpts().CPlusPlus) {
18079 if (!Diagnoser.Suppress) {
18080 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18081 for (const PartialDiagnosticAt &Note : Notes)
18082 Diag(Note.first, Note.second);
18083 }
18084 return ExprError();
18085 }
18086
18087 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18088 for (const PartialDiagnosticAt &Note : Notes)
18089 Diag(Note.first, Note.second);
18090
18091 return E;
18092 }
18093
18094 Expr::EvalResult EvalResult;
18096 EvalResult.Diag = &Notes;
18097
18098 // Try to evaluate the expression, and produce diagnostics explaining why it's
18099 // not a constant expression as a side-effect.
18100 bool Folded =
18101 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
18102 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
18103 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
18104
18105 if (!isa<ConstantExpr>(E))
18106 E = ConstantExpr::Create(Context, E, EvalResult.Val);
18107
18108 // In C++11, we can rely on diagnostics being produced for any expression
18109 // which is not a constant expression. If no diagnostics were produced, then
18110 // this is a constant expression.
18111 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18112 if (Result)
18113 *Result = EvalResult.Val.getInt();
18114 return E;
18115 }
18116
18117 // If our only note is the usual "invalid subexpression" note, just point
18118 // the caret at its location rather than producing an essentially
18119 // redundant note.
18120 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18121 diag::note_invalid_subexpr_in_const_expr) {
18122 DiagLoc = Notes[0].first;
18123 Notes.clear();
18124 }
18125
18126 if (!Folded || CanFold == AllowFoldKind::No) {
18127 if (!Diagnoser.Suppress) {
18128 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18129 for (const PartialDiagnosticAt &Note : Notes)
18130 Diag(Note.first, Note.second);
18131 }
18132
18133 return ExprError();
18134 }
18135
18136 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18137 for (const PartialDiagnosticAt &Note : Notes)
18138 Diag(Note.first, Note.second);
18139
18140 if (Result)
18141 *Result = EvalResult.Val.getInt();
18142 return E;
18143}
18144
18145namespace {
18146 // Handle the case where we conclude a expression which we speculatively
18147 // considered to be unevaluated is actually evaluated.
18148 class TransformToPE : public TreeTransform<TransformToPE> {
18149 typedef TreeTransform<TransformToPE> BaseTransform;
18150
18151 public:
18152 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18153
18154 // Make sure we redo semantic analysis
18155 bool AlwaysRebuild() { return true; }
18156 bool ReplacingOriginal() { return true; }
18157
18158 // We need to special-case DeclRefExprs referring to FieldDecls which
18159 // are not part of a member pointer formation; normal TreeTransforming
18160 // doesn't catch this case because of the way we represent them in the AST.
18161 // FIXME: This is a bit ugly; is it really the best way to handle this
18162 // case?
18163 //
18164 // Error on DeclRefExprs referring to FieldDecls.
18165 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18166 if (isa<FieldDecl>(E->getDecl()) &&
18167 !SemaRef.isUnevaluatedContext())
18168 return SemaRef.Diag(E->getLocation(),
18169 diag::err_invalid_non_static_member_use)
18170 << E->getDecl() << E->getSourceRange();
18171
18172 return BaseTransform::TransformDeclRefExpr(E);
18173 }
18174
18175 // Exception: filter out member pointer formation
18176 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18177 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18178 return E;
18179
18180 return BaseTransform::TransformUnaryOperator(E);
18181 }
18182
18183 // The body of a lambda-expression is in a separate expression evaluation
18184 // context so never needs to be transformed.
18185 // FIXME: Ideally we wouldn't transform the closure type either, and would
18186 // just recreate the capture expressions and lambda expression.
18187 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18188 return SkipLambdaBody(E, Body);
18189 }
18190 };
18191}
18192
18194 assert(isUnevaluatedContext() &&
18195 "Should only transform unevaluated expressions");
18196 ExprEvalContexts.back().Context =
18197 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18199 return E;
18200 return TransformToPE(*this).TransformExpr(E);
18201}
18202
18204 assert(isUnevaluatedContext() &&
18205 "Should only transform unevaluated expressions");
18208 return TInfo;
18209 return TransformToPE(*this).TransformType(TInfo);
18210}
18211
18212void
18214 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18216 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
18217 LambdaContextDecl, ExprContext);
18218
18219 // Discarded statements and immediate contexts nested in other
18220 // discarded statements or immediate context are themselves
18221 // a discarded statement or an immediate context, respectively.
18222 ExprEvalContexts.back().InDiscardedStatement =
18224
18225 // C++23 [expr.const]/p15
18226 // An expression or conversion is in an immediate function context if [...]
18227 // it is a subexpression of a manifestly constant-evaluated expression or
18228 // conversion.
18229 const auto &Prev = parentEvaluationContext();
18230 ExprEvalContexts.back().InImmediateFunctionContext =
18231 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18232
18233 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18234 Prev.InImmediateEscalatingFunctionContext;
18235
18236 Cleanup.reset();
18237 if (!MaybeODRUseExprs.empty())
18238 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
18239}
18240
18241void
18245 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18246 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
18247}
18248
18250 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18251 // [expr.const]/p14.1
18252 // An expression or conversion is in an immediate function context if it is
18253 // potentially evaluated and either: its innermost enclosing non-block scope
18254 // is a function parameter scope of an immediate function.
18256 FD && FD->isConsteval()
18258 : NewContext);
18262
18263 Current.InDiscardedStatement = false;
18264
18265 if (FD) {
18266
18267 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18268 // context is nested in an immediate function context, so smaller contexts
18269 // that appear inside immediate functions (like variable initializers) are
18270 // considered to be inside an immediate function context even though by
18271 // themselves they are not immediate function contexts. But when a new
18272 // function is entered, we need to reset this tracking, since the entered
18273 // function might be not an immediate function.
18274
18276 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18277
18278 if (isLambdaMethod(FD))
18280 FD->isConsteval() ||
18281 (isLambdaMethod(FD) && (Parent.isConstantEvaluated() ||
18282 Parent.isImmediateFunctionContext()));
18283 else
18285 }
18286}
18287
18289 TypeSourceInfo *TSI) {
18290 return BuildCXXReflectExpr(CaretCaretLoc, TSI);
18291}
18292
18294 TypeSourceInfo *TSI) {
18295 return CXXReflectExpr::Create(Context, CaretCaretLoc, TSI);
18296}
18297
18298namespace {
18299
18300const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18301 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18302 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
18303 if (E->getOpcode() == UO_Deref)
18304 return CheckPossibleDeref(S, E->getSubExpr());
18305 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
18306 return CheckPossibleDeref(S, E->getBase());
18307 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
18308 return CheckPossibleDeref(S, E->getBase());
18309 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
18310 QualType Inner;
18311 QualType Ty = E->getType();
18312 if (const auto *Ptr = Ty->getAs<PointerType>())
18313 Inner = Ptr->getPointeeType();
18314 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
18315 Inner = Arr->getElementType();
18316 else
18317 return nullptr;
18318
18319 if (Inner->hasAttr(attr::NoDeref))
18320 return E;
18321 }
18322 return nullptr;
18323}
18324
18325} // namespace
18326
18328 for (const Expr *E : Rec.PossibleDerefs) {
18329 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
18330 if (DeclRef) {
18331 const ValueDecl *Decl = DeclRef->getDecl();
18332 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
18333 << Decl->getName() << E->getSourceRange();
18334 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
18335 } else {
18336 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
18337 << E->getSourceRange();
18338 }
18339 }
18340 Rec.PossibleDerefs.clear();
18341}
18342
18345 return;
18346
18347 // Note: ignoring parens here is not justified by the standard rules, but
18348 // ignoring parentheses seems like a more reasonable approach, and this only
18349 // drives a deprecation warning so doesn't affect conformance.
18350 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
18351 if (BO->getOpcode() == BO_Assign) {
18352 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18353 llvm::erase(LHSs, BO->getLHS());
18354 }
18355 }
18356}
18357
18359 assert(getLangOpts().CPlusPlus20 &&
18360 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18361 "Cannot mark an immediate escalating expression outside of an "
18362 "immediate escalating context");
18363 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
18364 Call && Call->getCallee()) {
18365 if (auto *DeclRef =
18366 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18367 DeclRef->setIsImmediateEscalating(true);
18368 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
18369 Ctr->setIsImmediateEscalating(true);
18370 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
18371 DeclRef->setIsImmediateEscalating(true);
18372 } else {
18373 assert(false && "expected an immediately escalating expression");
18374 }
18376 FI->FoundImmediateEscalatingExpression = true;
18377}
18378
18380 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18381 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18384 return E;
18385
18386 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18387 /// It's OK if this fails; we'll also remove this in
18388 /// HandleImmediateInvocations, but catching it here allows us to avoid
18389 /// walking the AST looking for it in simple cases.
18390 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18391 if (auto *DeclRef =
18392 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18393 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18394
18395 // C++23 [expr.const]/p16
18396 // An expression or conversion is immediate-escalating if it is not initially
18397 // in an immediate function context and it is [...] an immediate invocation
18398 // that is not a constant expression and is not a subexpression of an
18399 // immediate invocation.
18400 APValue Cached;
18401 auto CheckConstantExpressionAndKeepResult = [&]() {
18402 Expr::EvalResult Eval;
18403 bool Res = E.get()->EvaluateAsConstantExpr(
18404 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
18405 if (Res && !Eval.DiagEmitted) {
18406 Cached = std::move(Eval.Val);
18407 return true;
18408 }
18409 return false;
18410 };
18411
18412 if (!E.get()->isValueDependent() &&
18413 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18414 !CheckConstantExpressionAndKeepResult()) {
18416 return E;
18417 }
18418
18419 if (Cleanup.exprNeedsCleanups()) {
18420 // Since an immediate invocation is a full expression itself - it requires
18421 // an additional ExprWithCleanups node, but it can participate to a bigger
18422 // full expression which actually requires cleanups to be run after so
18423 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18424 // may discard cleanups for outer expression too early.
18425
18426 // Note that ExprWithCleanups created here must always have empty cleanup
18427 // objects:
18428 // - compound literals do not create cleanup objects in C++ and immediate
18429 // invocations are C++-only.
18430 // - blocks are not allowed inside constant expressions and compiler will
18431 // issue an error if they appear there.
18432 //
18433 // Hence, in correct code any cleanup objects created inside current
18434 // evaluation context must be outside the immediate invocation.
18436 Cleanup.cleanupsHaveSideEffects(), {});
18437 }
18438
18440 getASTContext(), E.get(),
18441 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18442 getASTContext()),
18443 /*IsImmediateInvocation*/ true);
18444 if (Cached.hasValue())
18445 Res->MoveIntoResult(Cached, getASTContext());
18446 /// Value-dependent constant expressions should not be immediately
18447 /// evaluated until they are instantiated.
18448 if (!Res->isValueDependent())
18449 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18450 return Res;
18451}
18452
18456 Expr::EvalResult Eval;
18457 Eval.Diag = &Notes;
18458 ConstantExpr *CE = Candidate.getPointer();
18459 bool Result = CE->EvaluateAsConstantExpr(
18460 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18461 if (!Result || !Notes.empty()) {
18463 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18464 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18465 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18466 FunctionDecl *FD = nullptr;
18467 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18468 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18469 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18470 FD = Call->getConstructor();
18471 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18472 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18473
18474 assert(FD && FD->isImmediateFunction() &&
18475 "could not find an immediate function in this expression");
18476 if (FD->isInvalidDecl())
18477 return;
18478 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18479 << FD << FD->isConsteval();
18480 if (auto Context =
18482 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18483 << Context->Decl;
18484 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18485 }
18486 if (!FD->isConsteval())
18488 for (auto &Note : Notes)
18489 SemaRef.Diag(Note.first, Note.second);
18490 return;
18491 }
18493}
18494
18498 struct ComplexRemove : TreeTransform<ComplexRemove> {
18500 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18503 CurrentII;
18504 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18507 4>::reverse_iterator Current)
18508 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18509 void RemoveImmediateInvocation(ConstantExpr* E) {
18510 auto It = std::find_if(CurrentII, IISet.rend(),
18512 return Elem.getPointer() == E;
18513 });
18514 // It is possible that some subexpression of the current immediate
18515 // invocation was handled from another expression evaluation context. Do
18516 // not handle the current immediate invocation if some of its
18517 // subexpressions failed before.
18518 if (It == IISet.rend()) {
18519 if (SemaRef.FailedImmediateInvocations.contains(E))
18520 CurrentII->setInt(1);
18521 } else {
18522 It->setInt(1); // Mark as deleted
18523 }
18524 }
18525 ExprResult TransformConstantExpr(ConstantExpr *E) {
18526 if (!E->isImmediateInvocation())
18527 return Base::TransformConstantExpr(E);
18528 RemoveImmediateInvocation(E);
18529 return Base::TransformExpr(E->getSubExpr());
18530 }
18531 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18532 /// we need to remove its DeclRefExpr from the DRSet.
18533 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18534 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18535 return Base::TransformCXXOperatorCallExpr(E);
18536 }
18537 /// Base::TransformUserDefinedLiteral doesn't preserve the
18538 /// UserDefinedLiteral node.
18539 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18540 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18541 /// here.
18542 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18543 if (!Init)
18544 return Init;
18545
18546 // We cannot use IgnoreImpCasts because we need to preserve
18547 // full expressions.
18548 while (true) {
18549 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
18550 Init = ICE->getSubExpr();
18551 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
18552 Init = ICE->getSubExpr();
18553 else
18554 break;
18555 }
18556 /// ConstantExprs are the first layer of implicit node to be removed so if
18557 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18558 if (auto *CE = dyn_cast<ConstantExpr>(Init);
18559 CE && CE->isImmediateInvocation())
18560 RemoveImmediateInvocation(CE);
18561 return Base::TransformInitializer(Init, NotCopyInit);
18562 }
18563 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18564 DRSet.erase(E);
18565 return E;
18566 }
18567 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18568 // Do not rebuild lambdas to avoid creating a new type.
18569 // Lambdas have already been processed inside their eval contexts.
18570 return E;
18571 }
18572
18573 // We do not have enough information to transform opaque expressions and
18574 // assume they do not contain immediate subexpressions.
18575 ExprResult TransformOpaqueValueExpr(OpaqueValueExpr *E) { return E; }
18576
18577 bool AlwaysRebuild() { return false; }
18578 bool ReplacingOriginal() { return true; }
18579 bool AllowSkippingCXXConstructExpr() {
18580 bool Res = AllowSkippingFirstCXXConstructExpr;
18581 AllowSkippingFirstCXXConstructExpr = true;
18582 return Res;
18583 }
18584 bool AllowSkippingFirstCXXConstructExpr = true;
18585 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18587
18588 /// CXXConstructExpr with a single argument are getting skipped by
18589 /// TreeTransform in some situtation because they could be implicit. This
18590 /// can only occur for the top-level CXXConstructExpr because it is used
18591 /// nowhere in the expression being transformed therefore will not be rebuilt.
18592 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18593 /// skipping the first CXXConstructExpr.
18594 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18595 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18596
18597 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18598 // The result may not be usable in case of previous compilation errors.
18599 // In this case evaluation of the expression may result in crash so just
18600 // don't do anything further with the result.
18601 if (Res.isUsable()) {
18603 It->getPointer()->setSubExpr(Res.get());
18604 }
18605}
18606
18607static void
18610 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18611 Rec.ReferenceToConsteval.size() == 0) ||
18613 return;
18614
18615 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18616 // [...]
18617 // - the initializer of a variable that is usable in constant expressions or
18618 // has constant initialization.
18619 if (SemaRef.getLangOpts().CPlusPlus23 &&
18620 Rec.ExprContext ==
18622 auto *VD = dyn_cast<VarDecl>(Rec.ManglingContextDecl);
18623 if (VD && (VD->isUsableInConstantExpressions(SemaRef.Context) ||
18624 VD->hasConstantInitialization())) {
18625 // An expression or conversion is in an 'immediate function context' if it
18626 // is potentially evaluated and either:
18627 // [...]
18628 // - it is a subexpression of a manifestly constant-evaluated expression
18629 // or conversion.
18630 return;
18631 }
18632 }
18633
18634 /// When we have more than 1 ImmediateInvocationCandidates or previously
18635 /// failed immediate invocations, we need to check for nested
18636 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18637 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18638 /// invocation.
18639 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18641
18642 /// Prevent sema calls during the tree transform from adding pointers that
18643 /// are already in the sets.
18644 llvm::SaveAndRestore DisableIITracking(
18646
18647 /// Prevent diagnostic during tree transfrom as they are duplicates
18649
18650 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18651 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18652 if (!It->getInt())
18654 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18655 Rec.ReferenceToConsteval.size()) {
18656 struct SimpleRemove : DynamicRecursiveASTVisitor {
18657 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18658 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18659 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18660 DRSet.erase(E);
18661 return DRSet.size();
18662 }
18663 } Visitor(Rec.ReferenceToConsteval);
18664 Visitor.TraverseStmt(
18665 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18666 }
18667 for (auto CE : Rec.ImmediateInvocationCandidates)
18668 if (!CE.getInt())
18670 for (auto *DR : Rec.ReferenceToConsteval) {
18671 // If the expression is immediate escalating, it is not an error;
18672 // The outer context itself becomes immediate and further errors,
18673 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18674 if (DR->isImmediateEscalating())
18675 continue;
18676 auto *FD = cast<FunctionDecl>(DR->getDecl());
18677 const NamedDecl *ND = FD;
18678 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18679 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18680 ND = MD->getParent();
18681
18682 // C++23 [expr.const]/p16
18683 // An expression or conversion is immediate-escalating if it is not
18684 // initially in an immediate function context and it is [...] a
18685 // potentially-evaluated id-expression that denotes an immediate function
18686 // that is not a subexpression of an immediate invocation.
18687 bool ImmediateEscalating = false;
18688 bool IsPotentiallyEvaluated =
18689 Rec.Context ==
18691 Rec.Context ==
18693 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18694 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18695
18697 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18698 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18699 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18700 if (!FD->getBuiltinID())
18701 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18702 if (auto Context =
18704 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18705 << Context->Decl;
18706 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18707 }
18708 if (FD->isImmediateEscalating() && !FD->isConsteval())
18710
18711 } else {
18713 }
18714 }
18715}
18716
18719 if (!Rec.Lambdas.empty()) {
18721 if (!getLangOpts().CPlusPlus20 &&
18722 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18723 Rec.isUnevaluated() ||
18725 unsigned D;
18726 if (Rec.isUnevaluated()) {
18727 // C++11 [expr.prim.lambda]p2:
18728 // A lambda-expression shall not appear in an unevaluated operand
18729 // (Clause 5).
18730 D = diag::err_lambda_unevaluated_operand;
18731 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18732 // C++1y [expr.const]p2:
18733 // A conditional-expression e is a core constant expression unless the
18734 // evaluation of e, following the rules of the abstract machine, would
18735 // evaluate [...] a lambda-expression.
18736 D = diag::err_lambda_in_constant_expression;
18737 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18738 // C++17 [expr.prim.lamda]p2:
18739 // A lambda-expression shall not appear [...] in a template-argument.
18740 D = diag::err_lambda_in_invalid_context;
18741 } else
18742 llvm_unreachable("Couldn't infer lambda error message.");
18743
18744 for (const auto *L : Rec.Lambdas)
18745 Diag(L->getBeginLoc(), D);
18746 }
18747 }
18748
18749 // Append the collected materialized temporaries into previous context before
18750 // exit if the previous also is a lifetime extending context.
18752 parentEvaluationContext().InLifetimeExtendingContext &&
18753 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18756 }
18757
18759 HandleImmediateInvocations(*this, Rec);
18760
18761 // Warn on any volatile-qualified simple-assignments that are not discarded-
18762 // value expressions nor unevaluated operands (those cases get removed from
18763 // this list by CheckUnusedVolatileAssignment).
18764 for (auto *BO : Rec.VolatileAssignmentLHSs)
18765 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18766 << BO->getType();
18767
18768 // When are coming out of an unevaluated context, clear out any
18769 // temporaries that we may have created as part of the evaluation of
18770 // the expression in that context: they aren't relevant because they
18771 // will never be constructed.
18772 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18774 ExprCleanupObjects.end());
18775 Cleanup = Rec.ParentCleanup;
18778 // Otherwise, merge the contexts together.
18779 } else {
18780 Cleanup.mergeFrom(Rec.ParentCleanup);
18781 MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
18782 }
18783
18785
18786 // Pop the current expression evaluation context off the stack.
18787 ExprEvalContexts.pop_back();
18788}
18789
18791 ExprCleanupObjects.erase(
18792 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18793 ExprCleanupObjects.end());
18794 Cleanup.reset();
18795 MaybeODRUseExprs.clear();
18796}
18797
18800 if (Result.isInvalid())
18801 return ExprError();
18802 E = Result.get();
18803 if (!E->getType()->isVariablyModifiedType())
18804 return E;
18806}
18807
18808/// Are we in a context that is potentially constant evaluated per C++20
18809/// [expr.const]p12?
18811 /// C++2a [expr.const]p12:
18812 // An expression or conversion is potentially constant evaluated if it is
18813 switch (SemaRef.ExprEvalContexts.back().Context) {
18816
18817 // -- a manifestly constant-evaluated expression,
18821 // -- a potentially-evaluated expression,
18823 // -- an immediate subexpression of a braced-init-list,
18824
18825 // -- [FIXME] an expression of the form & cast-expression that occurs
18826 // within a templated entity
18827 // -- a subexpression of one of the above that is not a subexpression of
18828 // a nested unevaluated operand.
18829 return true;
18830
18833 // Expressions in this context are never evaluated.
18834 return false;
18835 }
18836 llvm_unreachable("Invalid context");
18837}
18838
18839/// Return true if this function has a calling convention that requires mangling
18840/// in the size of the parameter pack.
18842 // These manglings are only applicable for targets whcih use Microsoft
18843 // mangling scheme for C.
18845 return false;
18846
18847 // If this is C++ and this isn't an extern "C" function, parameters do not
18848 // need to be complete. In this case, C++ mangling will apply, which doesn't
18849 // use the size of the parameters.
18850 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18851 return false;
18852
18853 // Stdcall, fastcall, and vectorcall need this special treatment.
18854 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18855 switch (CC) {
18856 case CC_X86StdCall:
18857 case CC_X86FastCall:
18858 case CC_X86VectorCall:
18859 return true;
18860 default:
18861 break;
18862 }
18863 return false;
18864}
18865
18866/// Require that all of the parameter types of function be complete. Normally,
18867/// parameter types are only required to be complete when a function is called
18868/// or defined, but to mangle functions with certain calling conventions, the
18869/// mangler needs to know the size of the parameter list. In this situation,
18870/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18871/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18872/// result in a linker error. Clang doesn't implement this behavior, and instead
18873/// attempts to error at compile time.
18875 SourceLocation Loc) {
18876 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18877 FunctionDecl *FD;
18878 ParmVarDecl *Param;
18879
18880 public:
18881 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18882 : FD(FD), Param(Param) {}
18883
18884 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18885 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18886 StringRef CCName;
18887 switch (CC) {
18888 case CC_X86StdCall:
18889 CCName = "stdcall";
18890 break;
18891 case CC_X86FastCall:
18892 CCName = "fastcall";
18893 break;
18894 case CC_X86VectorCall:
18895 CCName = "vectorcall";
18896 break;
18897 default:
18898 llvm_unreachable("CC does not need mangling");
18899 }
18900
18901 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18902 << Param->getDeclName() << FD->getDeclName() << CCName;
18903 }
18904 };
18905
18906 for (ParmVarDecl *Param : FD->parameters()) {
18907 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18908 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18909 }
18910}
18911
18912namespace {
18913enum class OdrUseContext {
18914 /// Declarations in this context are not odr-used.
18915 None,
18916 /// Declarations in this context are formally odr-used, but this is a
18917 /// dependent context.
18918 Dependent,
18919 /// Declarations in this context are odr-used but not actually used (yet).
18920 FormallyOdrUsed,
18921 /// Declarations in this context are used.
18922 Used
18923};
18924}
18925
18926/// Are we within a context in which references to resolved functions or to
18927/// variables result in odr-use?
18928static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18931
18932 if (Context.isUnevaluated())
18933 return OdrUseContext::None;
18934
18936 return OdrUseContext::Dependent;
18937
18938 if (Context.isDiscardedStatementContext())
18939 return OdrUseContext::FormallyOdrUsed;
18940
18941 else if (Context.Context ==
18943 return OdrUseContext::FormallyOdrUsed;
18944
18945 return OdrUseContext::Used;
18946}
18947
18949 if (!Func->isConstexpr())
18950 return false;
18951
18952 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18953 return true;
18954
18955 // Lambda conversion operators are never user provided.
18956 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))
18957 return isLambdaConversionOperator(Conv);
18958
18959 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18960 return CCD && CCD->getInheritedConstructor();
18961}
18962
18964 bool MightBeOdrUse) {
18965 assert(Func && "No function?");
18966
18967 Func->setReferenced();
18968
18969 // Recursive functions aren't really used until they're used from some other
18970 // context.
18971 bool IsRecursiveCall = CurContext == Func;
18972
18973 // C++11 [basic.def.odr]p3:
18974 // A function whose name appears as a potentially-evaluated expression is
18975 // odr-used if it is the unique lookup result or the selected member of a
18976 // set of overloaded functions [...].
18977 //
18978 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18979 // can just check that here.
18980 OdrUseContext OdrUse =
18981 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18982 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18983 OdrUse = OdrUseContext::FormallyOdrUsed;
18984
18985 // Trivial default constructors and destructors are never actually used.
18986 // FIXME: What about other special members?
18987 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18988 OdrUse == OdrUseContext::Used) {
18989 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18990 if (Constructor->isDefaultConstructor())
18991 OdrUse = OdrUseContext::FormallyOdrUsed;
18993 OdrUse = OdrUseContext::FormallyOdrUsed;
18994 }
18995
18996 // C++20 [expr.const]p12:
18997 // A function [...] is needed for constant evaluation if it is [...] a
18998 // constexpr function that is named by an expression that is potentially
18999 // constant evaluated
19000 bool NeededForConstantEvaluation =
19003
19004 // Determine whether we require a function definition to exist, per
19005 // C++11 [temp.inst]p3:
19006 // Unless a function template specialization has been explicitly
19007 // instantiated or explicitly specialized, the function template
19008 // specialization is implicitly instantiated when the specialization is
19009 // referenced in a context that requires a function definition to exist.
19010 // C++20 [temp.inst]p7:
19011 // The existence of a definition of a [...] function is considered to
19012 // affect the semantics of the program if the [...] function is needed for
19013 // constant evaluation by an expression
19014 // C++20 [basic.def.odr]p10:
19015 // Every program shall contain exactly one definition of every non-inline
19016 // function or variable that is odr-used in that program outside of a
19017 // discarded statement
19018 // C++20 [special]p1:
19019 // The implementation will implicitly define [defaulted special members]
19020 // if they are odr-used or needed for constant evaluation.
19021 //
19022 // Note that we skip the implicit instantiation of templates that are only
19023 // used in unused default arguments or by recursive calls to themselves.
19024 // This is formally non-conforming, but seems reasonable in practice.
19025 bool NeedDefinition =
19026 !IsRecursiveCall &&
19027 (OdrUse == OdrUseContext::Used ||
19028 (NeededForConstantEvaluation && !Func->isPureVirtual()));
19029
19030 // C++14 [temp.expl.spec]p6:
19031 // If a template [...] is explicitly specialized then that specialization
19032 // shall be declared before the first use of that specialization that would
19033 // cause an implicit instantiation to take place, in every translation unit
19034 // in which such a use occurs
19035 if (NeedDefinition &&
19036 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
19037 Func->getMemberSpecializationInfo()))
19039
19040 if (getLangOpts().CUDA)
19041 CUDA().CheckCall(Loc, Func);
19042
19043 // If we need a definition, try to create one.
19044 if (NeedDefinition && !Func->getBody()) {
19047 dyn_cast<CXXConstructorDecl>(Func)) {
19049 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
19050 if (Constructor->isDefaultConstructor()) {
19051 if (Constructor->isTrivial() &&
19052 !Constructor->hasAttr<DLLExportAttr>())
19053 return;
19055 } else if (Constructor->isCopyConstructor()) {
19057 } else if (Constructor->isMoveConstructor()) {
19059 }
19060 } else if (Constructor->getInheritedConstructor()) {
19062 }
19063 } else if (CXXDestructorDecl *Destructor =
19064 dyn_cast<CXXDestructorDecl>(Func)) {
19066 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
19067 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
19068 return;
19070 }
19071 if (Destructor->isVirtual() && getLangOpts().AppleKext)
19072 MarkVTableUsed(Loc, Destructor->getParent());
19073 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
19074 if (MethodDecl->isOverloadedOperator() &&
19075 MethodDecl->getOverloadedOperator() == OO_Equal) {
19076 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
19077 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
19078 if (MethodDecl->isCopyAssignmentOperator())
19079 DefineImplicitCopyAssignment(Loc, MethodDecl);
19080 else if (MethodDecl->isMoveAssignmentOperator())
19081 DefineImplicitMoveAssignment(Loc, MethodDecl);
19082 }
19083 } else if (isa<CXXConversionDecl>(MethodDecl) &&
19084 MethodDecl->getParent()->isLambda()) {
19085 CXXConversionDecl *Conversion =
19086 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
19087 if (Conversion->isLambdaToBlockPointerConversion())
19089 else
19091 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19092 MarkVTableUsed(Loc, MethodDecl->getParent());
19093 }
19094
19095 if (Func->isDefaulted() && !Func->isDeleted()) {
19099 }
19100
19101 // Implicit instantiation of function templates and member functions of
19102 // class templates.
19103 if (Func->isImplicitlyInstantiable()) {
19105 Func->getTemplateSpecializationKindForInstantiation();
19106 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19107 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19108 if (FirstInstantiation) {
19109 PointOfInstantiation = Loc;
19110 if (auto *MSI = Func->getMemberSpecializationInfo())
19111 MSI->setPointOfInstantiation(Loc);
19112 // FIXME: Notify listener.
19113 else
19114 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19115 } else if (TSK != TSK_ImplicitInstantiation) {
19116 // Use the point of use as the point of instantiation, instead of the
19117 // point of explicit instantiation (which we track as the actual point
19118 // of instantiation). This gives better backtraces in diagnostics.
19119 PointOfInstantiation = Loc;
19120 }
19121
19122 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19123 Func->isConstexpr()) {
19124 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
19125 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
19126 CodeSynthesisContexts.size())
19128 std::make_pair(Func, PointOfInstantiation));
19129 else if (Func->isConstexpr())
19130 // Do not defer instantiations of constexpr functions, to avoid the
19131 // expression evaluator needing to call back into Sema if it sees a
19132 // call to such a function.
19133 InstantiateFunctionDefinition(PointOfInstantiation, Func);
19134 else {
19135 Func->setInstantiationIsPending(true);
19136 PendingInstantiations.push_back(
19137 std::make_pair(Func, PointOfInstantiation));
19138 if (llvm::isTimeTraceVerbose()) {
19139 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
19140 std::string Name;
19141 llvm::raw_string_ostream OS(Name);
19142 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
19143 /*Qualified=*/true);
19144 return Name;
19145 });
19146 }
19147 // Notify the consumer that a function was implicitly instantiated.
19148 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
19149 }
19150 }
19151 } else {
19152 // Walk redefinitions, as some of them may be instantiable.
19153 for (auto *i : Func->redecls()) {
19154 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
19155 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
19156 }
19157 }
19158 });
19159 }
19160
19161 // If a constructor was defined in the context of a default parameter
19162 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19163 // context), its initializers may not be referenced yet.
19164 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
19166 *this,
19167 Constructor->isImmediateFunction()
19170 Constructor);
19171 for (CXXCtorInitializer *Init : Constructor->inits()) {
19172 if (Init->isInClassMemberInitializer())
19173 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
19174 MarkDeclarationsReferencedInExpr(Init->getInit());
19175 });
19176 }
19177 }
19178
19179 // C++14 [except.spec]p17:
19180 // An exception-specification is considered to be needed when:
19181 // - the function is odr-used or, if it appears in an unevaluated operand,
19182 // would be odr-used if the expression were potentially-evaluated;
19183 //
19184 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19185 // function is a pure virtual function we're calling, and in that case the
19186 // function was selected by overload resolution and we need to resolve its
19187 // exception specification for a different reason.
19188 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19190 ResolveExceptionSpec(Loc, FPT);
19191
19192 // A callee could be called by a host function then by a device function.
19193 // If we only try recording once, we will miss recording the use on device
19194 // side. Therefore keep trying until it is recorded.
19195 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19196 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
19198
19199 // If this is the first "real" use, act on that.
19200 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19201 // Keep track of used but undefined functions.
19202 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19203 if (mightHaveNonExternalLinkage(Func))
19204 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19205 else if (Func->getMostRecentDecl()->isInlined() &&
19206 !LangOpts.GNUInline &&
19207 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19208 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19210 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19211 }
19212
19213 // Some x86 Windows calling conventions mangle the size of the parameter
19214 // pack into the name. Computing the size of the parameters requires the
19215 // parameter types to be complete. Check that now.
19218
19219 // In the MS C++ ABI, the compiler emits destructor variants where they are
19220 // used. If the destructor is used here but defined elsewhere, mark the
19221 // virtual base destructors referenced. If those virtual base destructors
19222 // are inline, this will ensure they are defined when emitting the complete
19223 // destructor variant. This checking may be redundant if the destructor is
19224 // provided later in this TU.
19225 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19226 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
19227 CXXRecordDecl *Parent = Dtor->getParent();
19228 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19230 }
19231 }
19232
19233 Func->markUsed(Context);
19234 }
19235}
19236
19237/// Directly mark a variable odr-used. Given a choice, prefer to use
19238/// MarkVariableReferenced since it does additional checks and then
19239/// calls MarkVarDeclODRUsed.
19240/// If the variable must be captured:
19241/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19242/// - else capture it in the DeclContext that maps to the
19243/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19244static void
19246 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19247 // Keep track of used but undefined variables.
19248 // FIXME: We shouldn't suppress this warning for static data members.
19249 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19250 assert(Var && "expected a capturable variable");
19251
19253 (!Var->isExternallyVisible() || Var->isInline() ||
19255 !(Var->isStaticDataMember() && Var->hasInit())) {
19257 if (old.isInvalid())
19258 old = Loc;
19259 }
19260 QualType CaptureType, DeclRefType;
19261 if (SemaRef.LangOpts.OpenMP)
19264 /*EllipsisLoc*/ SourceLocation(),
19265 /*BuildAndDiagnose*/ true, CaptureType,
19266 DeclRefType, FunctionScopeIndexToStopAt);
19267
19268 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19269 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
19270 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
19271 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
19272 if (VarTarget == SemaCUDA::CVT_Host &&
19273 (UserTarget == CUDAFunctionTarget::Device ||
19274 UserTarget == CUDAFunctionTarget::HostDevice ||
19275 UserTarget == CUDAFunctionTarget::Global)) {
19276 // Diagnose ODR-use of host global variables in device functions.
19277 // Reference of device global variables in host functions is allowed
19278 // through shadow variables therefore it is not diagnosed.
19279 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19280 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
19281 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19283 Var->getType().isConstQualified()
19284 ? diag::note_cuda_const_var_unpromoted
19285 : diag::note_cuda_host_var);
19286 }
19287 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19288 // Also capture __device__ const variables, which are classified
19289 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19290 // an explicit CUDADeviceAttr to distinguish them from plain
19291 // const variables (no __device__), which also get CVT_Both but
19292 // only have an implicit CUDADeviceAttr.
19293 (VarTarget == SemaCUDA::CVT_Both &&
19294 Var->hasAttr<CUDADeviceAttr>() &&
19295 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19296 !Var->hasAttr<CUDASharedAttr>() &&
19297 (UserTarget == CUDAFunctionTarget::Host ||
19298 UserTarget == CUDAFunctionTarget::HostDevice)) {
19299 // Record a CUDA/HIP device side variable if it is ODR-used
19300 // by host code. This is done conservatively, when the variable is
19301 // referenced in any of the following contexts:
19302 // - a non-function context
19303 // - a host function
19304 // - a host device function
19305 // This makes the ODR-use of the device side variable by host code to
19306 // be visible in the device compilation for the compiler to be able to
19307 // emit template variables instantiated by host code only and to
19308 // externalize the static device side variable ODR-used by host code.
19309 if (!Var->hasExternalStorage())
19311 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19312 (!FD || (!FD->getDescribedFunctionTemplate() &&
19316 }
19317 }
19318
19319 V->markUsed(SemaRef.Context);
19320}
19321
19323 SourceLocation Loc,
19324 unsigned CapturingScopeIndex) {
19325 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
19326}
19327
19329 SourceLocation loc,
19330 ValueDecl *var) {
19331 DeclContext *VarDC = var->getDeclContext();
19332
19333 // If the parameter still belongs to the translation unit, then
19334 // we're actually just using one parameter in the declaration of
19335 // the next.
19336 if (isa<ParmVarDecl>(var) &&
19338 return;
19339
19340 // For C code, don't diagnose about capture if we're not actually in code
19341 // right now; it's impossible to write a non-constant expression outside of
19342 // function context, so we'll get other (more useful) diagnostics later.
19343 //
19344 // For C++, things get a bit more nasty... it would be nice to suppress this
19345 // diagnostic for certain cases like using a local variable in an array bound
19346 // for a member of a local class, but the correct predicate is not obvious.
19347 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19348 return;
19349
19350 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
19351 unsigned ContextKind = 3; // unknown
19352 if (isa<CXXMethodDecl>(VarDC) &&
19353 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
19354 ContextKind = 2;
19355 } else if (isa<FunctionDecl>(VarDC)) {
19356 ContextKind = 0;
19357 } else if (isa<BlockDecl>(VarDC)) {
19358 ContextKind = 1;
19359 }
19360
19361 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
19362 << var << ValueKind << ContextKind << VarDC;
19363 S.Diag(var->getLocation(), diag::note_entity_declared_at)
19364 << var;
19365
19366 // FIXME: Add additional diagnostic info about class etc. which prevents
19367 // capture.
19368}
19369
19371 ValueDecl *Var,
19372 bool &SubCapturesAreNested,
19373 QualType &CaptureType,
19374 QualType &DeclRefType) {
19375 // Check whether we've already captured it.
19376 if (CSI->CaptureMap.count(Var)) {
19377 // If we found a capture, any subcaptures are nested.
19378 SubCapturesAreNested = true;
19379
19380 // Retrieve the capture type for this variable.
19381 CaptureType = CSI->getCapture(Var).getCaptureType();
19382
19383 // Compute the type of an expression that refers to this variable.
19384 DeclRefType = CaptureType.getNonReferenceType();
19385
19386 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19387 // are mutable in the sense that user can change their value - they are
19388 // private instances of the captured declarations.
19389 const Capture &Cap = CSI->getCapture(Var);
19390 // C++ [expr.prim.lambda]p10:
19391 // The type of such a data member is [...] an lvalue reference to the
19392 // referenced function type if the entity is a reference to a function.
19393 // [...]
19394 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19395 !(isa<LambdaScopeInfo>(CSI) &&
19396 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
19398 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19399 DeclRefType.addConst();
19400 return true;
19401 }
19402 return false;
19403}
19404
19405// Only block literals, captured statements, and lambda expressions can
19406// capture; other scopes don't work.
19408 ValueDecl *Var,
19409 SourceLocation Loc,
19410 const bool Diagnose,
19411 Sema &S) {
19414
19415 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19416 if (Underlying) {
19417 if (Underlying->hasLocalStorage() && Diagnose)
19419 }
19420 return nullptr;
19421}
19422
19423// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19424// certain types of variables (unnamed, variably modified types etc.)
19425// so check for eligibility.
19427 SourceLocation Loc, const bool Diagnose,
19428 Sema &S) {
19429
19430 assert((isa<VarDecl, BindingDecl>(Var)) &&
19431 "Only variables and structured bindings can be captured");
19432
19433 bool IsBlock = isa<BlockScopeInfo>(CSI);
19434 bool IsLambda = isa<LambdaScopeInfo>(CSI);
19435
19436 // Lambdas are not allowed to capture unnamed variables
19437 // (e.g. anonymous unions).
19438 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19439 // assuming that's the intent.
19440 if (IsLambda && !Var->getDeclName()) {
19441 if (Diagnose) {
19442 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19443 S.Diag(Var->getLocation(), diag::note_declared_at);
19444 }
19445 return false;
19446 }
19447
19448 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19449 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19450 if (Diagnose) {
19451 S.Diag(Loc, diag::err_ref_vm_type);
19452 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19453 }
19454 return false;
19455 }
19456 // Prohibit structs with flexible array members too.
19457 // We cannot capture what is in the tail end of the struct.
19458 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19459 VTD && VTD->hasFlexibleArrayMember()) {
19460 if (Diagnose) {
19461 if (IsBlock)
19462 S.Diag(Loc, diag::err_ref_flexarray_type);
19463 else
19464 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19465 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19466 }
19467 return false;
19468 }
19469 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19470 // Lambdas and captured statements are not allowed to capture __block
19471 // variables; they don't support the expected semantics.
19472 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19473 if (Diagnose) {
19474 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19475 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19476 }
19477 return false;
19478 }
19479 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19480 if (S.getLangOpts().OpenCL && IsBlock &&
19481 Var->getType()->isBlockPointerType()) {
19482 if (Diagnose)
19483 S.Diag(Loc, diag::err_opencl_block_ref_block);
19484 return false;
19485 }
19486
19487 if (isa<BindingDecl>(Var)) {
19488 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19489 if (Diagnose)
19491 return false;
19492 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19493 S.Diag(Loc, S.LangOpts.CPlusPlus20
19494 ? diag::warn_cxx17_compat_capture_binding
19495 : diag::ext_capture_binding)
19496 << Var;
19497 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19498 }
19499 }
19500
19501 return true;
19502}
19503
19504// Returns true if the capture by block was successful.
19506 SourceLocation Loc, const bool BuildAndDiagnose,
19507 QualType &CaptureType, QualType &DeclRefType,
19508 const bool Nested, Sema &S, bool Invalid) {
19509 bool ByRef = false;
19510
19511 // Blocks are not allowed to capture arrays, excepting OpenCL.
19512 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19513 // (decayed to pointers).
19514 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19515 if (BuildAndDiagnose) {
19516 S.Diag(Loc, diag::err_ref_array_type);
19517 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19518 Invalid = true;
19519 } else {
19520 return false;
19521 }
19522 }
19523
19524 // Forbid the block-capture of autoreleasing variables.
19525 if (!Invalid &&
19527 if (BuildAndDiagnose) {
19528 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19529 << /*block*/ 0;
19530 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19531 Invalid = true;
19532 } else {
19533 return false;
19534 }
19535 }
19536
19537 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19538 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19539 QualType PointeeTy = PT->getPointeeType();
19540
19541 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19543 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19544 if (BuildAndDiagnose) {
19545 SourceLocation VarLoc = Var->getLocation();
19546 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19547 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19548 }
19549 }
19550 }
19551
19552 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19553 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19554 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
19555 // Block capture by reference does not change the capture or
19556 // declaration reference types.
19557 ByRef = true;
19558 } else {
19559 // Block capture by copy introduces 'const'.
19560 CaptureType = CaptureType.getNonReferenceType().withConst();
19561 DeclRefType = CaptureType;
19562 }
19563
19564 // Actually capture the variable.
19565 if (BuildAndDiagnose)
19566 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19567 CaptureType, Invalid);
19568
19569 return !Invalid;
19570}
19571
19572/// Capture the given variable in the captured region.
19575 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19576 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19577 Sema &S, bool Invalid) {
19578 // By default, capture variables by reference.
19579 bool ByRef = true;
19580 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19581 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19582 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19583 // Using an LValue reference type is consistent with Lambdas (see below).
19584 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
19585 bool HasConst = DeclRefType.isConstQualified();
19586 DeclRefType = DeclRefType.getUnqualifiedType();
19587 // Don't lose diagnostics about assignments to const.
19588 if (HasConst)
19589 DeclRefType.addConst();
19590 }
19591 // Do not capture firstprivates in tasks.
19592 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
19593 RSI->OpenMPCaptureLevel) != OMPC_unknown)
19594 return true;
19595 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19596 RSI->OpenMPCaptureLevel);
19597 }
19598
19599 if (ByRef)
19600 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19601 else
19602 CaptureType = DeclRefType;
19603
19604 // Actually capture the variable.
19605 if (BuildAndDiagnose)
19606 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19607 Loc, SourceLocation(), CaptureType, Invalid);
19608
19609 return !Invalid;
19610}
19611
19612/// Capture the given variable in the lambda.
19614 SourceLocation Loc, const bool BuildAndDiagnose,
19615 QualType &CaptureType, QualType &DeclRefType,
19616 const bool RefersToCapturedVariable,
19617 const TryCaptureKind Kind,
19618 SourceLocation EllipsisLoc, const bool IsTopScope,
19619 Sema &S, bool Invalid) {
19620 // Determine whether we are capturing by reference or by value.
19621 bool ByRef = false;
19622 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19623 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19624 } else {
19625 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19626 }
19627
19628 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19630 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19631 Invalid = true;
19632 }
19633
19634 // Compute the type of the field that will capture this variable.
19635 if (ByRef) {
19636 // C++11 [expr.prim.lambda]p15:
19637 // An entity is captured by reference if it is implicitly or
19638 // explicitly captured but not captured by copy. It is
19639 // unspecified whether additional unnamed non-static data
19640 // members are declared in the closure type for entities
19641 // captured by reference.
19642 //
19643 // FIXME: It is not clear whether we want to build an lvalue reference
19644 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19645 // to do the former, while EDG does the latter. Core issue 1249 will
19646 // clarify, but for now we follow GCC because it's a more permissive and
19647 // easily defensible position.
19648 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19649 } else {
19650 // C++11 [expr.prim.lambda]p14:
19651 // For each entity captured by copy, an unnamed non-static
19652 // data member is declared in the closure type. The
19653 // declaration order of these members is unspecified. The type
19654 // of such a data member is the type of the corresponding
19655 // captured entity if the entity is not a reference to an
19656 // object, or the referenced type otherwise. [Note: If the
19657 // captured entity is a reference to a function, the
19658 // corresponding data member is also a reference to a
19659 // function. - end note ]
19660 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19661 if (!RefType->getPointeeType()->isFunctionType())
19662 CaptureType = RefType->getPointeeType();
19663 }
19664
19665 // Forbid the lambda copy-capture of autoreleasing variables.
19666 if (!Invalid &&
19668 if (BuildAndDiagnose) {
19669 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19670 S.Diag(Var->getLocation(), diag::note_previous_decl)
19671 << Var->getDeclName();
19672 Invalid = true;
19673 } else {
19674 return false;
19675 }
19676 }
19677
19678 // Make sure that by-copy captures are of a complete and non-abstract type.
19679 if (!Invalid && BuildAndDiagnose) {
19680 if (!CaptureType->isDependentType() &&
19682 Loc, CaptureType,
19683 diag::err_capture_of_incomplete_or_sizeless_type,
19684 Var->getDeclName()))
19685 Invalid = true;
19686 else if (S.RequireNonAbstractType(Loc, CaptureType,
19687 diag::err_capture_of_abstract_type))
19688 Invalid = true;
19689 }
19690 }
19691
19692 // Compute the type of a reference to this captured variable.
19693 if (ByRef)
19694 DeclRefType = CaptureType.getNonReferenceType();
19695 else {
19696 // C++ [expr.prim.lambda]p5:
19697 // The closure type for a lambda-expression has a public inline
19698 // function call operator [...]. This function call operator is
19699 // declared const (9.3.1) if and only if the lambda-expression's
19700 // parameter-declaration-clause is not followed by mutable.
19701 DeclRefType = CaptureType.getNonReferenceType();
19702 bool Const = LSI->lambdaCaptureShouldBeConst();
19703 // C++ [expr.prim.lambda]p10:
19704 // The type of such a data member is [...] an lvalue reference to the
19705 // referenced function type if the entity is a reference to a function.
19706 // [...]
19707 if (Const && !CaptureType->isReferenceType() &&
19708 !DeclRefType->isFunctionType())
19709 DeclRefType.addConst();
19710 }
19711
19712 // Add the capture.
19713 if (BuildAndDiagnose)
19714 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19715 Loc, EllipsisLoc, CaptureType, Invalid);
19716
19717 return !Invalid;
19718}
19719
19721 const ASTContext &Context) {
19722 // Offer a Copy fix even if the type is dependent.
19723 if (Var->getType()->isDependentType())
19724 return true;
19726 if (T.isTriviallyCopyableType(Context))
19727 return true;
19728 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19729
19730 if (!(RD = RD->getDefinition()))
19731 return false;
19732 if (RD->hasSimpleCopyConstructor())
19733 return true;
19734 if (RD->hasUserDeclaredCopyConstructor())
19735 for (CXXConstructorDecl *Ctor : RD->ctors())
19736 if (Ctor->isCopyConstructor())
19737 return !Ctor->isDeleted();
19738 }
19739 return false;
19740}
19741
19742/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19743/// default capture. Fixes may be omitted if they aren't allowed by the
19744/// standard, for example we can't emit a default copy capture fix-it if we
19745/// already explicitly copy capture capture another variable.
19747 ValueDecl *Var) {
19749 // Don't offer Capture by copy of default capture by copy fixes if Var is
19750 // known not to be copy constructible.
19751 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19752
19753 SmallString<32> FixBuffer;
19754 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19755 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19756 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19757 if (ShouldOfferCopyFix) {
19758 // Offer fixes to insert an explicit capture for the variable.
19759 // [] -> [VarName]
19760 // [OtherCapture] -> [OtherCapture, VarName]
19761 FixBuffer.assign({Separator, Var->getName()});
19762 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19763 << Var << /*value*/ 0
19764 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19765 }
19766 // As above but capture by reference.
19767 FixBuffer.assign({Separator, "&", Var->getName()});
19768 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19769 << Var << /*reference*/ 1
19770 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19771 }
19772
19773 // Only try to offer default capture if there are no captures excluding this
19774 // and init captures.
19775 // [this]: OK.
19776 // [X = Y]: OK.
19777 // [&A, &B]: Don't offer.
19778 // [A, B]: Don't offer.
19779 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19780 return !C.isThisCapture() && !C.isInitCapture();
19781 }))
19782 return;
19783
19784 // The default capture specifiers, '=' or '&', must appear first in the
19785 // capture body.
19786 SourceLocation DefaultInsertLoc =
19788
19789 if (ShouldOfferCopyFix) {
19790 bool CanDefaultCopyCapture = true;
19791 // [=, *this] OK since c++17
19792 // [=, this] OK since c++20
19793 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19794 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19796 : false;
19797 // We can't use default capture by copy if any captures already specified
19798 // capture by copy.
19799 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19800 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19801 })) {
19802 FixBuffer.assign({"=", Separator});
19803 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19804 << /*value*/ 0
19805 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19806 }
19807 }
19808
19809 // We can't use default capture by reference if any captures already specified
19810 // capture by reference.
19811 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19812 return !C.isInitCapture() && C.isReferenceCapture() &&
19813 !C.isThisCapture();
19814 })) {
19815 FixBuffer.assign({"&", Separator});
19816 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19817 << /*reference*/ 1
19818 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19819 }
19820}
19821
19823 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19824 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19825 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19826 // An init-capture is notionally from the context surrounding its
19827 // declaration, but its parent DC is the lambda class.
19828 DeclContext *VarDC =
19830 DeclContext *DC = CurContext;
19831
19832 // Skip past RequiresExprBodys because they don't constitute function scopes.
19833 while (DC->isRequiresExprBody() || DC->isExpansionStmt())
19834 DC = DC->getParent();
19835
19836 // tryCaptureVariable is called every time a DeclRef is formed,
19837 // it can therefore have non-negigible impact on performances.
19838 // For local variables and when there is no capturing scope,
19839 // we can bailout early.
19840 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19841 return true;
19842
19843 // Exception: Function parameters are not tied to the function's DeclContext
19844 // until we enter the function definition. Capturing them anyway would result
19845 // in an out-of-bounds error while traversing DC and its parents.
19846 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
19847 return true;
19848
19849 const auto *VD = dyn_cast<VarDecl>(Var);
19850 if (VD) {
19851 if (VD->isInitCapture())
19852 VarDC = VarDC->getParent();
19853 } else {
19855 }
19856 assert(VD && "Cannot capture a null variable");
19857
19858 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19859 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19860 // We need to sync up the Declaration Context with the
19861 // FunctionScopeIndexToStopAt
19862 if (FunctionScopeIndexToStopAt) {
19863 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19864 unsigned FSIndex = FunctionScopes.size() - 1;
19865 // When we're parsing the lambda parameter list, the current DeclContext is
19866 // NOT the lambda but its parent. So move away the current LSI before
19867 // aligning DC and FunctionScopeIndexToStopAt.
19868 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
19869 FSIndex && LSI && !LSI->AfterParameterList)
19870 --FSIndex;
19871 assert(MaxFunctionScopesIndex <= FSIndex &&
19872 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19873 "FunctionScopes.");
19874 while (FSIndex != MaxFunctionScopesIndex) {
19876 --FSIndex;
19877 }
19878 }
19879
19880 // Capture global variables if it is required to use private copy of this
19881 // variable.
19882 bool IsGlobal = !VD->hasLocalStorage();
19883 if (IsGlobal && !(LangOpts.OpenMP &&
19884 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19885 MaxFunctionScopesIndex)))
19886 return true;
19887
19888 if (isa<VarDecl>(Var))
19889 Var = cast<VarDecl>(Var->getCanonicalDecl());
19890
19891 // Walk up the stack to determine whether we can capture the variable,
19892 // performing the "simple" checks that don't depend on type. We stop when
19893 // we've either hit the declared scope of the variable or find an existing
19894 // capture of that variable. We start from the innermost capturing-entity
19895 // (the DC) and ensure that all intervening capturing-entities
19896 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19897 // declcontext can either capture the variable or have already captured
19898 // the variable.
19899 CaptureType = Var->getType();
19900 DeclRefType = CaptureType.getNonReferenceType();
19901 bool Nested = false;
19902 bool Explicit = (Kind != TryCaptureKind::Implicit);
19903 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19904 do {
19905
19906 LambdaScopeInfo *LSI = nullptr;
19907 if (!FunctionScopes.empty())
19908 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19909 FunctionScopes[FunctionScopesIndex]);
19910
19911 bool IsInScopeDeclarationContext =
19912 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19913
19914 if (LSI && !LSI->AfterParameterList) {
19915 // This allows capturing parameters from a default value which does not
19916 // seems correct
19917 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19918 return true;
19919 }
19920 // If the variable is declared in the current context, there is no need to
19921 // capture it.
19922 if (IsInScopeDeclarationContext &&
19923 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19924 return true;
19925
19926 // Only block literals, captured statements, and lambda expressions can
19927 // capture; other scopes don't work.
19928 DeclContext *ParentDC =
19929 !IsInScopeDeclarationContext
19930 ? DC->getParent()
19931 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19932 BuildAndDiagnose, *this);
19933 // We need to check for the parent *first* because, if we *have*
19934 // private-captured a global variable, we need to recursively capture it in
19935 // intermediate blocks, lambdas, etc.
19936 if (!ParentDC) {
19937 if (IsGlobal) {
19938 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19939 break;
19940 }
19941 return true;
19942 }
19943
19944 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19946
19947 // Check whether we've already captured it.
19948 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19949 DeclRefType)) {
19950 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19951 break;
19952 }
19953
19954 // When evaluating some attributes (like enable_if) we might refer to a
19955 // function parameter appertaining to the same declaration as that
19956 // attribute.
19957 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19958 Parm && Parm->getDeclContext() == DC)
19959 return true;
19960
19961 // If we are instantiating a generic lambda call operator body,
19962 // we do not want to capture new variables. What was captured
19963 // during either a lambdas transformation or initial parsing
19964 // should be used.
19966 if (BuildAndDiagnose) {
19969 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19970 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19971 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19972 buildLambdaCaptureFixit(*this, LSI, Var);
19973 } else
19975 }
19976 return true;
19977 }
19978
19979 // Try to capture variable-length arrays types.
19980 if (Var->getType()->isVariablyModifiedType()) {
19981 // We're going to walk down into the type and look for VLA
19982 // expressions.
19983 QualType QTy = Var->getType();
19984 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19985 QTy = PVD->getOriginalType();
19987 }
19988
19989 if (getLangOpts().OpenMP) {
19990 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19991 // OpenMP private variables should not be captured in outer scope, so
19992 // just break here. Similarly, global variables that are captured in a
19993 // target region should not be captured outside the scope of the region.
19994 if (RSI->CapRegionKind == CR_OpenMP) {
19995 // FIXME: We should support capturing structured bindings in OpenMP.
19996 if (isa<BindingDecl>(Var)) {
19997 if (BuildAndDiagnose) {
19998 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19999 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
20000 }
20001 return true;
20002 }
20003 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
20004 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
20005 // If the variable is private (i.e. not captured) and has variably
20006 // modified type, we still need to capture the type for correct
20007 // codegen in all regions, associated with the construct. Currently,
20008 // it is captured in the innermost captured region only.
20009 if (IsOpenMPPrivateDecl != OMPC_unknown &&
20010 Var->getType()->isVariablyModifiedType()) {
20011 QualType QTy = Var->getType();
20012 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
20013 QTy = PVD->getOriginalType();
20014 for (int I = 1,
20015 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
20016 I < E; ++I) {
20017 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
20018 FunctionScopes[FunctionScopesIndex - I]);
20019 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
20020 "Wrong number of captured regions associated with the "
20021 "OpenMP construct.");
20022 captureVariablyModifiedType(Context, QTy, OuterRSI);
20023 }
20024 }
20025 bool IsTargetCap =
20026 IsOpenMPPrivateDecl != OMPC_private &&
20027 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
20028 RSI->OpenMPCaptureLevel);
20029 // Do not capture global if it is not privatized in outer regions.
20030 bool IsGlobalCap =
20031 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
20032 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
20033
20034 // When we detect target captures we are looking from inside the
20035 // target region, therefore we need to propagate the capture from the
20036 // enclosing region. Therefore, the capture is not initially nested.
20037 if (IsTargetCap)
20038 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
20039 RSI->OpenMPLevel);
20040
20041 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
20042 (IsGlobal && !IsGlobalCap)) {
20043 Nested = !IsTargetCap;
20044 bool HasConst = DeclRefType.isConstQualified();
20045 DeclRefType = DeclRefType.getUnqualifiedType();
20046 // Don't lose diagnostics about assignments to const.
20047 if (HasConst)
20048 DeclRefType.addConst();
20049 CaptureType = Context.getLValueReferenceType(DeclRefType);
20050 break;
20051 }
20052 }
20053 }
20054 }
20056 // No capture-default, and this is not an explicit capture
20057 // so cannot capture this variable.
20058 if (BuildAndDiagnose) {
20059 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
20060 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
20061 auto *LSI = cast<LambdaScopeInfo>(CSI);
20062 if (LSI->Lambda) {
20063 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
20064 buildLambdaCaptureFixit(*this, LSI, Var);
20065 }
20066 // FIXME: If we error out because an outer lambda can not implicitly
20067 // capture a variable that an inner lambda explicitly captures, we
20068 // should have the inner lambda do the explicit capture - because
20069 // it makes for cleaner diagnostics later. This would purely be done
20070 // so that the diagnostic does not misleadingly claim that a variable
20071 // can not be captured by a lambda implicitly even though it is captured
20072 // explicitly. Suggestion:
20073 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
20074 // at the function head
20075 // - cache the StartingDeclContext - this must be a lambda
20076 // - captureInLambda in the innermost lambda the variable.
20077 }
20078 return true;
20079 }
20080 Explicit = false;
20081 FunctionScopesIndex--;
20082 if (IsInScopeDeclarationContext)
20083 DC = ParentDC;
20084 } while (!VarDC->Equals(DC));
20085
20086 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
20087 // computing the type of the capture at each step, checking type-specific
20088 // requirements, and adding captures if requested.
20089 // If the variable had already been captured previously, we start capturing
20090 // at the lambda nested within that one.
20091 bool Invalid = false;
20092 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
20093 ++I) {
20095
20096 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
20097 // certain types of variables (unnamed, variably modified types etc.)
20098 // so check for eligibility.
20099 if (!Invalid)
20100 Invalid =
20101 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
20102
20103 // After encountering an error, if we're actually supposed to capture, keep
20104 // capturing in nested contexts to suppress any follow-on diagnostics.
20105 if (Invalid && !BuildAndDiagnose)
20106 return true;
20107
20108 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
20109 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20110 DeclRefType, Nested, *this, Invalid);
20111 Nested = true;
20112 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
20114 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
20115 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
20116 Nested = true;
20117 } else {
20119 Invalid =
20120 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20121 DeclRefType, Nested, Kind, EllipsisLoc,
20122 /*IsTopScope*/ I == N - 1, *this, Invalid);
20123 Nested = true;
20124 }
20125
20126 if (Invalid && !BuildAndDiagnose)
20127 return true;
20128 }
20129 return Invalid;
20130}
20131
20133 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20134 QualType CaptureType;
20135 QualType DeclRefType;
20136 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
20137 /*BuildAndDiagnose=*/true, CaptureType,
20138 DeclRefType, nullptr);
20139}
20140
20142 QualType CaptureType;
20143 QualType DeclRefType;
20144 return !tryCaptureVariable(
20146 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);
20147}
20148
20150 assert(Var && "Null value cannot be captured");
20151
20152 QualType CaptureType;
20153 QualType DeclRefType;
20154
20155 // Determine whether we can capture this variable.
20157 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20158 nullptr))
20159 return QualType();
20160
20161 return DeclRefType;
20162}
20163
20164namespace {
20165// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20166// The produced TemplateArgumentListInfo* points to data stored within this
20167// object, so should only be used in contexts where the pointer will not be
20168// used after the CopiedTemplateArgs object is destroyed.
20169class CopiedTemplateArgs {
20170 bool HasArgs;
20171 TemplateArgumentListInfo TemplateArgStorage;
20172public:
20173 template<typename RefExpr>
20174 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20175 if (HasArgs)
20176 E->copyTemplateArgumentsInto(TemplateArgStorage);
20177 }
20178 operator TemplateArgumentListInfo*()
20179#ifdef __has_cpp_attribute
20180#if __has_cpp_attribute(clang::lifetimebound)
20181 [[clang::lifetimebound]]
20182#endif
20183#endif
20184 {
20185 return HasArgs ? &TemplateArgStorage : nullptr;
20186 }
20187};
20188}
20189
20190/// Walk the set of potential results of an expression and mark them all as
20191/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20192///
20193/// \return A new expression if we found any potential results, ExprEmpty() if
20194/// not, and ExprError() if we diagnosed an error.
20196 NonOdrUseReason NOUR) {
20197 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20198 // an object that satisfies the requirements for appearing in a
20199 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20200 // is immediately applied." This function handles the lvalue-to-rvalue
20201 // conversion part.
20202 //
20203 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20204 // transform it into the relevant kind of non-odr-use node and rebuild the
20205 // tree of nodes leading to it.
20206 //
20207 // This is a mini-TreeTransform that only transforms a restricted subset of
20208 // nodes (and only certain operands of them).
20209
20210 // Rebuild a subexpression.
20211 auto Rebuild = [&](Expr *Sub) {
20212 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
20213 };
20214
20215 // Check whether a potential result satisfies the requirements of NOUR.
20216 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20217 // Any entity other than a VarDecl is always odr-used whenever it's named
20218 // in a potentially-evaluated expression.
20219 auto *VD = dyn_cast<VarDecl>(D);
20220 if (!VD)
20221 return true;
20222
20223 // C++2a [basic.def.odr]p4:
20224 // A variable x whose name appears as a potentially-evalauted expression
20225 // e is odr-used by e unless
20226 // -- x is a reference that is usable in constant expressions, or
20227 // -- x is a variable of non-reference type that is usable in constant
20228 // expressions and has no mutable subobjects, and e is an element of
20229 // the set of potential results of an expression of
20230 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20231 // conversion is applied, or
20232 // -- x is a variable of non-reference type, and e is an element of the
20233 // set of potential results of a discarded-value expression to which
20234 // the lvalue-to-rvalue conversion is not applied
20235 //
20236 // We check the first bullet and the "potentially-evaluated" condition in
20237 // BuildDeclRefExpr. We check the type requirements in the second bullet
20238 // in CheckLValueToRValueConversionOperand below.
20239 switch (NOUR) {
20240 case NOUR_None:
20241 case NOUR_Unevaluated:
20242 llvm_unreachable("unexpected non-odr-use-reason");
20243
20244 case NOUR_Constant:
20245 // Constant references were handled when they were built.
20246 if (VD->getType()->isReferenceType())
20247 return true;
20248 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20249 if (RD->hasDefinition() && RD->hasMutableFields())
20250 return true;
20251 if (!VD->isUsableInConstantExpressions(S.Context))
20252 return true;
20253 break;
20254
20255 case NOUR_Discarded:
20256 if (VD->getType()->isReferenceType())
20257 return true;
20258 break;
20259 }
20260 return false;
20261 };
20262
20263 // Check whether this expression may be odr-used in CUDA/HIP.
20264 auto MaybeCUDAODRUsed = [&]() -> bool {
20265 if (!S.LangOpts.CUDA)
20266 return false;
20267 LambdaScopeInfo *LSI = S.getCurLambda();
20268 if (!LSI)
20269 return false;
20270 auto *DRE = dyn_cast<DeclRefExpr>(E);
20271 if (!DRE)
20272 return false;
20273 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
20274 if (!VD)
20275 return false;
20276 return LSI->CUDAPotentialODRUsedVars.count(VD);
20277 };
20278
20279 // Mark that this expression does not constitute an odr-use.
20280 auto MarkNotOdrUsed = [&] {
20281 if (!MaybeCUDAODRUsed()) {
20282 S.MaybeODRUseExprs.remove(E);
20283 if (LambdaScopeInfo *LSI = S.getCurLambda())
20284 LSI->markVariableExprAsNonODRUsed(E);
20285 }
20286 };
20287
20288 // C++2a [basic.def.odr]p2:
20289 // The set of potential results of an expression e is defined as follows:
20290 switch (E->getStmtClass()) {
20291 // -- If e is an id-expression, ...
20292 case Expr::DeclRefExprClass: {
20293 auto *DRE = cast<DeclRefExpr>(E);
20294 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20295 break;
20296
20297 // Rebuild as a non-odr-use DeclRefExpr.
20298 MarkNotOdrUsed();
20299 return DeclRefExpr::Create(
20300 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
20301 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
20302 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
20303 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
20304 }
20305
20306 case Expr::FunctionParmPackExprClass: {
20307 auto *FPPE = cast<FunctionParmPackExpr>(E);
20308 // If any of the declarations in the pack is odr-used, then the expression
20309 // as a whole constitutes an odr-use.
20310 for (ValueDecl *D : *FPPE)
20311 if (IsPotentialResultOdrUsed(D))
20312 return ExprEmpty();
20313
20314 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20315 // nothing cares about whether we marked this as an odr-use, but it might
20316 // be useful for non-compiler tools.
20317 MarkNotOdrUsed();
20318 break;
20319 }
20320
20321 // -- If e is a subscripting operation with an array operand...
20322 case Expr::ArraySubscriptExprClass: {
20323 auto *ASE = cast<ArraySubscriptExpr>(E);
20324 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20325 if (!OldBase->getType()->isArrayType())
20326 break;
20327 ExprResult Base = Rebuild(OldBase);
20328 if (!Base.isUsable())
20329 return Base;
20330 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20331 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20332 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20333 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
20334 ASE->getRBracketLoc());
20335 }
20336
20337 case Expr::MemberExprClass: {
20338 auto *ME = cast<MemberExpr>(E);
20339 // -- If e is a class member access expression [...] naming a non-static
20340 // data member...
20341 if (isa<FieldDecl>(ME->getMemberDecl())) {
20342 ExprResult Base = Rebuild(ME->getBase());
20343 if (!Base.isUsable())
20344 return Base;
20345 return MemberExpr::Create(
20346 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
20347 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
20348 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
20349 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
20350 ME->getObjectKind(), ME->isNonOdrUse());
20351 }
20352
20353 if (ME->getMemberDecl()->isCXXInstanceMember())
20354 break;
20355
20356 // -- If e is a class member access expression naming a static data member,
20357 // ...
20358 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20359 break;
20360
20361 // Rebuild as a non-odr-use MemberExpr.
20362 MarkNotOdrUsed();
20363 return MemberExpr::Create(
20364 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
20365 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
20366 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
20367 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
20368 }
20369
20370 case Expr::BinaryOperatorClass: {
20371 auto *BO = cast<BinaryOperator>(E);
20372 Expr *LHS = BO->getLHS();
20373 Expr *RHS = BO->getRHS();
20374 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20375 if (BO->getOpcode() == BO_PtrMemD) {
20376 ExprResult Sub = Rebuild(LHS);
20377 if (!Sub.isUsable())
20378 return Sub;
20379 BO->setLHS(Sub.get());
20380 // -- If e is a comma expression, ...
20381 } else if (BO->getOpcode() == BO_Comma) {
20382 ExprResult Sub = Rebuild(RHS);
20383 if (!Sub.isUsable())
20384 return Sub;
20385 BO->setRHS(Sub.get());
20386 } else {
20387 break;
20388 }
20389 return ExprResult(BO);
20390 }
20391
20392 // -- If e has the form (e1)...
20393 case Expr::ParenExprClass: {
20394 auto *PE = cast<ParenExpr>(E);
20395 ExprResult Sub = Rebuild(PE->getSubExpr());
20396 if (!Sub.isUsable())
20397 return Sub;
20398 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20399 }
20400
20401 // -- If e is a glvalue conditional expression, ...
20402 // We don't apply this to a binary conditional operator. FIXME: Should we?
20403 case Expr::ConditionalOperatorClass: {
20404 auto *CO = cast<ConditionalOperator>(E);
20405 ExprResult LHS = Rebuild(CO->getLHS());
20406 if (LHS.isInvalid())
20407 return ExprError();
20408 ExprResult RHS = Rebuild(CO->getRHS());
20409 if (RHS.isInvalid())
20410 return ExprError();
20411 if (!LHS.isUsable() && !RHS.isUsable())
20412 return ExprEmpty();
20413 if (!LHS.isUsable())
20414 LHS = CO->getLHS();
20415 if (!RHS.isUsable())
20416 RHS = CO->getRHS();
20417 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20418 CO->getCond(), LHS.get(), RHS.get());
20419 }
20420
20421 // [Clang extension]
20422 // -- If e has the form __extension__ e1...
20423 case Expr::UnaryOperatorClass: {
20424 auto *UO = cast<UnaryOperator>(E);
20425 if (UO->getOpcode() != UO_Extension)
20426 break;
20427 ExprResult Sub = Rebuild(UO->getSubExpr());
20428 if (!Sub.isUsable())
20429 return Sub;
20430 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20431 Sub.get());
20432 }
20433
20434 // [Clang extension]
20435 // -- If e has the form _Generic(...), the set of potential results is the
20436 // union of the sets of potential results of the associated expressions.
20437 case Expr::GenericSelectionExprClass: {
20438 auto *GSE = cast<GenericSelectionExpr>(E);
20439
20440 SmallVector<Expr *, 4> AssocExprs;
20441 bool AnyChanged = false;
20442 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20443 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20444 if (AssocExpr.isInvalid())
20445 return ExprError();
20446 if (AssocExpr.isUsable()) {
20447 AssocExprs.push_back(AssocExpr.get());
20448 AnyChanged = true;
20449 } else {
20450 AssocExprs.push_back(OrigAssocExpr);
20451 }
20452 }
20453
20454 void *ExOrTy = nullptr;
20455 bool IsExpr = GSE->isExprPredicate();
20456 if (IsExpr)
20457 ExOrTy = GSE->getControllingExpr();
20458 else
20459 ExOrTy = GSE->getControllingType();
20460 return AnyChanged ? S.CreateGenericSelectionExpr(
20461 GSE->getGenericLoc(), GSE->getDefaultLoc(),
20462 GSE->getRParenLoc(), IsExpr, ExOrTy,
20463 GSE->getAssocTypeSourceInfos(), AssocExprs)
20464 : ExprEmpty();
20465 }
20466
20467 // [Clang extension]
20468 // -- If e has the form __builtin_choose_expr(...), the set of potential
20469 // results is the union of the sets of potential results of the
20470 // second and third subexpressions.
20471 case Expr::ChooseExprClass: {
20472 auto *CE = cast<ChooseExpr>(E);
20473
20474 ExprResult LHS = Rebuild(CE->getLHS());
20475 if (LHS.isInvalid())
20476 return ExprError();
20477
20478 ExprResult RHS = Rebuild(CE->getLHS());
20479 if (RHS.isInvalid())
20480 return ExprError();
20481
20482 if (!LHS.get() && !RHS.get())
20483 return ExprEmpty();
20484 if (!LHS.isUsable())
20485 LHS = CE->getLHS();
20486 if (!RHS.isUsable())
20487 RHS = CE->getRHS();
20488
20489 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20490 RHS.get(), CE->getRParenLoc());
20491 }
20492
20493 // Step through non-syntactic nodes.
20494 case Expr::ConstantExprClass: {
20495 auto *CE = cast<ConstantExpr>(E);
20496 ExprResult Sub = Rebuild(CE->getSubExpr());
20497 if (!Sub.isUsable())
20498 return Sub;
20499 return ConstantExpr::Create(S.Context, Sub.get());
20500 }
20501
20502 // We could mostly rely on the recursive rebuilding to rebuild implicit
20503 // casts, but not at the top level, so rebuild them here.
20504 case Expr::ImplicitCastExprClass: {
20505 auto *ICE = cast<ImplicitCastExpr>(E);
20506 // Only step through the narrow set of cast kinds we expect to encounter.
20507 // Anything else suggests we've left the region in which potential results
20508 // can be found.
20509 switch (ICE->getCastKind()) {
20510 case CK_NoOp:
20511 case CK_DerivedToBase:
20512 case CK_UncheckedDerivedToBase: {
20513 ExprResult Sub = Rebuild(ICE->getSubExpr());
20514 if (!Sub.isUsable())
20515 return Sub;
20516 CXXCastPath Path(ICE->path());
20517 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20518 ICE->getValueKind(), &Path);
20519 }
20520
20521 default:
20522 break;
20523 }
20524 break;
20525 }
20526
20527 default:
20528 break;
20529 }
20530
20531 // Can't traverse through this node. Nothing to do.
20532 return ExprEmpty();
20533}
20534
20536 // Check whether the operand is or contains an object of non-trivial C union
20537 // type.
20538 if (E->getType().isVolatileQualified() &&
20544
20545 // C++2a [basic.def.odr]p4:
20546 // [...] an expression of non-volatile-qualified non-class type to which
20547 // the lvalue-to-rvalue conversion is applied [...]
20548 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20549 return E;
20550
20553 if (Result.isInvalid())
20554 return ExprError();
20555 return Result.get() ? Result : E;
20556}
20557
20559 if (!Res.isUsable())
20560 return Res;
20561
20562 // If a constant-expression is a reference to a variable where we delay
20563 // deciding whether it is an odr-use, just assume we will apply the
20564 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20565 // (a non-type template argument), we have special handling anyway.
20567}
20568
20570 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20571 // call.
20572 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20573 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20574
20575 for (Expr *E : LocalMaybeODRUseExprs) {
20576 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20577 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20578 DRE->getLocation(), *this);
20579 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20580 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20581 *this);
20582 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20583 for (ValueDecl *VD : *FP)
20584 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20585 } else {
20586 llvm_unreachable("Unexpected expression");
20587 }
20588 }
20589
20590 assert(MaybeODRUseExprs.empty() &&
20591 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20592}
20593
20595 ValueDecl *Var, Expr *E) {
20597 if (!VD)
20598 return;
20599
20600 const bool RefersToEnclosingScope =
20601 (SemaRef.CurContext != VD->getDeclContext() &&
20603 if (RefersToEnclosingScope) {
20604 LambdaScopeInfo *const LSI =
20605 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20606 if (LSI && (!LSI->CallOperator ||
20607 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20608 // If a variable could potentially be odr-used, defer marking it so
20609 // until we finish analyzing the full expression for any
20610 // lvalue-to-rvalue
20611 // or discarded value conversions that would obviate odr-use.
20612 // Add it to the list of potential captures that will be analyzed
20613 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20614 // unless the variable is a reference that was initialized by a constant
20615 // expression (this will never need to be captured or odr-used).
20616 //
20617 // FIXME: We can simplify this a lot after implementing P0588R1.
20618 assert(E && "Capture variable should be used in an expression.");
20619 if (!Var->getType()->isReferenceType() ||
20622 }
20623 }
20624}
20625
20627 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20628 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20629 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20631 "Invalid Expr argument to DoMarkVarDeclReferenced");
20632 Var->setReferenced();
20633
20634 if (Var->isInvalidDecl())
20635 return;
20636
20637 auto *MSI = Var->getMemberSpecializationInfo();
20638 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20640
20641 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20642 bool UsableInConstantExpr =
20644
20645 // Only track variables with internal linkage or local scope.
20646 // Use canonical decl so in-class declarations and out-of-class definitions
20647 // of static data members in anonymous namespaces are tracked as a single
20648 // entry.
20649 const VarDecl *CanonVar = Var->getCanonicalDecl();
20650 if ((CanonVar->isLocalVarDeclOrParm() ||
20651 CanonVar->isInternalLinkageFileVar()) &&
20652 !CanonVar->hasExternalStorage()) {
20653 RefsMinusAssignments.insert({CanonVar, 0}).first->getSecond()++;
20654 }
20655
20656 // C++20 [expr.const]p12:
20657 // A variable [...] is needed for constant evaluation if it is [...] a
20658 // variable whose name appears as a potentially constant evaluated
20659 // expression that is either a contexpr variable or is of non-volatile
20660 // const-qualified integral type or of reference type
20661 bool NeededForConstantEvaluation =
20662 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20663
20664 bool NeedDefinition =
20665 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20666 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20667 Var->getType()->isUndeducedType());
20668
20670 "Can't instantiate a partial template specialization.");
20671
20672 // If this might be a member specialization of a static data member, check
20673 // the specialization is visible. We already did the checks for variable
20674 // template specializations when we created them.
20675 if (NeedDefinition && TSK != TSK_Undeclared &&
20678
20679 // Perform implicit instantiation of static data members, static data member
20680 // templates of class templates, and variable template specializations. Delay
20681 // instantiations of variable templates, except for those that could be used
20682 // in a constant expression.
20683 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20684 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20685 // instantiation declaration if a variable is usable in a constant
20686 // expression (among other cases).
20687 bool TryInstantiating =
20689 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20690
20691 if (TryInstantiating) {
20692 SourceLocation PointOfInstantiation =
20693 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20694 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20695 if (FirstInstantiation) {
20696 PointOfInstantiation = Loc;
20697 if (MSI)
20698 MSI->setPointOfInstantiation(PointOfInstantiation);
20699 // FIXME: Notify listener.
20700 else
20701 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20702 }
20703
20704 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20705 // Do not defer instantiations of variables that could be used in a
20706 // constant expression.
20707 // The type deduction also needs a complete initializer.
20708 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20709 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20710 });
20711
20712 // The size of an incomplete array type can be updated by
20713 // instantiating the initializer. The DeclRefExpr's type should be
20714 // updated accordingly too, or users of it would be confused!
20715 if (E)
20717
20718 // Re-set the member to trigger a recomputation of the dependence bits
20719 // for the expression.
20720 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20721 DRE->setDecl(DRE->getDecl());
20722 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20723 ME->setMemberDecl(ME->getMemberDecl());
20724 } else if (FirstInstantiation) {
20726 .push_back(std::make_pair(Var, PointOfInstantiation));
20727 } else {
20728 bool Inserted = false;
20729 for (auto &I : SemaRef.SavedPendingInstantiations) {
20730 auto Iter = llvm::find_if(
20731 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20732 return P.first == Var;
20733 });
20734 if (Iter != I.end()) {
20735 SemaRef.PendingInstantiations.push_back(*Iter);
20736 I.erase(Iter);
20737 Inserted = true;
20738 break;
20739 }
20740 }
20741
20742 // FIXME: For a specialization of a variable template, we don't
20743 // distinguish between "declaration and type implicitly instantiated"
20744 // and "implicit instantiation of definition requested", so we have
20745 // no direct way to avoid enqueueing the pending instantiation
20746 // multiple times.
20747 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20749 .push_back(std::make_pair(Var, PointOfInstantiation));
20750 }
20751 }
20752 }
20753
20754 // C++2a [basic.def.odr]p4:
20755 // A variable x whose name appears as a potentially-evaluated expression e
20756 // is odr-used by e unless
20757 // -- x is a reference that is usable in constant expressions
20758 // -- x is a variable of non-reference type that is usable in constant
20759 // expressions and has no mutable subobjects [FIXME], and e is an
20760 // element of the set of potential results of an expression of
20761 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20762 // conversion is applied
20763 // -- x is a variable of non-reference type, and e is an element of the set
20764 // of potential results of a discarded-value expression to which the
20765 // lvalue-to-rvalue conversion is not applied [FIXME]
20766 //
20767 // We check the first part of the second bullet here, and
20768 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20769 // FIXME: To get the third bullet right, we need to delay this even for
20770 // variables that are not usable in constant expressions.
20771
20772 // If we already know this isn't an odr-use, there's nothing more to do.
20773 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20774 if (DRE->isNonOdrUse())
20775 return;
20776 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20777 if (ME->isNonOdrUse())
20778 return;
20779
20780 switch (OdrUse) {
20781 case OdrUseContext::None:
20782 // In some cases, a variable may not have been marked unevaluated, if it
20783 // appears in a defaukt initializer.
20784 assert((!E || isa<FunctionParmPackExpr>(E) ||
20786 "missing non-odr-use marking for unevaluated decl ref");
20787 break;
20788
20789 case OdrUseContext::FormallyOdrUsed:
20790 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20791 // behavior.
20792 break;
20793
20794 case OdrUseContext::Used:
20795 // If we might later find that this expression isn't actually an odr-use,
20796 // delay the marking.
20798 SemaRef.MaybeODRUseExprs.insert(E);
20799 else
20800 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20801 break;
20802
20803 case OdrUseContext::Dependent:
20804 // If this is a dependent context, we don't need to mark variables as
20805 // odr-used, but we may still need to track them for lambda capture.
20806 // FIXME: Do we also need to do this inside dependent typeid expressions
20807 // (which are modeled as unevaluated at this point)?
20808 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20809 break;
20810 }
20811}
20812
20814 BindingDecl *BD, Expr *E) {
20815 BD->setReferenced();
20816
20817 if (BD->isInvalidDecl())
20818 return;
20819
20820 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20821 if (OdrUse == OdrUseContext::Used) {
20822 QualType CaptureType, DeclRefType;
20824 /*EllipsisLoc*/ SourceLocation(),
20825 /*BuildAndDiagnose*/ true, CaptureType,
20826 DeclRefType,
20827 /*FunctionScopeIndexToStopAt*/ nullptr);
20828 } else if (OdrUse == OdrUseContext::Dependent) {
20829 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20830 }
20831}
20832
20834 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20835}
20836
20837// C++ [temp.dep.expr]p3:
20838// An id-expression is type-dependent if it contains:
20839// - an identifier associated by name lookup with an entity captured by copy
20840// in a lambda-expression that has an explicit object parameter whose type
20841// is dependent ([dcl.fct]),
20843 Sema &SemaRef, ValueDecl *D, Expr *E) {
20844 auto *ID = dyn_cast<DeclRefExpr>(E);
20845 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20846 return;
20847
20848 // If any enclosing lambda with a dependent explicit object parameter either
20849 // explicitly captures the variable by value, or has a capture default of '='
20850 // and does not capture the variable by reference, then the type of the DRE
20851 // is dependent on the type of that lambda's explicit object parameter.
20852 auto IsDependent = [&]() {
20853 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
20854 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
20855 if (!LSI)
20856 continue;
20857
20858 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
20859 LSI->AfterParameterList)
20860 return false;
20861
20862 const auto *MD = LSI->CallOperator;
20863 if (MD->getType().isNull())
20864 continue;
20865
20866 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20867 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20868 !Ty->getParamType(0)->isDependentType())
20869 continue;
20870
20871 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
20872 if (C->isCopyCapture())
20873 return true;
20874 continue;
20875 }
20876
20877 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20878 return true;
20879 }
20880 return false;
20881 }();
20882
20883 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20884 IsDependent, SemaRef.getASTContext());
20885}
20886
20887static void
20889 bool MightBeOdrUse,
20890 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20893
20894 if (SemaRef.getLangOpts().OpenACC)
20895 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20896
20897 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20899 if (SemaRef.getLangOpts().CPlusPlus)
20901 Var, E);
20902 return;
20903 }
20904
20905 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20907 if (SemaRef.getLangOpts().CPlusPlus)
20909 Decl, E);
20910 return;
20911 }
20912 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20913
20914 // If this is a call to a method via a cast, also mark the method in the
20915 // derived class used in case codegen can devirtualize the call.
20916 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20917 if (!ME)
20918 return;
20919 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20920 if (!MD)
20921 return;
20922 // Only attempt to devirtualize if this is truly a virtual call.
20923 bool IsVirtualCall = MD->isVirtual() &&
20925 if (!IsVirtualCall)
20926 return;
20927
20928 // If it's possible to devirtualize the call, mark the called function
20929 // referenced.
20931 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20932 if (DM)
20933 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20934}
20935
20937 // [basic.def.odr] (CWG 1614)
20938 // A function is named by an expression or conversion [...]
20939 // unless it is a pure virtual function and either the expression is not an
20940 // id-expression naming the function with an explicitly qualified name or
20941 // the expression forms a pointer to member
20942 bool OdrUse = true;
20943 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20944 if (Method->isVirtual() &&
20945 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20946 OdrUse = false;
20947
20948 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20952 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20953 !FD->isDependentContext())
20954 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20955 }
20956 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20958}
20959
20961 // C++11 [basic.def.odr]p2:
20962 // A non-overloaded function whose name appears as a potentially-evaluated
20963 // expression or a member of a set of candidate functions, if selected by
20964 // overload resolution when referred to from a potentially-evaluated
20965 // expression, is odr-used, unless it is a pure virtual function and its
20966 // name is not explicitly qualified.
20967 bool MightBeOdrUse = true;
20969 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20970 if (Method->isPureVirtual())
20971 MightBeOdrUse = false;
20972 }
20973 SourceLocation Loc =
20974 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20975 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20977}
20978
20984
20985/// Perform marking for a reference to an arbitrary declaration. It
20986/// marks the declaration referenced, and performs odr-use checking for
20987/// functions and variables. This method should not be used when building a
20988/// normal expression which refers to a variable.
20990 bool MightBeOdrUse) {
20991 if (MightBeOdrUse) {
20992 if (auto *VD = dyn_cast<VarDecl>(D)) {
20993 MarkVariableReferenced(Loc, VD);
20994 return;
20995 }
20996 }
20997 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20998 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20999 return;
21000 }
21001 D->setReferenced();
21002}
21003
21004namespace {
21005 // Mark all of the declarations used by a type as referenced.
21006 // FIXME: Not fully implemented yet! We need to have a better understanding
21007 // of when we're entering a context we should not recurse into.
21008 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
21009 // TreeTransforms rebuilding the type in a new context. Rather than
21010 // duplicating the TreeTransform logic, we should consider reusing it here.
21011 // Currently that causes problems when rebuilding LambdaExprs.
21012class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
21013 Sema &S;
21014 SourceLocation Loc;
21015
21016public:
21017 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
21018
21019 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
21020};
21021}
21022
21023bool MarkReferencedDecls::TraverseTemplateArgument(
21024 const TemplateArgument &Arg) {
21025 {
21026 // A non-type template argument is a constant-evaluated context.
21027 EnterExpressionEvaluationContext Evaluated(
21030 if (Decl *D = Arg.getAsDecl())
21031 S.MarkAnyDeclReferenced(Loc, D, true);
21032 } else if (Arg.getKind() == TemplateArgument::Expression) {
21034 }
21035 }
21036
21038}
21039
21041 MarkReferencedDecls Marker(*this, Loc);
21042 Marker.TraverseType(T);
21043}
21044
21045namespace {
21046/// Helper class that marks all of the declarations referenced by
21047/// potentially-evaluated subexpressions as "referenced".
21048class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
21049public:
21050 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
21051 bool SkipLocalVariables;
21053
21054 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
21056 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
21057
21058 void visitUsedDecl(SourceLocation Loc, Decl *D) {
21060 }
21061
21062 void Visit(Expr *E) {
21063 if (llvm::is_contained(StopAt, E))
21064 return;
21065 Inherited::Visit(E);
21066 }
21067
21068 void VisitConstantExpr(ConstantExpr *E) {
21069 // Don't mark declarations within a ConstantExpression, as this expression
21070 // will be evaluated and folded to a value.
21071 }
21072
21073 void VisitDeclRefExpr(DeclRefExpr *E) {
21074 // If we were asked not to visit local variables, don't.
21075 if (SkipLocalVariables) {
21076 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
21077 if (VD->hasLocalStorage())
21078 return;
21079 }
21080
21081 // FIXME: This can trigger the instantiation of the initializer of a
21082 // variable, which can cause the expression to become value-dependent
21083 // or error-dependent. Do we need to propagate the new dependence bits?
21085 }
21086
21087 void VisitMemberExpr(MemberExpr *E) {
21089 Visit(E->getBase());
21090 }
21091};
21092} // namespace
21093
21095 bool SkipLocalVariables,
21096 ArrayRef<const Expr*> StopAt) {
21097 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
21098}
21099
21100/// Emit a diagnostic when statements are reachable.
21102 const PartialDiagnostic &PD) {
21103 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
21104 // The initializer of a constexpr variable or of the first declaration of a
21105 // static data member is not syntactically a constant evaluated constant,
21106 // but nonetheless is always required to be a constant expression, so we
21107 // can skip diagnosing.
21108 if (Decl &&
21109 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
21110 Decl->isFirstDecl() && !Decl->isInline())))
21111 return false;
21112
21113 if (Stmts.empty()) {
21114 Diag(Loc, PD);
21115 return true;
21116 }
21117
21118 if (getCurFunction()) {
21119 // This queue flushes after the function is analyzed, by which time an
21120 // ignore-all-warnings region live here is gone, so sample it now. A note
21121 // is not error-class either, so this also drops the notes that accompany a
21122 // skipped warning. They arrive on their own call, out of reach of the
21123 // engine's rule that drops a note whose warning was ignored.
21124 if (Diags.getIgnoreAllWarnings() &&
21125 Diags.getDiagnosticIDs()->isWarningOrExtension(PD.getDiagID()))
21126 return false;
21127 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21128 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21129 return true;
21130 }
21131
21132 // For non-constexpr file-scope variables with reachability context (non-empty
21133 // Stmts), build a CFG for the initializer and check whether the context in
21134 // question is reachable.
21135 if (Decl && Decl->isFileVarDecl()) {
21136 AnalysisWarnings.registerVarDeclWarning(
21137 Decl, sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21138 return true;
21139 }
21140
21141 Diag(Loc, PD);
21142 return true;
21143}
21144
21145/// Emit a diagnostic that describes an effect on the run-time behavior
21146/// of the program being compiled.
21147///
21148/// This routine emits the given diagnostic when the code currently being
21149/// type-checked is "potentially evaluated", meaning that there is a
21150/// possibility that the code will actually be executable. Code in sizeof()
21151/// expressions, code used only during overload resolution, etc., are not
21152/// potentially evaluated. This routine will suppress such diagnostics or,
21153/// in the absolutely nutty case of potentially potentially evaluated
21154/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21155/// later.
21156///
21157/// This routine should be used for all diagnostics that describe the run-time
21158/// behavior of a program, such as passing a non-POD value through an ellipsis.
21159/// Failure to do so will likely result in spurious diagnostics or failures
21160/// during overload resolution or within sizeof/alignof/typeof/typeid.
21162 const PartialDiagnostic &PD) {
21163
21164 if (ExprEvalContexts.back().isDiscardedStatementContext())
21165 return false;
21166
21167 switch (ExprEvalContexts.back().Context) {
21172 // The argument will never be evaluated, so don't complain.
21173 break;
21174
21177 // Relevant diagnostics should be produced by constant evaluation.
21178 break;
21179
21182 return DiagIfReachable(Loc, Stmts, PD);
21183 }
21184
21185 return false;
21186}
21187
21189 const PartialDiagnostic &PD) {
21190 return DiagRuntimeBehavior(
21191 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21192 PD);
21193}
21194
21196 CallExpr *CE, FunctionDecl *FD) {
21197 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21198 return false;
21199
21200 // If we're inside a decltype's expression, don't check for a valid return
21201 // type or construct temporaries until we know whether this is the last call.
21202 if (ExprEvalContexts.back().ExprContext ==
21204 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
21205 return false;
21206 }
21207
21208 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21209 FunctionDecl *FD;
21210 CallExpr *CE;
21211
21212 public:
21213 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21214 : FD(FD), CE(CE) { }
21215
21216 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21217 if (!FD) {
21218 S.Diag(Loc, diag::err_call_incomplete_return)
21219 << T << CE->getSourceRange();
21220 return;
21221 }
21222
21223 S.Diag(Loc, diag::err_call_function_incomplete_return)
21224 << CE->getSourceRange() << FD << T;
21225 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
21226 << FD->getDeclName();
21227 }
21228 } Diagnoser(FD, CE);
21229
21230 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
21231 return true;
21232
21233 return false;
21234}
21235
21236// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21237// will prevent this condition from triggering, which is what we want.
21239 SourceLocation Loc;
21240
21241 unsigned diagnostic = diag::warn_condition_is_assignment;
21242 bool IsOrAssign = false;
21243
21244 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
21245 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21246 return;
21247
21248 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21249
21250 // Greylist some idioms by putting them into a warning subcategory.
21251 if (ObjCMessageExpr *ME
21252 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
21253 Selector Sel = ME->getSelector();
21254
21255 // self = [<foo> init...]
21256 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21257 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21258
21259 // <foo> = [<bar> nextObject]
21260 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
21261 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21262 }
21263
21264 Loc = Op->getOperatorLoc();
21265 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
21266 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21267 return;
21268
21269 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21270 Loc = Op->getOperatorLoc();
21271 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
21272 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
21273 else {
21274 // Not an assignment.
21275 return;
21276 }
21277
21278 Diag(Loc, diagnostic) << E->getSourceRange();
21279
21282 Diag(Loc, diag::note_condition_assign_silence)
21284 << FixItHint::CreateInsertion(Close, ")");
21285
21286 if (IsOrAssign)
21287 Diag(Loc, diag::note_condition_or_assign_to_comparison)
21288 << FixItHint::CreateReplacement(Loc, "!=");
21289 else
21290 Diag(Loc, diag::note_condition_assign_to_comparison)
21291 << FixItHint::CreateReplacement(Loc, "==");
21292}
21293
21295 // Don't warn if the parens came from a macro.
21296 SourceLocation parenLoc = ParenE->getBeginLoc();
21297 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21298 return;
21299 // Don't warn for dependent expressions.
21300 if (ParenE->isTypeDependent())
21301 return;
21302
21303 Expr *E = ParenE->IgnoreParens();
21304 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21305 return;
21306
21307 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
21308 if (opE->getOpcode() == BO_EQ &&
21309 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
21310 == Expr::MLV_Valid) {
21311 SourceLocation Loc = opE->getOperatorLoc();
21312
21313 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
21314 SourceRange ParenERange = ParenE->getSourceRange();
21315 Diag(Loc, diag::note_equality_comparison_silence)
21316 << FixItHint::CreateRemoval(ParenERange.getBegin())
21317 << FixItHint::CreateRemoval(ParenERange.getEnd());
21318 Diag(Loc, diag::note_equality_comparison_to_assign)
21319 << FixItHint::CreateReplacement(Loc, "=");
21320 }
21321}
21322
21324 bool IsConstexpr) {
21326 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
21328
21329 ExprResult result = CheckPlaceholderExpr(E);
21330 if (result.isInvalid()) return ExprError();
21331 E = result.get();
21332
21333 if (!E->isTypeDependent()) {
21334 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21336
21337 if (getLangOpts().CPlusPlus)
21338 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
21339
21341 if (ERes.isInvalid())
21342 return ExprError();
21343 E = ERes.get();
21344
21345 QualType T = E->getType();
21346 if (!T->isScalarType()) { // C99 6.8.4.1p1
21347 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
21348 << T << E->getSourceRange();
21349 return ExprError();
21350 }
21351 CheckBoolLikeConversion(E, Loc);
21352 }
21353
21354 return E;
21355}
21356
21358 Expr *SubExpr, ConditionKind CK,
21359 bool MissingOK) {
21360 // MissingOK indicates whether having no condition expression is valid
21361 // (for loop) or invalid (e.g. while loop).
21362 if (!SubExpr)
21363 return MissingOK ? ConditionResult() : ConditionError();
21364
21366 switch (CK) {
21368 Cond = CheckBooleanCondition(Loc, SubExpr);
21369 break;
21370
21372 // Note: this might produce a FullExpr
21373 Cond = CheckBooleanCondition(Loc, SubExpr, true);
21374 break;
21375
21377 Cond = CheckSwitchCondition(Loc, SubExpr);
21378 break;
21379 }
21380 if (Cond.isInvalid()) {
21381 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
21382 {SubExpr}, PreferredConditionType(CK));
21383 if (!Cond.get())
21384 return ConditionError();
21385 } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))
21386 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
21387
21388 if (!Cond.isUsable())
21389 return ConditionError();
21390
21391 return ConditionResult(*this, nullptr, Cond,
21393}
21394
21395namespace {
21396 /// A visitor for rebuilding a call to an __unknown_any expression
21397 /// to have an appropriate type.
21398 struct RebuildUnknownAnyFunction
21399 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21400
21401 Sema &S;
21402
21403 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21404
21405 ExprResult VisitStmt(Stmt *S) {
21406 llvm_unreachable("unexpected statement!");
21407 }
21408
21409 ExprResult VisitExpr(Expr *E) {
21410 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21411 << E->getSourceRange();
21412 return ExprError();
21413 }
21414
21415 /// Rebuild an expression which simply semantically wraps another
21416 /// expression which it shares the type and value kind of.
21417 template <class T> ExprResult rebuildSugarExpr(T *E) {
21418 ExprResult SubResult = Visit(E->getSubExpr());
21419 if (SubResult.isInvalid()) return ExprError();
21420
21421 Expr *SubExpr = SubResult.get();
21422 E->setSubExpr(SubExpr);
21423 E->setType(SubExpr->getType());
21424 E->setValueKind(SubExpr->getValueKind());
21425 assert(E->getObjectKind() == OK_Ordinary);
21426 return E;
21427 }
21428
21429 ExprResult VisitParenExpr(ParenExpr *E) {
21430 return rebuildSugarExpr(E);
21431 }
21432
21433 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21434 return rebuildSugarExpr(E);
21435 }
21436
21437 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21438 ExprResult SubResult = Visit(E->getSubExpr());
21439 if (SubResult.isInvalid()) return ExprError();
21440
21441 Expr *SubExpr = SubResult.get();
21442 E->setSubExpr(SubExpr);
21443 E->setType(S.Context.getPointerType(SubExpr->getType()));
21444 assert(E->isPRValue());
21445 assert(E->getObjectKind() == OK_Ordinary);
21446 return E;
21447 }
21448
21449 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21450 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21451
21452 E->setType(VD->getType());
21453
21454 assert(E->isPRValue());
21455 if (S.getLangOpts().CPlusPlus &&
21456 !(isa<CXXMethodDecl>(VD) &&
21457 cast<CXXMethodDecl>(VD)->isInstance()))
21459
21460 return E;
21461 }
21462
21463 ExprResult VisitMemberExpr(MemberExpr *E) {
21464 return resolveDecl(E, E->getMemberDecl());
21465 }
21466
21467 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21468 return resolveDecl(E, E->getDecl());
21469 }
21470 };
21471}
21472
21473/// Given a function expression of unknown-any type, try to rebuild it
21474/// to have a function type.
21476 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21477 if (Result.isInvalid()) return ExprError();
21478 return S.DefaultFunctionArrayConversion(Result.get());
21479}
21480
21481namespace {
21482 /// A visitor for rebuilding an expression of type __unknown_anytype
21483 /// into one which resolves the type directly on the referring
21484 /// expression. Strict preservation of the original source
21485 /// structure is not a goal.
21486 struct RebuildUnknownAnyExpr
21487 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21488
21489 Sema &S;
21490
21491 /// The current destination type.
21492 QualType DestType;
21493
21494 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21495 : S(S), DestType(CastType) {}
21496
21497 ExprResult VisitStmt(Stmt *S) {
21498 llvm_unreachable("unexpected statement!");
21499 }
21500
21501 ExprResult VisitExpr(Expr *E) {
21502 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21503 << E->getSourceRange();
21504 return ExprError();
21505 }
21506
21507 ExprResult VisitCallExpr(CallExpr *E);
21508 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21509
21510 /// Rebuild an expression which simply semantically wraps another
21511 /// expression which it shares the type and value kind of.
21512 template <class T> ExprResult rebuildSugarExpr(T *E) {
21513 ExprResult SubResult = Visit(E->getSubExpr());
21514 if (SubResult.isInvalid()) return ExprError();
21515 Expr *SubExpr = SubResult.get();
21516 E->setSubExpr(SubExpr);
21517 E->setType(SubExpr->getType());
21518 E->setValueKind(SubExpr->getValueKind());
21519 assert(E->getObjectKind() == OK_Ordinary);
21520 return E;
21521 }
21522
21523 ExprResult VisitParenExpr(ParenExpr *E) {
21524 return rebuildSugarExpr(E);
21525 }
21526
21527 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21528 return rebuildSugarExpr(E);
21529 }
21530
21531 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21532 const PointerType *Ptr = DestType->getAs<PointerType>();
21533 if (!Ptr) {
21534 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21535 << E->getSourceRange();
21536 return ExprError();
21537 }
21538
21539 if (isa<CallExpr>(E->getSubExpr())) {
21540 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21541 << E->getSourceRange();
21542 return ExprError();
21543 }
21544
21545 assert(E->isPRValue());
21546 assert(E->getObjectKind() == OK_Ordinary);
21547 E->setType(DestType);
21548
21549 // Build the sub-expression as if it were an object of the pointee type.
21550 DestType = Ptr->getPointeeType();
21551 ExprResult SubResult = Visit(E->getSubExpr());
21552 if (SubResult.isInvalid()) return ExprError();
21553 E->setSubExpr(SubResult.get());
21554 return E;
21555 }
21556
21557 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21558
21559 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21560
21561 ExprResult VisitMemberExpr(MemberExpr *E) {
21562 return resolveDecl(E, E->getMemberDecl());
21563 }
21564
21565 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21566 return resolveDecl(E, E->getDecl());
21567 }
21568 };
21569}
21570
21571/// Rebuilds a call expression which yielded __unknown_anytype.
21572ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21573 Expr *CalleeExpr = E->getCallee();
21574
21575 enum FnKind {
21576 FK_MemberFunction,
21577 FK_FunctionPointer,
21578 FK_BlockPointer
21579 };
21580
21581 FnKind Kind;
21582 QualType CalleeType = CalleeExpr->getType();
21583 if (CalleeType == S.Context.BoundMemberTy) {
21585 Kind = FK_MemberFunction;
21586 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21587 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21588 CalleeType = Ptr->getPointeeType();
21589 Kind = FK_FunctionPointer;
21590 } else {
21591 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21592 Kind = FK_BlockPointer;
21593 }
21594 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21595
21596 // Verify that this is a legal result type of a function.
21597 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21598 DestType->isFunctionType()) {
21599 unsigned diagID = diag::err_func_returning_array_function;
21600 if (Kind == FK_BlockPointer)
21601 diagID = diag::err_block_returning_array_function;
21602
21603 S.Diag(E->getExprLoc(), diagID)
21604 << DestType->isFunctionType() << DestType;
21605 return ExprError();
21606 }
21607
21608 // Otherwise, go ahead and set DestType as the call's result.
21609 E->setType(DestType.getNonLValueExprType(S.Context));
21611 assert(E->getObjectKind() == OK_Ordinary);
21612
21613 // Rebuild the function type, replacing the result type with DestType.
21614 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21615 if (Proto) {
21616 // __unknown_anytype(...) is a special case used by the debugger when
21617 // it has no idea what a function's signature is.
21618 //
21619 // We want to build this call essentially under the K&R
21620 // unprototyped rules, but making a FunctionNoProtoType in C++
21621 // would foul up all sorts of assumptions. However, we cannot
21622 // simply pass all arguments as variadic arguments, nor can we
21623 // portably just call the function under a non-variadic type; see
21624 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21625 // However, it turns out that in practice it is generally safe to
21626 // call a function declared as "A foo(B,C,D);" under the prototype
21627 // "A foo(B,C,D,...);". The only known exception is with the
21628 // Windows ABI, where any variadic function is implicitly cdecl
21629 // regardless of its normal CC. Therefore we change the parameter
21630 // types to match the types of the arguments.
21631 //
21632 // This is a hack, but it is far superior to moving the
21633 // corresponding target-specific code from IR-gen to Sema/AST.
21634
21635 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21636 SmallVector<QualType, 8> ArgTypes;
21637 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21638 ArgTypes.reserve(E->getNumArgs());
21639 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21640 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21641 }
21642 ParamTypes = ArgTypes;
21643 }
21644 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21645 Proto->getExtProtoInfo());
21646 } else {
21647 DestType = S.Context.getFunctionNoProtoType(DestType,
21648 FnType->getExtInfo());
21649 }
21650
21651 // Rebuild the appropriate pointer-to-function type.
21652 switch (Kind) {
21653 case FK_MemberFunction:
21654 // Nothing to do.
21655 break;
21656
21657 case FK_FunctionPointer:
21658 DestType = S.Context.getPointerType(DestType);
21659 break;
21660
21661 case FK_BlockPointer:
21662 DestType = S.Context.getBlockPointerType(DestType);
21663 break;
21664 }
21665
21666 // Finally, we can recurse.
21667 ExprResult CalleeResult = Visit(CalleeExpr);
21668 if (!CalleeResult.isUsable()) return ExprError();
21669 E->setCallee(CalleeResult.get());
21670
21671 // Bind a temporary if necessary.
21672 return S.MaybeBindToTemporary(E);
21673}
21674
21675ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21676 // Verify that this is a legal result type of a call.
21677 if (DestType->isArrayType() || DestType->isFunctionType()) {
21678 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21679 << DestType->isFunctionType() << DestType;
21680 return ExprError();
21681 }
21682
21683 // Rewrite the method result type if available.
21684 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21685 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21686 Method->setReturnType(DestType);
21687 }
21688
21689 // Change the type of the message.
21690 E->setType(DestType.getNonReferenceType());
21692
21693 return S.MaybeBindToTemporary(E);
21694}
21695
21696ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21697 // The only case we should ever see here is a function-to-pointer decay.
21698 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21699 assert(E->isPRValue());
21700 assert(E->getObjectKind() == OK_Ordinary);
21701
21702 E->setType(DestType);
21703
21704 // Rebuild the sub-expression as the pointee (function) type.
21705 DestType = DestType->castAs<PointerType>()->getPointeeType();
21706
21707 ExprResult Result = Visit(E->getSubExpr());
21708 if (!Result.isUsable()) return ExprError();
21709
21710 E->setSubExpr(Result.get());
21711 return E;
21712 } else if (E->getCastKind() == CK_LValueToRValue) {
21713 assert(E->isPRValue());
21714 assert(E->getObjectKind() == OK_Ordinary);
21715
21716 assert(isa<BlockPointerType>(E->getType()));
21717
21718 E->setType(DestType);
21719
21720 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21721 DestType = S.Context.getLValueReferenceType(DestType);
21722
21723 ExprResult Result = Visit(E->getSubExpr());
21724 if (!Result.isUsable()) return ExprError();
21725
21726 E->setSubExpr(Result.get());
21727 return E;
21728 } else {
21729 llvm_unreachable("Unhandled cast type!");
21730 }
21731}
21732
21733ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21734 ExprValueKind ValueKind = VK_LValue;
21735 QualType Type = DestType;
21736
21737 // We know how to make this work for certain kinds of decls:
21738
21739 // - functions
21740 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21741 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21742 DestType = Ptr->getPointeeType();
21743 ExprResult Result = resolveDecl(E, VD);
21744 if (Result.isInvalid()) return ExprError();
21745 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21746 VK_PRValue);
21747 }
21748
21749 if (!Type->isFunctionType()) {
21750 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21751 << VD << E->getSourceRange();
21752 return ExprError();
21753 }
21754 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21755 // We must match the FunctionDecl's type to the hack introduced in
21756 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21757 // type. See the lengthy commentary in that routine.
21758 QualType FDT = FD->getType();
21759 const FunctionType *FnType = FDT->castAs<FunctionType>();
21760 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21761 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21762 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21763 SourceLocation Loc = FD->getLocation();
21764 FunctionDecl *NewFD = FunctionDecl::Create(
21765 S.Context, FD->getDeclContext(), Loc, Loc,
21766 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21768 false /*isInlineSpecified*/, FD->hasPrototype(),
21769 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21770
21771 if (FD->getQualifier())
21772 NewFD->setQualifierInfo(FD->getQualifierLoc());
21773
21774 SmallVector<ParmVarDecl*, 16> Params;
21775 for (const auto &AI : FT->param_types()) {
21776 ParmVarDecl *Param =
21777 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21778 Param->setScopeInfo(0, Params.size());
21779 Params.push_back(Param);
21780 }
21781 NewFD->setParams(Params);
21782 DRE->setDecl(NewFD);
21783 VD = DRE->getDecl();
21784 }
21785 }
21786
21787 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21788 if (MD->isInstance()) {
21789 ValueKind = VK_PRValue;
21791 }
21792
21793 // Function references aren't l-values in C.
21794 if (!S.getLangOpts().CPlusPlus)
21795 ValueKind = VK_PRValue;
21796
21797 // - variables
21798 } else if (isa<VarDecl>(VD)) {
21799 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21800 Type = RefTy->getPointeeType();
21801 } else if (Type->isFunctionType()) {
21802 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21803 << VD << E->getSourceRange();
21804 return ExprError();
21805 }
21806
21807 // - nothing else
21808 } else {
21809 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21810 << VD << E->getSourceRange();
21811 return ExprError();
21812 }
21813
21814 // Modifying the declaration like this is friendly to IR-gen but
21815 // also really dangerous.
21816 VD->setType(DestType);
21817 E->setType(Type);
21818 E->setValueKind(ValueKind);
21819 return E;
21820}
21821
21824 ExprValueKind &VK, CXXCastPath &Path) {
21825 // The type we're casting to must be either void or complete.
21826 if (!CastType->isVoidType() &&
21828 diag::err_typecheck_cast_to_incomplete))
21829 return ExprError();
21830
21831 // Rewrite the casted expression from scratch.
21832 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21833 if (!result.isUsable()) return ExprError();
21834
21835 CastExpr = result.get();
21837 CastKind = CK_NoOp;
21838
21839 return CastExpr;
21840}
21841
21843 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21844}
21845
21847 Expr *arg, QualType &paramType) {
21848 // If the syntactic form of the argument is not an explicit cast of
21849 // any sort, just do default argument promotion.
21850 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21851 if (!castArg) {
21853 if (result.isInvalid()) return ExprError();
21854 paramType = result.get()->getType();
21855 return result;
21856 }
21857
21858 // Otherwise, use the type that was written in the explicit cast.
21859 assert(!arg->hasPlaceholderType());
21860 paramType = castArg->getTypeAsWritten();
21861
21862 // Copy-initialize a parameter of that type.
21863 InitializedEntity entity =
21865 /*consumed*/ false);
21866 return PerformCopyInitialization(entity, callLoc, arg);
21867}
21868
21870 Expr *orig = E;
21871 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21872 while (true) {
21873 E = E->IgnoreParenImpCasts();
21874 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21875 E = call->getCallee();
21876 diagID = diag::err_uncasted_call_of_unknown_any;
21877 } else {
21878 break;
21879 }
21880 }
21881
21882 SourceLocation loc;
21883 NamedDecl *d;
21884 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21885 loc = ref->getLocation();
21886 d = ref->getDecl();
21887 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21888 loc = mem->getMemberLoc();
21889 d = mem->getMemberDecl();
21890 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21891 diagID = diag::err_uncasted_call_of_unknown_any;
21892 loc = msg->getSelectorStartLoc();
21893 d = msg->getMethodDecl();
21894 if (!d) {
21895 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21896 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21897 << orig->getSourceRange();
21898 return ExprError();
21899 }
21900 } else {
21901 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21902 << E->getSourceRange();
21903 return ExprError();
21904 }
21905
21906 S.Diag(loc, diagID) << d << orig->getSourceRange();
21907
21908 // Never recoverable.
21909 return ExprError();
21910}
21911
21913 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21914 if (!placeholderType) return E;
21915
21916 switch (placeholderType->getKind()) {
21917 case BuiltinType::UnresolvedTemplate: {
21918 auto *ULE = cast<UnresolvedLookupExpr>(E->IgnoreParens());
21919 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21920 // There's only one FoundDecl for UnresolvedTemplate type. See
21921 // BuildTemplateIdExpr.
21922 NamedDecl *Temp = *ULE->decls_begin();
21923 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
21924
21925 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21926 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21927 // as it models only the unqualified-id case, where this case can clearly be
21928 // qualified. Thus we can't just qualify an assumed template.
21929 TemplateName TN;
21930 if (auto *TD = dyn_cast<TemplateDecl>(Temp))
21931 TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),
21932 TemplateName(TD));
21933 else
21934 TN = Context.getAssumedTemplateName(NameInfo.getName());
21935
21936 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21937 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21938 Diag(Temp->getLocation(), diag::note_referenced_type_template)
21939 << IsTypeAliasTemplateDecl;
21940
21941 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21942 bool HasAnyDependentTA = false;
21943 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21944 HasAnyDependentTA |= Arg.getArgument().isDependent();
21945 TAL.addArgument(Arg);
21946 }
21947
21948 QualType TST;
21949 {
21950 SFINAETrap Trap(*this);
21951 TST = CheckTemplateIdType(
21952 ElaboratedTypeKeyword::None, TN, NameInfo.getBeginLoc(), TAL,
21953 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21954 }
21955 if (TST.isNull())
21956 TST = Context.getTemplateSpecializationType(
21957 ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),
21958 /*CanonicalArgs=*/{},
21959 HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21960 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},
21961 TST);
21962 }
21963
21964 // Overloaded expressions.
21965 case BuiltinType::Overload: {
21966 // Try to resolve a single function template specialization.
21967 // This is obligatory.
21968 ExprResult Result = E;
21970 return Result;
21971
21972 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21973 // leaves Result unchanged on failure.
21974 Result = E;
21976 return Result;
21977
21978 // If that failed, try to recover with a call.
21979 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21980 /*complain*/ true);
21981 return Result;
21982 }
21983
21984 // Bound member functions.
21985 case BuiltinType::BoundMember: {
21986 ExprResult result = E;
21987 const Expr *BME = E->IgnoreParens();
21988 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21989 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21991 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21992 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21993 if (ME->getMemberNameInfo().getName().getNameKind() ==
21995 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21996 }
21997 tryToRecoverWithCall(result, PD,
21998 /*complain*/ true);
21999 return result;
22000 }
22001
22002 // ARC unbridged casts.
22003 case BuiltinType::ARCUnbridgedCast: {
22004 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
22005 ObjC().diagnoseARCUnbridgedCast(realCast);
22006 return realCast;
22007 }
22008
22009 // Expressions of unknown type.
22010 case BuiltinType::UnknownAny:
22011 return diagnoseUnknownAnyExpr(*this, E);
22012
22013 // Pseudo-objects.
22014 case BuiltinType::PseudoObject:
22015 return PseudoObject().checkRValue(E);
22016
22017 case BuiltinType::BuiltinFn: {
22018 // Accept __noop without parens by implicitly converting it to a call expr.
22019 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
22020 if (DRE) {
22021 auto *FD = cast<FunctionDecl>(DRE->getDecl());
22022 unsigned BuiltinID = FD->getBuiltinID();
22023 if (BuiltinID == Builtin::BI__noop) {
22024 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
22025 CK_BuiltinFnToFnPtr)
22026 .get();
22027 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
22030 }
22031
22032 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
22033 // Any use of these other than a direct call is ill-formed as of C++20,
22034 // because they are not addressable functions. In earlier language
22035 // modes, warn and force an instantiation of the real body.
22036 Diag(E->getBeginLoc(),
22038 ? diag::err_use_of_unaddressable_function
22039 : diag::warn_cxx20_compat_use_of_unaddressable_function);
22040 if (FD->isImplicitlyInstantiable()) {
22041 // Require a definition here because a normal attempt at
22042 // instantiation for a builtin will be ignored, and we won't try
22043 // again later. We assume that the definition of the template
22044 // precedes this use.
22046 /*Recursive=*/false,
22047 /*DefinitionRequired=*/true,
22048 /*AtEndOfTU=*/false);
22049 }
22050 // Produce a properly-typed reference to the function.
22051 CXXScopeSpec SS;
22052 SS.Adopt(DRE->getQualifierLoc());
22053 TemplateArgumentListInfo TemplateArgs;
22054 DRE->copyTemplateArgumentsInto(TemplateArgs);
22055 return BuildDeclRefExpr(
22056 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
22057 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
22058 DRE->getTemplateKeywordLoc(),
22059 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
22060 }
22061 }
22062
22063 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
22064 return ExprError();
22065 }
22066
22067 case BuiltinType::IncompleteMatrixIdx: {
22068 auto *MS = cast<MatrixSubscriptExpr>(E->IgnoreParens());
22069 // At this point, we know there was no second [] to complete the operator.
22070 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
22071 if (getLangOpts().HLSL) {
22073 MS->getBase(), MS->getRowIdx(), E->getExprLoc());
22074 }
22075 Diag(MS->getRowIdx()->getBeginLoc(), diag::err_matrix_incomplete_index);
22076 return ExprError();
22077 }
22078
22079 // Expressions of unknown type.
22080 case BuiltinType::ArraySection:
22081 // If we've already diagnosed something on the array section type, we
22082 // shouldn't need to do any further diagnostic here.
22083 if (!E->containsErrors())
22084 Diag(E->getBeginLoc(), diag::err_array_section_use)
22085 << cast<ArraySectionExpr>(E->IgnoreParens())->isOMPArraySection();
22086 return ExprError();
22087
22088 // Expressions of unknown type.
22089 case BuiltinType::OMPArrayShaping:
22090 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
22091
22092 case BuiltinType::OMPIterator:
22093 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
22094
22095 // Everything else should be impossible.
22096#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
22097 case BuiltinType::Id:
22098#include "clang/Basic/OpenCLImageTypes.def"
22099#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
22100 case BuiltinType::Id:
22101#include "clang/Basic/OpenCLExtensionTypes.def"
22102#define SVE_TYPE(Name, Id, SingletonId) \
22103 case BuiltinType::Id:
22104#include "clang/Basic/AArch64ACLETypes.def"
22105#define PPC_VECTOR_TYPE(Name, Id, Size) \
22106 case BuiltinType::Id:
22107#include "clang/Basic/PPCTypes.def"
22108#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22109#include "clang/Basic/RISCVVTypes.def"
22110#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22111#include "clang/Basic/WebAssemblyReferenceTypes.def"
22112#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
22113#include "clang/Basic/AMDGPUTypes.def"
22114#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22115#include "clang/Basic/HLSLIntangibleTypes.def"
22116#define SPIRV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22117#include "clang/Basic/SPIRVTypes.def"
22118#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
22119#define PLACEHOLDER_TYPE(Id, SingletonId)
22120#include "clang/AST/BuiltinTypes.def"
22121 break;
22122 }
22123
22124 llvm_unreachable("invalid placeholder type!");
22125}
22126
22128 if (E->isTypeDependent())
22129 return true;
22131 return E->getType()->isIntegralOrEnumerationType();
22132 return false;
22133}
22134
22136 ArrayRef<Expr *> SubExprs, QualType T) {
22137 if (!Context.getLangOpts().RecoveryAST)
22138 return ExprError();
22139
22140 if (isSFINAEContext())
22141 return ExprError();
22142
22143 if (T.isNull() || T->isUndeducedType() ||
22144 !Context.getLangOpts().RecoveryASTType)
22145 // We don't know the concrete type, fallback to dependent type.
22146 T = Context.DependentTy;
22147
22148 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
22149}
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, 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...
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
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1852
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2936
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:302
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3405
QualType getPointeeType() const
Definition TypeBase.h:3415
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition Expr.cpp:639
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition Expr.cpp:679
bool isMacroDefined(StringRef Id)
IdentifierTable & getIdentifierTable()
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6816
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8585
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8590
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition Type.h:85
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3690
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:3027
bool isAddressSpaceOverlapping(QualType T, const ASTContext &Ctx) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition TypeBase.h:1432
QualType withConst() const
Definition TypeBase.h:1175
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1172
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8501
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8627
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition Type.h:79
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8541
bool isCXX98PODType(const ASTContext &Context) const
Return true if this is a POD type according to the rules of the C++98 standard, regardless of the cur...
Definition Type.cpp:2804
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8686
QualType getCanonicalType() const
Definition TypeBase.h:8553
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8595
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition Type.cpp:3046
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1195
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C.
Definition TypeBase.h:8693
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8574
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1719
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
bool isCanonical() const
Definition TypeBase.h:8558
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1325
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2792
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8666
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8533
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition Type.h:73
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:496
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
void removeObjCLifetime()
Definition TypeBase.h:552
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:728
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:709
void removeAddressSpace()
Definition TypeBase.h:597
void setAddressSpace(LangAS space)
Definition TypeBase.h:592
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:604
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:546
Qualifiers withoutObjCLifetime() const
Definition TypeBase.h:534
Qualifiers withoutObjCGCAttr() const
Definition TypeBase.h:529
LangAS getAddressSpace() const
Definition TypeBase.h:572
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:751
Represents a struct/union/class.
Definition Decl.h:4369
bool hasFlexibleArrayMember() const
Definition Decl.h:4402
field_iterator field_end() const
Definition Decl.h:4575
field_range fields() const
Definition Decl.h:4572
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4557
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition Expr.cpp:5474
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3684
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition Scope.h:414
bool Contains(const Scope &rhs) const
Returns if rhs has a higher scope depth than this.
Definition Scope.h:623
bool isInCFunctionScope() const
isInObjcMethodScope - Return true if this scope is, or is contained, in an C function body.
Definition Scope.h:434
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:473
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isUnarySelector() const
Expr * ExpandAMDGPUPredicateBuiltIn(Expr *CE)
Expand a valid use of the feature identification builtins into its corresponding sequence of instruct...
void AddPotentiallyUnguardedBuiltinUser(FunctionDecl *FD)
Diagnose unguarded usages of AMDGPU builtins and recommend guarding with __builtin_amdgcn_is_invocabl...
bool checkSVETypeSupport(QualType Ty, SourceLocation Loc, const FunctionDecl *FD, const llvm::StringMap< bool > &FeatureMap)
Definition SemaARM.cpp:1768
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void RecordImplicitHostDeviceFuncUsedByDevice(const FunctionDecl *FD)
Record FD if it is a CUDA/HIP implicit host device function used on device side in device compilation...
Definition SemaCUDA.cpp:795
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:208
bool CheckCall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition SemaCUDA.cpp:973
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition SemaCUDA.h:121
@ CVT_Both
Emitted on host side only.
Definition SemaCUDA.h:122
ExprResult ActOnOutParamExpr(ParmVarDecl *Param, Expr *Arg)
void emitLogicalOperatorFixIt(Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
QualType handleVectorBinOpConversion(ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
bool canHaveOverloadedBinOp(QualType Ty, BinaryOperatorKind Opc)
std::optional< ExprResult > tryPerformConstantBufferConversion(Expr *BaseExpr)
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures.
Definition SemaObjC.h:859
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr)
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr)
const DeclContext * getCurObjCLexicalContext() const
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
void diagnoseARCUnbridgedCast(Expr *e)
Given that we saw an expression with the ARCUnbridgedCastTy placeholder type, complain bitterly.
ObjCMethodDecl * LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance)
LookupMethodInQualifiedType - Lookups up a method in protocol qualifier list of a qualified objective...
ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose=true, bool DiagnoseCFAudited=false, BinaryOperatorKind Opc=BO_PtrMemD, bool IsReinterpretCast=false)
Checks for invalid conversions and casts between retainable pointers and other pointer kinds for ARC ...
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod)
Build an ObjC subscript pseudo-object expression, given that that's supported by the runtime.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
void CheckDeclReference(SourceLocation Loc, Expr *E, Decl *D)
ExprResult ActOnArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, Expr *Length, SourceLocation RBLoc)
Checks and creates an Array Section used in an OpenACC construct/clause.
void checkBuiltinReadImage(FunctionDecl *FDecl, CallExpr *Call)
ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig)
Given the potential call expression Call, determine if there is a specialization via the OpenMP decla...
void tryCaptureOpenMPLambdas(ValueDecl *V)
Function tries to capture lambda's captured variables in the OpenMP region before the original lambda...
OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const
Check if the specified variable is used in 'private' clause.
VarDecl * isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo=false, unsigned StopAt=0)
Check if the specified variable is used in one of the private clauses (private, firstprivate,...
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc)
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const
Return true if the provided declaration VD should be captured by reference.
bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified variable is captured by 'target' directive.
bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified global variable must be captured by outer capture regions.
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition SemaOpenMP.h:379
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
const ValueDecl * getOpenMPDeclareMapperVarName() const
ExprResult checkAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS)
ExprResult checkIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op)
Check an increment or decrement of a pseudo-object expression.
ExprResult checkRValue(Expr *E)
void CheckDeviceUseOfDecl(NamedDecl *ND, SourceLocation Loc)
Issues a deferred diagnostic if use of the declaration designated by 'ND' is invalid in a device cont...
Definition SemaSYCL.cpp:225
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8541
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12607
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12651
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7810
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T)
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:869
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1452
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
ExprResult ActOnCXXParenListInitExpr(ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition Sema.h:8294
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13752
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1143
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8344
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
bool isAlwaysConstantEvaluatedContext() const
Definition Sema.h:8262
bool isExternalWithNoLinkageType(const ValueDecl *VD) const
Determine if VD, which must be a variable or function, is an external symbol that nonetheless can't b...
Definition Sema.cpp:970
bool isAttrContext() const
Definition Sema.h:7051
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
ExprResult BuildBoolLiteral(SourceLocation Loc, bool Value)
Build a boolean-typed literal expression.
ExprResult IgnoredValueConversions(Expr *E)
IgnoredValueConversions - Given that an expression's result is syntactically ignored,...
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8337
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9427
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9466
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9435
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition SemaExpr.cpp:417
ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx, SourceLocation RBLoc)
ExprResult ActOnConstantExpression(ExprResult Res)
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool areVectorTypesSameSize(QualType srcType, QualType destType)
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition Sema.h:1537
void ActOnStartStmtExpr()
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec)
Emit a warning for all pending noderef expressions that we recorded.
void ActOnStmtExprError()
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false, ArrayRef< const Expr * > StopAt={})
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
bool BoundsSafetyCheckAssignmentToCountAttrPtr(QualType LHSTy, Expr *RHSExpr, AssignmentAction Action, SourceLocation Loc, const ValueDecl *Assignee, bool ShowFullyQualifiedAssigneeName)
Perform Bounds Safety Semantic checks for assigning to a __counted_by or __counted_by_or_null pointer...
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
void CheckFloatComparison(SourceLocation Loc, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition Sema.h:1253
SemaCUDA & CUDA()
Definition Sema.h:1477
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
Definition Sema.h:7931
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7933
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7932
bool needsRebuildOfDefaultArgOrInit() const
Definition Sema.h:8282
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicCallType::DoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
SourceLocation LocationOfExcessPrecisionNotSatisfied
Definition Sema.h:8424
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1246
Preprocessor & getPreprocessor() const
Definition Sema.h:940
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7029
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2462
QualType GetSignedSizelessVectorType(QualType V)
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of 'this' is actually available in the current context, if it is a potentially ev...
llvm::SmallPtrSet< ConstantExpr *, 4 > FailedImmediateInvocations
Definition Sema.h:8413
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition Sema.h:8325
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex)
llvm::SmallSetVector< Expr *, 4 > MaybeODRUseExprSet
Store a set of either DeclRefExprs or MemberExprs that contain a reference to a variable (constant) t...
Definition Sema.h:6858
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef< QualType > ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit=nullptr)
LookupLiteralOperator - Determine which literal operator should be used for a user-defined literal,...
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2085
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types?
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth)
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, const Designation &Desig, SourceLocation RParenLoc)
SemaSYCL & SYCL()
Definition Sema.h:1562
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:7041
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1757
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc)
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:842
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
ExprResult CheckUnevaluatedOperand(Expr *E)
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Look for instances where it is likely the comma operator is confused with another operator.
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
ASTContext & Context
Definition Sema.h:1310
static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading=false)
To be used for checking whether the arguments being passed to function exceeds the number of paramete...
Definition Sema.h:8249
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
bool DiagIfReachable(SourceLocation Loc, ArrayRef< const Stmt * > Stmts, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the statements's reachability analysis.
bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E)
Perform Bounds Safety semantic checks for uses of invalid uses counted_by or counted_by_or_null point...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:227
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:938
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool CheckCaseExpression(Expr *E)
SemaObjC & ObjC()
Definition Sema.h:1522
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain=false, bool(*IsPlausibleResult)(QualType)=nullptr)
Try to recover by turning the given expression into a call.
Definition Sema.cpp:2972
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
void CleanupVarDeclMarking()
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:763
bool isImmediateFunctionContext() const
Definition Sema.h:8274
ASTContext & getASTContext() const
Definition Sema.h:941
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1083
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition SemaExpr.cpp:773
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
void PopExpressionEvaluationContext()
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:777
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition SemaExpr.cpp:892
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr)
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Sema.h:6176
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6178
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, const Designation &Desig, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1214
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1762
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< TypeSourceInfo * > Types, ArrayRef< Expr * > Exprs)
ControllingExprOrType is either a TypeSourceInfo * or an Expr *.
AssumedTemplateKind
Definition Sema.h:11569
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
SourceRange getExprRange(Expr *E) const
Definition SemaExpr.cpp:514
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
std::optional< ExpressionEvaluationContextRecord::InitializationContext > OutermostDeclarationWithDelayedImmediateInvocations() const
Definition Sema.h:8309
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition SemaStmt.cpp:406
FPOptions & getCurFPFeatures()
Definition Sema.h:936
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8407
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:277
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
@ UPPC_Block
Block expression.
Definition Sema.h:14606
const LangOptions & getLangOpts() const
Definition Sema.h:934
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
void DiagnoseInvalidJumps(Stmt *Body)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2593
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
SemaOpenACC & OpenACC()
Definition Sema.h:1527
ReuseLambdaContextDecl_t
Definition Sema.h:7120
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void MarkExpressionAsImmediateEscalating(Expr *E)
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc)
Produce diagnostics if FD is an aligned allocation or deallocation function that is unavailable.
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E)
Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false)
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
Preprocessor & PP
Definition Sema.h:1309
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition Sema.cpp:2268
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnCXXBoolLiteral - Parse {true,false} literals.
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1308
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2708
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition SemaExpr.cpp:961
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6602
SemaHLSL & HLSL()
Definition Sema.h:1487
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand,...
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition Sema.h:15837
ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr)
Prepare SplattedExpr for a matrix splat operation, adding implicit casts if necessary.
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:216
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
Definition Sema.h:5338
ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc, TypeSourceInfo *TSI)
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition SemaExpr.cpp:78
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Diagnose cases where a scalar was implicitly converted to a vector and diagnose the underlying types.
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any ArgDependent DiagnoseIfAttr...
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7065
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6632
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
SmallVector< std::deque< PendingImplicitInstantiation >, 8 > SavedPendingInstantiations
Definition Sema.h:14151
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition Sema.cpp:884
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1345
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, StringLiteral *BinaryData, StringRef FileName)
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr)
DiagnoseAssignmentEnum - Warn if assignment to enum is a constant integer not in the range of enum va...
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition Sema.h:7062
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2445
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:647
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition Sema.h:8278
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr * > ArgExprs)
ControllingExprOrType is either an opaque pointer coming out of a ParsedType or an Expr *.
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
bool IsAssignConvertCompatible(AssignConvertType ConvTy)
Definition Sema.h:8145
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2663
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1450
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition Sema.h:12678
SemaOpenCL & OpenCL()
Definition Sema.h:1532
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition Sema.h:14160
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8270
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1736
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr, bool ForTypeDeduction=false)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition Sema.h:6861
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
ExprResult TransformToPotentiallyEvaluated(Expr *E)
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef< Expr * > Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14095
SourceManager & getSourceManager() const
Definition Sema.h:939
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
bool CheckVecStepExpr(Expr *E)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckVectorCompareOperands - vector comparisons are a clang extension that operates on extended vecto...
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks, ObjCInterfaceDecl *ClassReceiver)
CallExpr::ADLCallKind ADLCallKind
Definition Sema.h:7574
@ NTCUK_Destruct
Definition Sema.h:4156
@ NTCUK_Copy
Definition Sema.h:4157
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition Sema.h:8423
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
bool anyAltivecTypes(QualType srcType, QualType destType)
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition Sema.cpp:2493
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
QualType CXXCheckConditionalOperands(ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc)
Check the operands of ?
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
MaybeODRUseExprSet MaybeODRUseExprs
Definition Sema.h:6859
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool isSFINAEContext() const
Definition Sema.h:13843
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e....
ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15609
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
void checkUnusedDeclAttributes(Declarator &D)
checkUnusedDeclAttributes - Given a declarator which is not being used to build a declaration,...
ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind)
QualType CheckTemplateIdType(ElaboratedTypeKeyword Keyword, TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, Scope *Scope, bool ForNestedNameSpecifier)
void setFunctionHasBranchProtectedScope()
Definition Sema.cpp:2648
bool isConstantEvaluatedContext() const
Definition Sema.h:2647
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
ASTConsumer & Consumer
Definition Sema.h:1311
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4715
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:7069
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:126
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1350
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14143
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition Sema.h:6803
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6825
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6815
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6830
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6820
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6840
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6809
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6835
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6850
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range)
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Parse a __builtin_astype expression.
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1269
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope.
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition Sema.h:8260
void DiscardCleanupsInEvaluationContext()
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8410
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
SourceManager & SourceMgr
Definition Sema.h:1313
@ TemplateNameIsRequired
Definition Sema.h:11546
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition SemaExpr.cpp:792
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const
Determine whether FD is an aligned allocation or deallocation function that is unavailable.
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1312
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:935
FPOptions CurFPFeatures
Definition Sema.h:1306
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:523
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types?
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc, bool IsExplicit)
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
friend class InitializationSequence
Definition Sema.h:1592
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
void PopDeclContext()
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:6636
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD)
Produce notes explaining why a defaulted function was defined as deleted.
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:646
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
ExprResult ActOnStmtExprResult(ExprResult E)
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2251
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
QualType PreferredConditionType(ConditionKind K) const
Definition Sema.h:8068
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9480
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9486
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9478
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9483
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9494
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9490
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6517
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition Sema.h:14139
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc, ArithConvKind ACK)
Check that the usual arithmetic conversions can be performed on this pair of expressions that might b...
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
static ConditionResult ConditionError()
Definition Sema.h:7917
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ActOnConvertVectorExpr - create a new convert-vector expression from the provided arguments.
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType)
Type-check an expression that's being passed to an __unknown_anytype parameter.
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
SemaPseudoObject & PseudoObject()
Definition Sema.h:1547
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2639
bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy)
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
bool isCheckingDefaultArgumentOrInitializer() const
Definition Sema.h:8286
SemaARM & ARM()
Definition Sema.h:1457
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
SmallVector< std::pair< Scope *, SourceLocation >, 2 > CurrentDefer
Stack of '_Defer' statements that are currently being parsed, as well as the locations of their '_Def...
Definition Sema.h:11076
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8755
ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc)
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition Expr.h:5032
SourceLocation getBeginLoc() const
Definition Expr.h:5077
const DeclContext * getParentContext() const
If the SourceLocExpr has been resolved return the subexpression representing the resolved value.
Definition Expr.h:5073
SourceLocation getEndLoc() const
Definition Expr.h:5078
SourceLocIdentKind getIdentKind() const
Definition Expr.h:5052
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:298
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:309
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition Overload.h:396
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4601
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
StmtClass getStmtClass() const
Definition Stmt.h:1502
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
unsigned getLength() const
Definition Expr.h:1915
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1194
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1888
StringRef getString() const
Definition Expr.h:1873
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3862
bool isUnion() const
Definition Decl.h:3972
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
Exposes information about the current target.
Definition TargetInfo.h:227
virtual bool hasLongDoubleType() const
Determine whether the long double type is supported on this target.
Definition TargetInfo.h:742
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:342
bool shouldUseMicrosoftCCforMangling() const
Should the Microsoft mangling scheme be used for C Calling Convention.
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
Location wrapper for a TemplateArgument.
Represents a template argument.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Represents a C++ template name within the type system.
A template parameter object.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
void setKind(tok::TokenKind K)
Definition Token.h:100
void startToken()
Reset all flags to cleared.
Definition Token.h:187
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
EnsureImmediateInvocationInDefaultArgs & getDerived()
Represents a declaration of a type.
Definition Decl.h:3557
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3591
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition TypeLoc.h:217
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
SourceRange getLocalSourceRange() const
Get the local source range.
Definition TypeLoc.h:160
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2766
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8472
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8483
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1876
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2546
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition TypeBase.h:9178
bool isBlockPointerType() const
Definition TypeBase.h:8758
bool isVoidType() const
Definition TypeBase.h:9110
bool isBooleanType() const
Definition TypeBase.h:9247
bool isObjCBuiltinType() const
Definition TypeBase.h:8968
bool isMFloat8Type() const
Definition TypeBase.h:9135
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition Type.cpp:2000
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9297
bool isIncompleteArrayType() const
Definition TypeBase.h:8845
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition TypeBase.h:9086
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:761
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2177
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9277
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition Type.cpp:2123
bool isVoidPointerType() const
Definition Type.cpp:749
const ComplexType * getAsComplexIntegerType() const
Definition Type.cpp:782
bool isArrayType() const
Definition TypeBase.h:8837
bool isCharType() const
Definition Type.cpp:2197
bool isFunctionPointerType() const
Definition TypeBase.h:8805
bool isArithmeticType() const
Definition Type.cpp:2426
bool isConstantMatrixType() const
Definition TypeBase.h:8905
bool isPointerType() const
Definition TypeBase.h:8738
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9154
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2671
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9404
bool isReferenceType() const
Definition TypeBase.h:8762
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9198
bool isEnumeralType() const
Definition TypeBase.h:8869
bool isScalarType() const
Definition TypeBase.h:9216
bool isVariableArrayType() const
Definition TypeBase.h:8849
bool isSizelessBuiltinType() const
Definition Type.cpp:2627
bool isClkEventT() const
Definition TypeBase.h:8990
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2705
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2160
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8938
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9232
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition Type.cpp:2380
bool isExtVectorType() const
Definition TypeBase.h:8881
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2233
bool isExtVectorBoolType() const
Definition TypeBase.h:8885
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2744
bool isImageType() const
Definition TypeBase.h:9002
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition TypeBase.h:9104
bool isPipeType() const
Definition TypeBase.h:9009
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2864
bool isBitIntType() const
Definition TypeBase.h:9013
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9079
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8861
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2856
bool isAnyComplexType() const
Definition TypeBase.h:8873
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9170
bool isHalfType() const
Definition TypeBase.h:9114
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9186
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2466
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition Type.cpp:2458
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9092
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2314
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2655
bool isQueueT() const
Definition TypeBase.h:8994
bool isMemberPointerType() const
Definition TypeBase.h:8819
bool isAtomicType() const
Definition TypeBase.h:8930
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9260
bool isObjCIdType() const
Definition TypeBase.h:8950
bool isMatrixType() const
Definition TypeBase.h:8901
bool isOverflowBehaviorType() const
Definition TypeBase.h:8909
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2874
bool isComplexIntegerType() const
Definition Type.cpp:767
bool isUnscopedEnumerationType() const
Definition Type.cpp:2190
bool isObjCObjectType() const
Definition TypeBase.h:8921
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition Type.cpp:5371
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9390
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5460
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9253
bool isHLSLResourceRecord() const
Definition Type.cpp:5545
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isDoubleType() const
Definition TypeBase.h:9127
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2531
bool isFunctionType() const
Definition TypeBase.h:8734
bool isObjCObjectPointerType() const
Definition TypeBase.h:8917
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2401
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9212
bool isVectorType() const
Definition TypeBase.h:8877
bool isObjCQualifiedClassType() const
Definition TypeBase.h:8944
bool isObjCClassType() const
Definition TypeBase.h:8956
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2409
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2692
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2995
@ STK_FloatingComplex
Definition TypeBase.h:2838
@ STK_ObjCObjectPointer
Definition TypeBase.h:2832
@ STK_IntegralComplex
Definition TypeBase.h:2837
@ STK_MemberPointer
Definition TypeBase.h:2833
bool isFloatingType() const
Definition Type.cpp:2393
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2336
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:3002
bool isAnyPointerType() const
Definition TypeBase.h:8746
bool isRealType() const
Definition Type.cpp:2415
TypeClass getTypeClass() const
Definition TypeBase.h:2446
bool isSubscriptableVectorType() const
Definition TypeBase.h:8897
bool isSamplerT() const
Definition TypeBase.h:8982
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9337
bool isNullPtrType() const
Definition TypeBase.h:9147
bool isRecordType() const
Definition TypeBase.h:8865
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5549
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition Type.cpp:772
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5160
bool isUnicodeCharacterType() const
Definition Type.cpp:2253
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Definition Type.cpp:2448
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
std::string getAsString(const LangOptions &LO) const
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
DeclClass * getCorrectionDeclAs() const
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2631
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
void setSubExpr(Expr *E)
Definition Expr.h:2292
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition Expr.h:2295
Expr * getSubExpr() const
Definition Expr.h:2291
Opcode getOpcode() const
Definition Expr.h:2286
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1436
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2346
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5165
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4481
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1088
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1176
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1170
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1140
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3389
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:437
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4125
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition ExprCXX.cpp:1689
bool isImplicitAccess() const
True if this is an implicit access, i.e., one in which the member being accessed was not written in t...
Definition ExprCXX.cpp:1651
A set of unresolved declarations.
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition ExprCXX.h:643
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:4963
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5581
VarDecl * getPotentiallyDecomposedVarDecl()
Definition DeclCXX.cpp:3695
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:932
bool hasInit() const
Definition Decl.cpp:2379
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2238
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1602
bool isInternalLinkageFileVar() const
Returns true if this is a file-scope variable with internal linkage.
Definition Decl.h:1222
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1306
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1247
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition Decl.cpp:2467
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition Decl.cpp:2870
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1575
const Expr * getInit() const
Definition Decl.h:1391
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1238
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1190
@ TLS_None
Not a TLS variable.
Definition Decl.h:952
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1318
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2356
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition Decl.cpp:2509
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2763
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1285
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2742
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2861
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4077
Expr * getSizeExpr() const
Definition TypeBase.h:4091
Represents a GCC generic vector type.
Definition TypeBase.h:4286
unsigned getNumElements() const
Definition TypeBase.h:4301
VectorKind getVectorKind() const
Definition TypeBase.h:4306
QualType getElementType() const
Definition TypeBase.h:4300
Retains information about a block that is currently being parsed.
Definition ScopeInfo.h:791
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition ScopeInfo.h:797
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition ScopeInfo.h:801
ValueDecl * getVariable() const
Definition ScopeInfo.h:676
bool isBlockCapture() const
Definition ScopeInfo.h:657
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:687
void markUsed(bool IsODRUse)
Definition ScopeInfo.h:669
bool isInvalid() const
Definition ScopeInfo.h:662
bool isThisCapture() const
Definition ScopeInfo.h:650
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition ScopeInfo.h:696
bool isCopyCapture() const
Definition ScopeInfo.h:655
bool isNested() const
Definition ScopeInfo.h:660
Retains information about a captured region.
Definition ScopeInfo.h:817
unsigned short CapRegionKind
The kind of captured region.
Definition ScopeInfo.h:832
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:746
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:733
bool ContainsUnexpandedParameterPack
Whether this contains an unexpanded parameter pack.
Definition ScopeInfo.h:729
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:722
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:709
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of 'this'; zero if 'this' is not captured.
Definition ScopeInfo.h:719
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition ScopeInfo.h:759
llvm::DenseMap< ValueDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition ScopeInfo.h:715
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:756
bool isVLATypeCaptured(const VariableArrayType *VAT) const
Determine whether the given variable-array type has been captured.
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:738
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition ScopeInfo.h:772
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
void recordUseOfWeak(const ExprT *E, bool IsRead=true)
Record that a weak object was accessed.
Definition ScopeInfo.h:1093
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
void addBlock(const BlockDecl *BD)
Definition ScopeInfo.h:494
llvm::SmallVector< AddrLabelExpr *, 4 > AddrLabels
The set of GNU address of label extension "&&label".
Definition ScopeInfo.h:251
bool HasOMPDeclareReductionCombiner
True if current scope is for OpenMP declare reduction combiner.
Definition ScopeInfo.h:135
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:887
bool lambdaCaptureShouldBeConst() const
void addPotentialCapture(Expr *VarExpr)
Add a variable that might potentially be captured by the lambda and therefore the enclosing lambdas.
Definition ScopeInfo.h:995
void addPotentialThisCapture(SourceLocation Loc)
Definition ScopeInfo.h:1001
llvm::SmallPtrSet< VarDecl *, 4 > CUDAPotentialODRUsedVars
Variables that are potentially ODR-used in CUDA/HIP.
Definition ScopeInfo.h:956
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:872
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition ScopeInfo.h:895
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:880
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:875
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:35
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition TokenKinds.h:101
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
The JSON file list parser is used to communicate input to InstallAPI.
const char * getTraitSpelling(TypeTrait T) LLVM_READONLY
Return the spelling of the trait T. Never null.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:213
@ CPlusPlus23
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus26
@ CPlusPlus17
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ GVA_StrongExternal
Definition Linkage.h:76
VariadicCallType
Definition Sema.h:513
bool isTargetAddressSpace(LangAS AS)
CUDAFunctionTarget
Definition Cuda.h:65
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
TryCaptureKind
Definition Sema.h:653
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition Sema.h:661
@ BitwiseOp
A bitwise operation.
Definition Sema.h:665
@ Arithmetic
An arithmetic operation.
Definition Sema.h:663
@ Conditional
A conditional (?:) operator.
Definition Sema.h:669
@ CompAssign
A compound assignment expression.
Definition Sema.h:671
@ Comparison
A comparison.
Definition Sema.h:667
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:349
@ Nullable
Values of this type can be null.
Definition Specifiers.h:353
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:358
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:351
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:150
@ OK_VectorComponent
A vector component is an element or range of elements of a vector.
Definition Specifiers.h:158
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition Specifiers.h:162
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition Specifiers.h:155
@ OK_MatrixComponent
A matrix component is a single element or range of elements of a matrix.
Definition Specifiers.h:170
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1082
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1080
@ AS_none
Definition Specifiers.h:128
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ CR_OpenMP
@ SC_Extern
Definition Specifiers.h:252
@ SC_Register
Definition Specifiers.h:258
@ SC_None
Definition Specifiers.h:251
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
unsigned toTargetAddressSpace(LangAS AS)
ExprResult ExprEmpty()
Definition Ownership.h:272
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:205
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_Identity
Identity conversion (no conversion)
Definition Overload.h:106
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition Overload.h:136
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition Overload.h:115
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:689
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:712
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition Sema.h:787
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition Sema.h:704
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition Sema.h:759
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition Sema.h:749
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition Sema.h:776
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition Sema.h:763
@ CompatibleOBTDiscards
CompatibleOBTDiscards - Assignment discards overflow behavior.
Definition Sema.h:783
@ IncompatibleOBTKinds
IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType kinds, e....
Definition Sema.h:780
@ CompatibleVoidPtrToNonVoidPtr
CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because a void * can implicitly convert...
Definition Sema.h:696
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition Sema.h:738
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:733
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition Sema.h:772
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:691
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition Sema.h:723
@ IncompatiblePointerDiscardsOverflowBehavior
IncompatiblePointerDiscardsOverflowBehavior - The assignment discards overflow behavior annotations b...
Definition Sema.h:743
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition Sema.h:700
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition Sema.h:708
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition Sema.h:755
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition Sema.h:717
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:729
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition Sema.h:767
bool isFunctionLocalStringLiteralMacro(tok::TokenKind K, const LangOptions &LO)
Return true if the token corresponds to a function local predefined macro, which expands to a string ...
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:564
@ AR_Unavailable
Definition DeclBase.h:76
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
AllowFoldKind
Definition Sema.h:655
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
VarArgKind
Definition Sema.h:676
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition ASTLambda.h:69
AssignmentAction
Definition Sema.h:216
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Concept_template
The name refers to a concept.
BuiltinCountedByRefKind
Definition Sema.h:521
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
@ CA_ToLiteralEncoding
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:276
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:282
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:290
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:279
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:286
StringLiteralKind
Definition Expr.h:1769
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:189
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:203
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_X86VectorCall
Definition Specifiers.h:284
@ CC_X86StdCall
Definition Specifiers.h:281
@ CC_X86FastCall
Definition Specifiers.h:282
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4256
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4265
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4250
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4253
@ Neon
is ARM Neon vector
Definition TypeBase.h:4259
@ Generic
not a target-specific vector type
Definition TypeBase.h:4247
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4271
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4274
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4268
U cast(CodeGen::Address addr)
Definition Address.h:327
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
SourceLocIdentKind
Definition Expr.h:5019
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6038
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition OpenMPKinds.h:28
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1774
PredefinedIdentKind
Definition Expr.h:1995
@ Implicit
An implicit conversion.
Definition Sema.h:440
OptionalUnsigned< NullabilityKind > NullabilityKindOrNone
Definition Specifiers.h:365
CharacterLiteralKind
Definition Expr.h:1609
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition ASTLambda.h:60
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition Specifiers.h:174
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition Specifiers.h:184
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:178
@ NOUR_None
This is an odr-use.
Definition Specifiers.h:176
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition Specifiers.h:181
#define false
Definition stdbool.h:26
ExprResult TransformSourceLocExpr(SourceLocExpr *E)
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
ExprResult TransformBlockExpr(BlockExpr *E)
ExprResult TransformLambdaExpr(LambdaExpr *E)
bool VisitSourceLocExpr(SourceLocExpr *E) override
bool VisitCXXConstructExpr(CXXConstructExpr *E) override
bool VisitCallExpr(CallExpr *E) override
const ASTContext & Context
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override
bool VisitLambdaExpr(LambdaExpr *E) override
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override
ImmediateCallVisitor(const ASTContext &Ctx)
Represents an element in a path from a derived class to a base class.
The class facilities generation and storage of conversion FixIts.
OverloadFixItKind Kind
The type of fix applied.
bool tryToFixConversion(const Expr *FromExpr, const QualType FromQTy, const QualType ToQTy, Sema &S)
If possible, generates and stores a fix for the given conversion.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
SourceLocation getBeginLoc() const
getBeginLoc - Retrieve the location of the first token.
SourceLocation getEndLoc() const LLVM_READONLY
Stores data related to a single embed directive.
Definition Expr.h:5108
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:640
bool DiagEmitted
Whether any diagnostic has been emitted.
Definition Expr.h:624
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition Expr.h:620
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
Extra information about a function prototype.
Definition TypeBase.h:5503
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13271
Data structure used to record current or nested expression evaluation contexts.
Definition Sema.h:6865
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition Sema.h:6900
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6951
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition Sema.h:6885
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition Sema.h:6905
llvm::SmallPtrSet< DeclRefExpr *, 4 > ReferenceToConsteval
Set of DeclRefExprs referencing a consteval function when used in a context not already known to be i...
Definition Sema.h:6913
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition Sema.h:6909
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6919
enum clang::Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext
SmallVector< LambdaExpr *, 2 > Lambdas
The lambdas that are present within this context, if it is indeed an unevaluated context.
Definition Sema.h:6880
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:6927
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition Sema.h:6870
ExpressionEvaluationContext Context
The expression evaluation context.
Definition Sema.h:6867
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition Sema.h:6874
Abstract class used to diagnose incomplete types.
Definition Sema.h:8351
Location information for a TemplateArgument.
TemplateNameKind Kind
The kind of template that Template refers to.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
Describes an entity that is being assigned.