clang 23.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 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
437 QualType Ty = VD->getType();
438 const FunctionType *Fn = nullptr;
439 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
440 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
441 if (!Fn)
442 return;
443 CalleeKind = CK_Function;
444 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
445 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
446 CalleeKind = CK_Block;
447 } else {
448 return;
449 }
450
451 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
452 NumFormalParams = proto->getNumParams();
453 else
454 NumFormalParams = 0;
455 } else {
456 return;
457 }
458
459 // "NullPos" is the number of formal parameters at the end which
460 // effectively count as part of the variadic arguments. This is
461 // useful if you would prefer to not have *any* formal parameters,
462 // but the language forces you to have at least one.
463 unsigned NullPos = Attr->getNullPos();
464 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
465 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
466
467 // The number of arguments which should follow the sentinel.
468 unsigned NumArgsAfterSentinel = Attr->getSentinel();
469
470 // If there aren't enough arguments for all the formal parameters,
471 // the sentinel, and the args after the sentinel, complain.
472 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
473 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
474 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
475 return;
476 }
477
478 // Otherwise, find the sentinel expression.
479 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
480 if (!SentinelExpr)
481 return;
482 if (SentinelExpr->isValueDependent())
483 return;
484 if (Context.isSentinelNullExpr(SentinelExpr))
485 return;
486
487 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
488 // or 'NULL' if those are actually defined in the context. Only use
489 // 'nil' for ObjC methods, where it's much more likely that the
490 // variadic arguments form a list of object pointers.
491 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
492 std::string NullValue;
493 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
494 NullValue = "nil";
495 else if (getLangOpts().CPlusPlus11)
496 NullValue = "nullptr";
497 else if (PP.isMacroDefined("NULL"))
498 NullValue = "NULL";
499 else
500 NullValue = "(void*) 0";
501
502 if (MissingNilLoc.isInvalid())
503 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
504 else
505 Diag(MissingNilLoc, diag::warn_missing_sentinel)
506 << int(CalleeKind)
507 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
508 Diag(D->getLocation(), diag::note_sentinel_here)
509 << int(CalleeKind) << Attr->getRange();
510}
511
513 return E ? E->getSourceRange() : SourceRange();
514}
515
516//===----------------------------------------------------------------------===//
517// Standard Promotions and Conversions
518//===----------------------------------------------------------------------===//
519
520/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
522 // Handle any placeholder expressions which made it here.
523 if (E->hasPlaceholderType()) {
525 if (result.isInvalid()) return ExprError();
526 E = result.get();
527 }
528
529 QualType Ty = E->getType();
530 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
531
532 if (Ty->isFunctionType()) {
533 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
534 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
536 return ExprError();
537
538 E = ImpCastExprToType(E, Context.getPointerType(Ty),
539 CK_FunctionToPointerDecay).get();
540 } else if (Ty->isArrayType()) {
541 // In C90 mode, arrays only promote to pointers if the array expression is
542 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
543 // type 'array of type' is converted to an expression that has type 'pointer
544 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
545 // that has type 'array of type' ...". The relevant change is "an lvalue"
546 // (C90) to "an expression" (C99).
547 //
548 // C++ 4.2p1:
549 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
550 // T" can be converted to an rvalue of type "pointer to T".
551 //
552 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
553 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
554 CK_ArrayToPointerDecay);
555 if (Res.isInvalid())
556 return ExprError();
557 E = Res.get();
558 }
559 }
560 return E;
561}
562
564 // Check to see if we are dereferencing a null pointer. If so,
565 // and if not volatile-qualified, this is undefined behavior that the
566 // optimizer will delete, so warn about it. People sometimes try to use this
567 // to get a deterministic trap and are surprised by clang's behavior. This
568 // only handles the pattern "*null", which is a very syntactic check.
569 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
570 if (UO && UO->getOpcode() == UO_Deref &&
571 UO->getSubExpr()->getType()->isPointerType()) {
572 const LangAS AS =
573 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
574 if ((!isTargetAddressSpace(AS) ||
575 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
576 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
578 !UO->getType().isVolatileQualified()) {
579 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
580 S.PDiag(diag::warn_indirection_through_null)
581 << UO->getSubExpr()->getSourceRange());
582 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
583 S.PDiag(diag::note_indirection_through_null));
584 }
585 }
586}
587
588static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
589 SourceLocation AssignLoc,
590 const Expr* RHS) {
591 const ObjCIvarDecl *IV = OIRE->getDecl();
592 if (!IV)
593 return;
594
595 DeclarationName MemberName = IV->getDeclName();
597 if (!Member || !Member->isStr("isa"))
598 return;
599
600 const Expr *Base = OIRE->getBase();
601 QualType BaseType = Base->getType();
602 if (OIRE->isArrow())
603 BaseType = BaseType->getPointeeType();
604 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
605 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
606 ObjCInterfaceDecl *ClassDeclared = nullptr;
607 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
608 if (!ClassDeclared->getSuperClass()
609 && (*ClassDeclared->ivar_begin()) == IV) {
610 if (RHS) {
611 NamedDecl *ObjectSetClass =
613 &S.Context.Idents.get("object_setClass"),
615 if (ObjectSetClass) {
616 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
617 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
619 "object_setClass(")
621 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
622 << FixItHint::CreateInsertion(RHSLocEnd, ")");
623 }
624 else
625 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
626 } else {
627 NamedDecl *ObjectGetClass =
629 &S.Context.Idents.get("object_getClass"),
631 if (ObjectGetClass)
632 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
634 "object_getClass(")
636 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
637 else
638 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
639 }
640 S.Diag(IV->getLocation(), diag::note_ivar_decl);
641 }
642 }
643}
644
646 // Handle any placeholder expressions which made it here.
647 if (E->hasPlaceholderType()) {
649 if (result.isInvalid()) return ExprError();
650 E = result.get();
651 }
652
653 // C++ [conv.lval]p1:
654 // A glvalue of a non-function, non-array type T can be
655 // converted to a prvalue.
656 if (!E->isGLValue()) return E;
657
658 QualType T = E->getType();
659 assert(!T.isNull() && "r-value conversion on typeless expression?");
660
661 // lvalue-to-rvalue conversion cannot be applied to types that decay to
662 // pointers (i.e. function or array types).
663 if (T->canDecayToPointerType())
664 return E;
665
666 // We don't want to throw lvalue-to-rvalue casts on top of
667 // expressions of certain types in C++.
668 // In HLSL LvaluetoRvalue conversion is allowed on records.
669 if (getLangOpts().CPlusPlus) {
670 if (T == Context.OverloadTy || (T->isRecordType() && !getLangOpts().HLSL) ||
671 (T->isDependentType() && !T->isAnyPointerType() &&
672 !T->isMemberPointerType()))
673 return E;
674 }
675
676 // The C standard is actually really unclear on this point, and
677 // DR106 tells us what the result should be but not why. It's
678 // generally best to say that void types just doesn't undergo
679 // lvalue-to-rvalue at all. Note that expressions of unqualified
680 // 'void' type are never l-values, but qualified void can be.
681 if (T->isVoidType())
682 return E;
683
684 // OpenCL usually rejects direct accesses to values of 'half' type.
685 if (getLangOpts().OpenCL &&
686 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
687 T->isHalfType()) {
688 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
689 << 0 << T;
690 return ExprError();
691 }
692
694 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
695 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
696 &Context.Idents.get("object_getClass"),
698 if (ObjectGetClass)
699 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
700 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
702 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
703 else
704 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
705 }
706 else if (const ObjCIvarRefExpr *OIRE =
707 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
708 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
709
710 // C++ [conv.lval]p1:
711 // [...] If T is a non-class type, the type of the prvalue is the
712 // cv-unqualified version of T. Otherwise, the type of the
713 // rvalue is T.
714 //
715 // C99 6.3.2.1p2:
716 // If the lvalue has qualified type, the value has the unqualified
717 // version of the type of the lvalue; otherwise, the value has the
718 // type of the lvalue.
719 if (T.hasQualifiers())
720 T = T.getUnqualifiedType();
721
722 // Under the MS ABI, lock down the inheritance model now.
723 if (T->isMemberPointerType() &&
724 Context.getTargetInfo().getCXXABI().isMicrosoft())
725 (void)isCompleteType(E->getExprLoc(), T);
726
728 if (Res.isInvalid())
729 return Res;
730 E = Res.get();
731
732 // Loading a __weak object implicitly retains the value, so we need a cleanup to
733 // balance that.
735 Cleanup.setExprNeedsCleanups(true);
736
738 Cleanup.setExprNeedsCleanups(true);
739
741 return ExprError();
742
743 // C++ [conv.lval]p3:
744 // If T is cv std::nullptr_t, the result is a null pointer constant.
745 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
746 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
748
749 // C11 6.3.2.1p2:
750 // ... if the lvalue has atomic type, the value has the non-atomic version
751 // of the type of the lvalue ...
752 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
753 T = Atomic->getValueType().getUnqualifiedType();
754 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
755 nullptr, VK_PRValue, FPOptionsOverride());
756 }
757
758 return Res;
759}
760
763 if (Res.isInvalid())
764 return ExprError();
765 Res = DefaultLvalueConversion(Res.get());
766 if (Res.isInvalid())
767 return ExprError();
768 return Res;
769}
770
772 QualType Ty = E->getType();
773 ExprResult Res = E;
774 // Only do implicit cast for a function type, but not for a pointer
775 // to function type.
776 if (Ty->isFunctionType()) {
777 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
778 CK_FunctionToPointerDecay);
779 if (Res.isInvalid())
780 return ExprError();
781 }
782 Res = DefaultLvalueConversion(Res.get());
783 if (Res.isInvalid())
784 return ExprError();
785 return Res.get();
786}
787
788/// UsualUnaryFPConversions - Promotes floating-point types according to the
789/// current language semantics.
791 QualType Ty = E->getType();
792 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
793
794 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
795 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
796 (getLangOpts().getFPEvalMethod() !=
798 PP.getLastFPEvalPragmaLocation().isValid())) {
799 switch (EvalMethod) {
800 default:
801 llvm_unreachable("Unrecognized float evaluation method");
802 break;
804 llvm_unreachable("Float evaluation method should be set by now");
805 break;
807 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
808 // Widen the expression to double.
809 return Ty->isComplexType()
811 Context.getComplexType(Context.DoubleTy),
812 CK_FloatingComplexCast)
813 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
814 break;
816 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
817 // Widen the expression to long double.
818 return Ty->isComplexType()
820 E, Context.getComplexType(Context.LongDoubleTy),
821 CK_FloatingComplexCast)
822 : ImpCastExprToType(E, Context.LongDoubleTy,
823 CK_FloatingCast);
824 break;
825 }
826 }
827
828 // Half FP have to be promoted to float unless it is natively supported
829 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
830 return ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast);
831
832 return E;
833}
834
835/// UsualUnaryConversions - Performs various conversions that are common to most
836/// operators (C99 6.3). The conversions of array and function types are
837/// sometimes suppressed. For example, the array->pointer conversion doesn't
838/// apply if the array is an argument to the sizeof or address (&) operators.
839/// In these instances, this routine should *not* be called.
841 // First, convert to an r-value.
843 if (Res.isInvalid())
844 return ExprError();
845
846 // Promote floating-point types.
847 Res = UsualUnaryFPConversions(Res.get());
848 if (Res.isInvalid())
849 return ExprError();
850 E = Res.get();
851
852 QualType Ty = E->getType();
853 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
854
855 // Try to perform integral promotions if the object has a theoretically
856 // promotable type.
858 // C99 6.3.1.1p2:
859 //
860 // The following may be used in an expression wherever an int or
861 // unsigned int may be used:
862 // - an object or expression with an integer type whose integer
863 // conversion rank is less than or equal to the rank of int
864 // and unsigned int.
865 // - A bit-field of type _Bool, int, signed int, or unsigned int.
866 //
867 // If an int can represent all values of the original type, the
868 // value is converted to an int; otherwise, it is converted to an
869 // unsigned int. These are called the integer promotions. All
870 // other types are unchanged by the integer promotions.
871
872 QualType PTy = Context.isPromotableBitField(E);
873 if (!PTy.isNull()) {
874 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
875 return E;
876 }
877 if (Context.isPromotableIntegerType(Ty)) {
878 QualType PT = Context.getPromotedIntegerType(Ty);
879 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
880 return E;
881 }
882 }
883 return E;
884}
885
886/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
887/// do not have a prototype. Arguments that have type float or __fp16
888/// are promoted to double. All other argument types are converted by
889/// UsualUnaryConversions().
891 QualType Ty = E->getType();
892 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
893
895 if (Res.isInvalid())
896 return ExprError();
897 E = Res.get();
898
899 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
900 // promote to double.
901 // Note that default argument promotion applies only to float (and
902 // half/fp16); it does not apply to _Float16.
903 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
904 if (BTy && (BTy->getKind() == BuiltinType::Half ||
905 BTy->getKind() == BuiltinType::Float)) {
906 if (getLangOpts().OpenCL &&
907 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
908 if (BTy->getKind() == BuiltinType::Half) {
909 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
910 }
911 } else {
912 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
913 }
914 }
915 if (BTy &&
916 getLangOpts().getExtendIntArgs() ==
918 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
919 Context.getTypeSizeInChars(BTy) <
920 Context.getTypeSizeInChars(Context.LongLongTy)) {
921 E = (Ty->isUnsignedIntegerType())
922 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
923 .get()
924 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
925 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
926 "Unexpected typesize for LongLongTy");
927 }
928
929 // C++ performs lvalue-to-rvalue conversion as a default argument
930 // promotion, even on class types, but note:
931 // C++11 [conv.lval]p2:
932 // When an lvalue-to-rvalue conversion occurs in an unevaluated
933 // operand or a subexpression thereof the value contained in the
934 // referenced object is not accessed. Otherwise, if the glvalue
935 // has a class type, the conversion copy-initializes a temporary
936 // of type T from the glvalue and the result of the conversion
937 // is a prvalue for the temporary.
938 // FIXME: add some way to gate this entire thing for correctness in
939 // potentially potentially evaluated contexts.
943 E->getExprLoc(), E);
944 if (Temp.isInvalid())
945 return ExprError();
946 E = Temp.get();
947 }
948
949 // C++ [expr.call]p7, per CWG722:
950 // An argument that has (possibly cv-qualified) type std::nullptr_t is
951 // converted to void* ([conv.ptr]).
952 // (This does not apply to C23 nullptr)
954 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
955
956 return E;
957}
958
960 if (Ty->isIncompleteType()) {
961 // C++11 [expr.call]p7:
962 // After these conversions, if the argument does not have arithmetic,
963 // enumeration, pointer, pointer to member, or class type, the program
964 // is ill-formed.
965 //
966 // Since we've already performed null pointer conversion, array-to-pointer
967 // decay and function-to-pointer decay, the only such type in C++ is cv
968 // void. This also handles initializer lists as variadic arguments.
969 if (Ty->isVoidType())
970 return VarArgKind::Invalid;
971
972 if (Ty->isObjCObjectType())
973 return VarArgKind::Invalid;
974 return VarArgKind::Valid;
975 }
976
978 return VarArgKind::Invalid;
979
980 if (Context.getTargetInfo().getTriple().isWasm() &&
982 return VarArgKind::Invalid;
983 }
984
985 if (Ty.isCXX98PODType(Context))
986 return VarArgKind::Valid;
987
988 // C++11 [expr.call]p7:
989 // Passing a potentially-evaluated argument of class type (Clause 9)
990 // having a non-trivial copy constructor, a non-trivial move constructor,
991 // or a non-trivial destructor, with no corresponding parameter,
992 // is conditionally-supported with implementation-defined semantics.
995 if (!Record->hasNonTrivialCopyConstructor() &&
996 !Record->hasNonTrivialMoveConstructor() &&
997 !Record->hasNonTrivialDestructor())
999
1000 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
1001 return VarArgKind::Valid;
1002
1003 if (Ty->isObjCObjectType())
1004 return VarArgKind::Invalid;
1005
1006 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1007 return VarArgKind::Valid;
1008
1009 if (getLangOpts().MSVCCompat)
1011
1012 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1013 return VarArgKind::Valid;
1014
1015 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1016 // permitted to reject them. We should consider doing so.
1017 return VarArgKind::Undefined;
1018}
1019
1021 // Don't allow one to pass an Objective-C interface to a vararg.
1022 const QualType &Ty = E->getType();
1023 VarArgKind VAK = isValidVarArgType(Ty);
1024
1025 // Complain about passing non-POD types through varargs.
1026 switch (VAK) {
1029 E->getBeginLoc(), nullptr,
1030 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1031 [[fallthrough]];
1032 case VarArgKind::Valid:
1033 if (Ty->isRecordType()) {
1034 // This is unlikely to be what the user intended. If the class has a
1035 // 'c_str' member function, the user probably meant to call that.
1036 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1037 PDiag(diag::warn_pass_class_arg_to_vararg)
1038 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1039 }
1040 break;
1041
1044 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1045 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1046 << getLangOpts().CPlusPlus11 << Ty << CT);
1047 break;
1048
1051 Diag(E->getBeginLoc(),
1052 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1053 << Ty << CT;
1054 else if (Ty->isObjCObjectType())
1055 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1056 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1057 << Ty << CT);
1058 else
1059 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1060 << isa<InitListExpr>(E) << Ty << CT;
1061 break;
1062 }
1063}
1064
1066 FunctionDecl *FDecl) {
1067 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1068 // Strip the unbridged-cast placeholder expression off, if applicable.
1069 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1070 (CT == VariadicCallType::Method ||
1071 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1072 E = ObjC().stripARCUnbridgedCast(E);
1073
1074 // Otherwise, do normal placeholder checking.
1075 } else {
1076 ExprResult ExprRes = CheckPlaceholderExpr(E);
1077 if (ExprRes.isInvalid())
1078 return ExprError();
1079 E = ExprRes.get();
1080 }
1081 }
1082
1084 if (ExprRes.isInvalid())
1085 return ExprError();
1086
1087 // Copy blocks to the heap.
1088 if (ExprRes.get()->getType()->isBlockPointerType())
1089 maybeExtendBlockObject(ExprRes);
1090
1091 E = ExprRes.get();
1092
1093 // Diagnostics regarding non-POD argument types are
1094 // emitted along with format string checking in Sema::CheckFunctionCall().
1096 // Turn this into a trap.
1097 CXXScopeSpec SS;
1098 SourceLocation TemplateKWLoc;
1099 UnqualifiedId Name;
1100 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1101 E->getBeginLoc());
1102 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1103 /*HasTrailingLParen=*/true,
1104 /*IsAddressOfOperand=*/false);
1105 if (TrapFn.isInvalid())
1106 return ExprError();
1107
1108 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1109 E->getEndLoc());
1110 if (Call.isInvalid())
1111 return ExprError();
1112
1113 ExprResult Comma =
1114 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1115 if (Comma.isInvalid())
1116 return ExprError();
1117 return Comma.get();
1118 }
1119
1120 if (!getLangOpts().CPlusPlus &&
1122 diag::err_call_incomplete_argument))
1123 return ExprError();
1124
1125 return E;
1126}
1127
1128/// Convert complex integers to complex floats and real integers to
1129/// real floats as required for complex arithmetic. Helper function of
1130/// UsualArithmeticConversions()
1131///
1132/// \return false if the integer expression is an integer type and is
1133/// successfully converted to the (complex) float type.
1135 ExprResult &ComplexExpr,
1136 QualType IntTy,
1137 QualType ComplexTy,
1138 bool SkipCast) {
1139 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1140 if (SkipCast) return false;
1141 if (IntTy->isIntegerType()) {
1142 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1143 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1144 } else {
1145 assert(IntTy->isComplexIntegerType());
1146 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1147 CK_IntegralComplexToFloatingComplex);
1148 }
1149 return false;
1150}
1151
1152// This handles complex/complex, complex/float, or float/complex.
1153// When both operands are complex, the shorter operand is converted to the
1154// type of the longer, and that is the type of the result. This corresponds
1155// to what is done when combining two real floating-point operands.
1156// The fun begins when size promotion occur across type domains.
1157// From H&S 6.3.4: When one operand is complex and the other is a real
1158// floating-point type, the less precise type is converted, within it's
1159// real or complex domain, to the precision of the other type. For example,
1160// when combining a "long double" with a "double _Complex", the
1161// "double _Complex" is promoted to "long double _Complex".
1163 QualType ShorterType,
1164 QualType LongerType,
1165 bool PromotePrecision) {
1166 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1168 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1169
1170 if (PromotePrecision) {
1171 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1172 Shorter =
1173 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1174 } else {
1175 if (LongerIsComplex)
1176 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1177 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1178 }
1179 }
1180 return Result;
1181}
1182
1183/// Handle arithmetic conversion with complex types. Helper function of
1184/// UsualArithmeticConversions()
1186 ExprResult &RHS, QualType LHSType,
1187 QualType RHSType, bool IsCompAssign) {
1188 // Handle (complex) integer types.
1189 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1190 /*SkipCast=*/false))
1191 return LHSType;
1192 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1193 /*SkipCast=*/IsCompAssign))
1194 return RHSType;
1195
1196 // Compute the rank of the two types, regardless of whether they are complex.
1197 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1198 if (Order < 0)
1199 // Promote the precision of the LHS if not an assignment.
1200 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1201 /*PromotePrecision=*/!IsCompAssign);
1202 // Promote the precision of the RHS unless it is already the same as the LHS.
1203 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1204 /*PromotePrecision=*/Order > 0);
1205}
1206
1207/// Handle arithmetic conversion from integer to float. Helper function
1208/// of UsualArithmeticConversions()
1210 ExprResult &IntExpr,
1211 QualType FloatTy, QualType IntTy,
1212 bool ConvertFloat, bool ConvertInt) {
1213 if (IntTy->isIntegerType()) {
1214 if (ConvertInt)
1215 // Convert intExpr to the lhs floating point type.
1216 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1217 CK_IntegralToFloating);
1218 return FloatTy;
1219 }
1220
1221 // Convert both sides to the appropriate complex float.
1222 assert(IntTy->isComplexIntegerType());
1223 QualType result = S.Context.getComplexType(FloatTy);
1224
1225 // _Complex int -> _Complex float
1226 if (ConvertInt)
1227 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1228 CK_IntegralComplexToFloatingComplex);
1229
1230 // float -> _Complex float
1231 if (ConvertFloat)
1232 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1233 CK_FloatingRealToComplex);
1234
1235 return result;
1236}
1237
1238/// Handle arithmethic conversion with floating point types. Helper
1239/// function of UsualArithmeticConversions()
1241 ExprResult &RHS, QualType LHSType,
1242 QualType RHSType, bool IsCompAssign) {
1243 bool LHSFloat = LHSType->isRealFloatingType();
1244 bool RHSFloat = RHSType->isRealFloatingType();
1245
1246 // N1169 4.1.4: If one of the operands has a floating type and the other
1247 // operand has a fixed-point type, the fixed-point operand
1248 // is converted to the floating type [...]
1249 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1250 if (LHSFloat)
1251 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1252 else if (!IsCompAssign)
1253 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1254 return LHSFloat ? LHSType : RHSType;
1255 }
1256
1257 // If we have two real floating types, convert the smaller operand
1258 // to the bigger result.
1259 if (LHSFloat && RHSFloat) {
1260 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1261 if (order > 0) {
1262 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1263 return LHSType;
1264 }
1265
1266 assert(order < 0 && "illegal float comparison");
1267 if (!IsCompAssign)
1268 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1269 return RHSType;
1270 }
1271
1272 if (LHSFloat) {
1273 // Half FP has to be promoted to float unless it is natively supported
1274 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1275 LHSType = S.Context.FloatTy;
1276
1277 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1278 /*ConvertFloat=*/!IsCompAssign,
1279 /*ConvertInt=*/ true);
1280 }
1281 assert(RHSFloat);
1282 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1283 /*ConvertFloat=*/ true,
1284 /*ConvertInt=*/!IsCompAssign);
1285}
1286
1287/// Diagnose attempts to convert between __float128, __ibm128 and
1288/// long double if there is no support for such conversion.
1289/// Helper function of UsualArithmeticConversions().
1290static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1291 QualType RHSType) {
1292 // No issue if either is not a floating point type.
1293 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1294 return false;
1295
1296 // No issue if both have the same 128-bit float semantics.
1297 auto *LHSComplex = LHSType->getAs<ComplexType>();
1298 auto *RHSComplex = RHSType->getAs<ComplexType>();
1299
1300 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1301 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1302
1303 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1304 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1305
1306 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1307 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1308 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1309 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1310 return false;
1311
1312 return true;
1313}
1314
1315typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1316
1317namespace {
1318/// These helper callbacks are placed in an anonymous namespace to
1319/// permit their use as function template parameters.
1320ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1321 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1322}
1323
1324ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1325 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1326 CK_IntegralComplexCast);
1327}
1328}
1329
1330/// Handle integer arithmetic conversions. Helper function of
1331/// UsualArithmeticConversions()
1332template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1334 ExprResult &RHS, QualType LHSType,
1335 QualType RHSType, bool IsCompAssign) {
1336 // The rules for this case are in C99 6.3.1.8
1337 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1338 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1339 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1340 if (LHSSigned == RHSSigned) {
1341 // Same signedness; use the higher-ranked type
1342 if (order >= 0) {
1343 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1344 return LHSType;
1345 } else if (!IsCompAssign)
1346 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1347 return RHSType;
1348 } else if (order != (LHSSigned ? 1 : -1)) {
1349 // The unsigned type has greater than or equal rank to the
1350 // signed type, so use the unsigned type
1351 if (RHSSigned) {
1352 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1353 return LHSType;
1354 } else if (!IsCompAssign)
1355 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1356 return RHSType;
1357 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1358 // The two types are different widths; if we are here, that
1359 // means the signed type is larger than the unsigned type, so
1360 // use the signed type.
1361 if (LHSSigned) {
1362 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1363 return LHSType;
1364 } else if (!IsCompAssign)
1365 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1366 return RHSType;
1367 } else {
1368 // The signed type is higher-ranked than the unsigned type,
1369 // but isn't actually any bigger (like unsigned int and long
1370 // on most 32-bit systems). Use the unsigned type corresponding
1371 // to the signed type.
1372 QualType result =
1373 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1374 RHS = (*doRHSCast)(S, RHS.get(), result);
1375 if (!IsCompAssign)
1376 LHS = (*doLHSCast)(S, LHS.get(), result);
1377 return result;
1378 }
1379}
1380
1381/// Handle conversions with GCC complex int extension. Helper function
1382/// of UsualArithmeticConversions()
1384 ExprResult &RHS, QualType LHSType,
1385 QualType RHSType,
1386 bool IsCompAssign) {
1387 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1388 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1389
1390 if (LHSComplexInt && RHSComplexInt) {
1391 QualType LHSEltType = LHSComplexInt->getElementType();
1392 QualType RHSEltType = RHSComplexInt->getElementType();
1393 QualType ScalarType =
1395 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1396
1397 return S.Context.getComplexType(ScalarType);
1398 }
1399
1400 if (LHSComplexInt) {
1401 QualType LHSEltType = LHSComplexInt->getElementType();
1402 QualType ScalarType =
1404 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1406 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1407 CK_IntegralRealToComplex);
1408
1409 return ComplexType;
1410 }
1411
1412 assert(RHSComplexInt);
1413
1414 QualType RHSEltType = RHSComplexInt->getElementType();
1415 QualType ScalarType =
1417 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1419
1420 if (!IsCompAssign)
1421 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1422 CK_IntegralRealToComplex);
1423 return ComplexType;
1424}
1425
1427 ExprResult &RHS,
1428 QualType LHSType,
1429 QualType RHSType,
1430 bool IsCompAssign) {
1431
1432 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1433 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1434
1435 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1436 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1437
1438 bool LHSHasTrap =
1439 LhsOBT && LhsOBT->getBehaviorKind() ==
1440 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1441 bool RHSHasTrap =
1442 RhsOBT && RhsOBT->getBehaviorKind() ==
1443 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1444 bool LHSHasWrap =
1445 LhsOBT && LhsOBT->getBehaviorKind() ==
1446 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1447 bool RHSHasWrap =
1448 RhsOBT && RhsOBT->getBehaviorKind() ==
1449 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1450
1451 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1452 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1453
1454 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1455 if (LHSHasTrap || RHSHasTrap)
1456 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1457 else if (LHSHasWrap || RHSHasWrap)
1458 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1459
1460 QualType LHSConvType = LHSUnderlyingType;
1461 QualType RHSConvType = RHSUnderlyingType;
1462 if (DominantBehavior) {
1463 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1464 LHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1465 LHSUnderlyingType);
1466 else
1467 LHSConvType = LHSType;
1468
1469 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1470 RHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1471 RHSUnderlyingType);
1472 else
1473 RHSConvType = RHSType;
1474 }
1475
1477 S, LHS, RHS, LHSConvType, RHSConvType, IsCompAssign);
1478}
1479
1480/// Return the rank of a given fixed point or integer type. The value itself
1481/// doesn't matter, but the values must be increasing with proper increasing
1482/// rank as described in N1169 4.1.1.
1483static unsigned GetFixedPointRank(QualType Ty) {
1484 const auto *BTy = Ty->getAs<BuiltinType>();
1485 assert(BTy && "Expected a builtin type.");
1486
1487 switch (BTy->getKind()) {
1488 case BuiltinType::ShortFract:
1489 case BuiltinType::UShortFract:
1490 case BuiltinType::SatShortFract:
1491 case BuiltinType::SatUShortFract:
1492 return 1;
1493 case BuiltinType::Fract:
1494 case BuiltinType::UFract:
1495 case BuiltinType::SatFract:
1496 case BuiltinType::SatUFract:
1497 return 2;
1498 case BuiltinType::LongFract:
1499 case BuiltinType::ULongFract:
1500 case BuiltinType::SatLongFract:
1501 case BuiltinType::SatULongFract:
1502 return 3;
1503 case BuiltinType::ShortAccum:
1504 case BuiltinType::UShortAccum:
1505 case BuiltinType::SatShortAccum:
1506 case BuiltinType::SatUShortAccum:
1507 return 4;
1508 case BuiltinType::Accum:
1509 case BuiltinType::UAccum:
1510 case BuiltinType::SatAccum:
1511 case BuiltinType::SatUAccum:
1512 return 5;
1513 case BuiltinType::LongAccum:
1514 case BuiltinType::ULongAccum:
1515 case BuiltinType::SatLongAccum:
1516 case BuiltinType::SatULongAccum:
1517 return 6;
1518 default:
1519 if (BTy->isInteger())
1520 return 0;
1521 llvm_unreachable("Unexpected fixed point or integer type");
1522 }
1523}
1524
1525/// handleFixedPointConversion - Fixed point operations between fixed
1526/// point types and integers or other fixed point types do not fall under
1527/// usual arithmetic conversion since these conversions could result in loss
1528/// of precsision (N1169 4.1.4). These operations should be calculated with
1529/// the full precision of their result type (N1169 4.1.6.2.1).
1531 QualType RHSTy) {
1532 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1533 "Expected at least one of the operands to be a fixed point type");
1534 assert((LHSTy->isFixedPointOrIntegerType() ||
1535 RHSTy->isFixedPointOrIntegerType()) &&
1536 "Special fixed point arithmetic operation conversions are only "
1537 "applied to ints or other fixed point types");
1538
1539 // If one operand has signed fixed-point type and the other operand has
1540 // unsigned fixed-point type, then the unsigned fixed-point operand is
1541 // converted to its corresponding signed fixed-point type and the resulting
1542 // type is the type of the converted operand.
1543 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1545 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1547
1548 // The result type is the type with the highest rank, whereby a fixed-point
1549 // conversion rank is always greater than an integer conversion rank; if the
1550 // type of either of the operands is a saturating fixedpoint type, the result
1551 // type shall be the saturating fixed-point type corresponding to the type
1552 // with the highest rank; the resulting value is converted (taking into
1553 // account rounding and overflow) to the precision of the resulting type.
1554 // Same ranks between signed and unsigned types are resolved earlier, so both
1555 // types are either signed or both unsigned at this point.
1556 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1557 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1558
1559 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1560
1562 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1563
1564 return ResultTy;
1565}
1566
1567/// Check that the usual arithmetic conversions can be performed on this pair of
1568/// expressions that might be of enumeration type.
1570 SourceLocation Loc,
1571 ArithConvKind ACK) {
1572 // C++2a [expr.arith.conv]p1:
1573 // If one operand is of enumeration type and the other operand is of a
1574 // different enumeration type or a floating-point type, this behavior is
1575 // deprecated ([depr.arith.conv.enum]).
1576 //
1577 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1578 // Eventually we will presumably reject these cases (in C++23 onwards?).
1580 R = RHS->getEnumCoercedType(Context);
1581 bool LEnum = L->isUnscopedEnumerationType(),
1582 REnum = R->isUnscopedEnumerationType();
1583 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1584 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1585 (REnum && L->isFloatingType())) {
1586 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1588 ? diag::warn_arith_conv_enum_float_cxx20
1589 : diag::warn_arith_conv_enum_float)
1590 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1591 << L << R;
1592 } else if (!IsCompAssign && LEnum && REnum &&
1593 !Context.hasSameUnqualifiedType(L, R)) {
1594 unsigned DiagID;
1595 // In C++ 26, usual arithmetic conversions between 2 different enum types
1596 // are ill-formed.
1598 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1599 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1600 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1601 // If either enumeration type is unnamed, it's less likely that the
1602 // user cares about this, but this situation is still deprecated in
1603 // C++2a. Use a different warning group.
1604 DiagID = getLangOpts().CPlusPlus20
1605 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1606 : diag::warn_arith_conv_mixed_anon_enum_types;
1607 } else if (ACK == ArithConvKind::Conditional) {
1608 // Conditional expressions are separated out because they have
1609 // historically had a different warning flag.
1610 DiagID = getLangOpts().CPlusPlus20
1611 ? diag::warn_conditional_mixed_enum_types_cxx20
1612 : diag::warn_conditional_mixed_enum_types;
1613 } else if (ACK == ArithConvKind::Comparison) {
1614 // Comparison expressions are separated out because they have
1615 // historically had a different warning flag.
1616 DiagID = getLangOpts().CPlusPlus20
1617 ? diag::warn_comparison_mixed_enum_types_cxx20
1618 : diag::warn_comparison_mixed_enum_types;
1619 } else {
1620 DiagID = getLangOpts().CPlusPlus20
1621 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1622 : diag::warn_arith_conv_mixed_enum_types;
1623 }
1624 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1625 << (int)ACK << L << R;
1626 }
1627}
1628
1630 Expr *RHS, SourceLocation Loc,
1631 ArithConvKind ACK) {
1632 QualType LHSType = LHS->getType().getUnqualifiedType();
1633 QualType RHSType = RHS->getType().getUnqualifiedType();
1634
1635 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1636 !RHSType->isUnicodeCharacterType())
1637 return;
1638
1639 if (ACK == ArithConvKind::Comparison) {
1640 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1641 return;
1642
1643 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1644 if (T->isChar8Type())
1645 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1646 if (T->isChar16Type())
1647 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1648 assert(T->isChar32Type());
1649 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1650 };
1651
1652 Expr::EvalResult LHSRes, RHSRes;
1653 bool LHSSuccess = LHS->EvaluateAsInt(LHSRes, SemaRef.getASTContext(),
1655 SemaRef.isConstantEvaluatedContext());
1656 bool RHSuccess = RHS->EvaluateAsInt(RHSRes, SemaRef.getASTContext(),
1658 SemaRef.isConstantEvaluatedContext());
1659
1660 // Don't warn if the one known value is a representable
1661 // in the type of both expressions.
1662 if (LHSSuccess != RHSuccess) {
1663 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1664 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1665 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1666 return;
1667 }
1668
1669 if (!LHSSuccess || !RHSuccess) {
1670 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types)
1671 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1672 << RHSType;
1673 return;
1674 }
1675
1676 llvm::APSInt LHSValue(32);
1677 LHSValue = LHSRes.Val.getInt();
1678 llvm::APSInt RHSValue(32);
1679 RHSValue = RHSRes.Val.getInt();
1680
1681 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1682 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1683 if (LHSSafe && RHSSafe)
1684 return;
1685
1686 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types_constant)
1687 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1688 << FormatUTFCodeUnitAsCodepoint(LHSValue.getExtValue(), LHSType)
1689 << FormatUTFCodeUnitAsCodepoint(RHSValue.getExtValue(), RHSType);
1690 return;
1691 }
1692
1693 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1694 return;
1695
1696 SemaRef.Diag(Loc, diag::warn_arith_conv_mixed_unicode_types)
1697 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1698 << RHSType;
1699}
1700
1701/// UsualArithmeticConversions - Performs various conversions that are common to
1702/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1703/// routine returns the first non-arithmetic type found. The client is
1704/// responsible for emitting appropriate error diagnostics.
1706 SourceLocation Loc,
1707 ArithConvKind ACK) {
1708
1709 checkEnumArithmeticConversions(LHS.get(), RHS.get(), Loc, ACK);
1710
1711 CheckUnicodeArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1712
1713 if (ACK != ArithConvKind::CompAssign) {
1714 LHS = UsualUnaryConversions(LHS.get());
1715 if (LHS.isInvalid())
1716 return QualType();
1717 }
1718
1719 RHS = UsualUnaryConversions(RHS.get());
1720 if (RHS.isInvalid())
1721 return QualType();
1722
1723 // For conversion purposes, we ignore any qualifiers.
1724 // For example, "const float" and "float" are equivalent.
1725 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1726 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1727
1728 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1729 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1730 LHSType = AtomicLHS->getValueType();
1731
1732 // If both types are identical, no conversion is needed.
1733 if (Context.hasSameType(LHSType, RHSType))
1734 return Context.getCommonSugaredType(LHSType, RHSType);
1735
1736 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1737 // The caller can deal with this (e.g. pointer + int).
1738 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1739 return QualType();
1740
1741 // Apply unary and bitfield promotions to the LHS's type.
1742 QualType LHSUnpromotedType = LHSType;
1743 if (Context.isPromotableIntegerType(LHSType))
1744 LHSType = Context.getPromotedIntegerType(LHSType);
1745 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1746 if (!LHSBitfieldPromoteTy.isNull())
1747 LHSType = LHSBitfieldPromoteTy;
1748 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1749 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1750
1751 // If both types are identical, no conversion is needed.
1752 if (Context.hasSameType(LHSType, RHSType))
1753 return Context.getCommonSugaredType(LHSType, RHSType);
1754
1755 // At this point, we have two different arithmetic types.
1756
1757 if ((LHSType->isFixedPointType() && RHSType->isBitIntType()) ||
1758 (LHSType->isBitIntType() && RHSType->isFixedPointType()))
1759 return QualType();
1760
1761 // Diagnose attempts to convert between __ibm128, __float128 and long double
1762 // where such conversions currently can't be handled.
1763 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1764 return QualType();
1765
1766 // Handle complex types first (C99 6.3.1.8p1).
1767 if (LHSType->isComplexType() || RHSType->isComplexType())
1768 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1770
1771 // Now handle "real" floating types (i.e. float, double, long double).
1772 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1773 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1775
1776 // Handle GCC complex int extension.
1777 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1778 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1780
1781 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1782 return handleFixedPointConversion(*this, LHSType, RHSType);
1783
1784 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1786 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1787
1788 // Finally, we have two differing integer types.
1790 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1791}
1792
1793//===----------------------------------------------------------------------===//
1794// Semantic Analysis for various Expression Types
1795//===----------------------------------------------------------------------===//
1796
1797
1799 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1800 bool PredicateIsExpr, void *ControllingExprOrType,
1801 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1802 unsigned NumAssocs = ArgTypes.size();
1803 assert(NumAssocs == ArgExprs.size());
1804
1805 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1806 for (unsigned i = 0; i < NumAssocs; ++i) {
1807 if (ArgTypes[i])
1808 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1809 else
1810 Types[i] = nullptr;
1811 }
1812
1813 // If we have a controlling type, we need to convert it from a parsed type
1814 // into a semantic type and then pass that along.
1815 if (!PredicateIsExpr) {
1816 TypeSourceInfo *ControllingType;
1817 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1818 &ControllingType);
1819 assert(ControllingType && "couldn't get the type out of the parser");
1820 ControllingExprOrType = ControllingType;
1821 }
1822
1824 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1825 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1826 delete [] Types;
1827 return ER;
1828}
1829
1830// Helper function to determine type compatibility for C _Generic expressions.
1831// Multiple compatible types within the same _Generic expression is ambiguous
1832// and not valid.
1834 QualType U) {
1835 // Try to handle special types like OverflowBehaviorTypes
1836 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1837 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1838
1839 if (TOBT || UOBT) {
1840 if (TOBT && UOBT) {
1841 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1842 return Ctx.typesAreCompatible(TOBT->getUnderlyingType(),
1843 UOBT->getUnderlyingType());
1844 return false;
1845 }
1846 return false;
1847 }
1848
1849 // We're dealing with types that don't require special handling.
1850 return Ctx.typesAreCompatible(T, U);
1851}
1852
1854 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1855 bool PredicateIsExpr, void *ControllingExprOrType,
1857 unsigned NumAssocs = Types.size();
1858 assert(NumAssocs == Exprs.size());
1859 assert(ControllingExprOrType &&
1860 "Must have either a controlling expression or a controlling type");
1861
1862 Expr *ControllingExpr = nullptr;
1863 TypeSourceInfo *ControllingType = nullptr;
1864 if (PredicateIsExpr) {
1865 // Decay and strip qualifiers for the controlling expression type, and
1866 // handle placeholder type replacement. See committee discussion from WG14
1867 // DR423.
1871 reinterpret_cast<Expr *>(ControllingExprOrType));
1872 if (R.isInvalid())
1873 return ExprError();
1874 ControllingExpr = R.get();
1875 } else {
1876 // The extension form uses the type directly rather than converting it.
1877 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1878 if (!ControllingType)
1879 return ExprError();
1880 }
1881
1882 bool TypeErrorFound = false,
1883 IsResultDependent = ControllingExpr
1884 ? ControllingExpr->isTypeDependent()
1885 : ControllingType->getType()->isDependentType(),
1886 ContainsUnexpandedParameterPack =
1887 ControllingExpr
1888 ? ControllingExpr->containsUnexpandedParameterPack()
1889 : ControllingType->getType()->containsUnexpandedParameterPack();
1890
1891 // The controlling expression is an unevaluated operand, so side effects are
1892 // likely unintended.
1893 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1894 ControllingExpr->HasSideEffects(Context, false))
1895 Diag(ControllingExpr->getExprLoc(),
1896 diag::warn_side_effects_unevaluated_context);
1897
1898 for (unsigned i = 0; i < NumAssocs; ++i) {
1899 if (Exprs[i]->containsUnexpandedParameterPack())
1900 ContainsUnexpandedParameterPack = true;
1901
1902 if (Types[i]) {
1903 if (Types[i]->getType()->containsUnexpandedParameterPack())
1904 ContainsUnexpandedParameterPack = true;
1905
1906 if (Types[i]->getType()->isDependentType()) {
1907 IsResultDependent = true;
1908 } else {
1909 // We relax the restriction on use of incomplete types and non-object
1910 // types with the type-based extension of _Generic. Allowing incomplete
1911 // objects means those can be used as "tags" for a type-safe way to map
1912 // to a value. Similarly, matching on function types rather than
1913 // function pointer types can be useful. However, the restriction on VM
1914 // types makes sense to retain as there are open questions about how
1915 // the selection can be made at compile time.
1916 //
1917 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1918 // complete object type other than a variably modified type."
1919 // C2y removed the requirement that an expression form must
1920 // use a complete type, though it's still as-if the type has undergone
1921 // lvalue conversion. We support this as an extension in C23 and
1922 // earlier because GCC does so.
1923 unsigned D = 0;
1924 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1925 D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete
1926 : diag::ext_assoc_type_incomplete;
1927 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1928 D = diag::err_assoc_type_nonobject;
1929 else if (Types[i]->getType()->isVariablyModifiedType())
1930 D = diag::err_assoc_type_variably_modified;
1931 else if (ControllingExpr) {
1932 // Because the controlling expression undergoes lvalue conversion,
1933 // array conversion, and function conversion, an association which is
1934 // of array type, function type, or is qualified can never be
1935 // reached. We will warn about this so users are less surprised by
1936 // the unreachable association. However, we don't have to handle
1937 // function types; that's not an object type, so it's handled above.
1938 //
1939 // The logic is somewhat different for C++ because C++ has different
1940 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1941 // If T is a non-class type, the type of the prvalue is the cv-
1942 // unqualified version of T. Otherwise, the type of the prvalue is T.
1943 // The result of these rules is that all qualified types in an
1944 // association in C are unreachable, and in C++, only qualified non-
1945 // class types are unreachable.
1946 //
1947 // NB: this does not apply when the first operand is a type rather
1948 // than an expression, because the type form does not undergo
1949 // conversion.
1950 unsigned Reason = 0;
1951 QualType QT = Types[i]->getType();
1952 if (QT->isArrayType())
1953 Reason = 1;
1954 else if (QT.hasQualifiers() &&
1955 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1956 Reason = 2;
1957
1958 if (Reason)
1959 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1960 diag::warn_unreachable_association)
1961 << QT << (Reason - 1);
1962 }
1963
1964 if (D != 0) {
1965 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1966 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1967 if (getDiagnostics().getDiagnosticLevel(
1968 D, Types[i]->getTypeLoc().getBeginLoc()) >=
1970 TypeErrorFound = true;
1971 }
1972
1973 // C11 6.5.1.1p2 "No two generic associations in the same generic
1974 // selection shall specify compatible types."
1975 for (unsigned j = i+1; j < NumAssocs; ++j)
1976 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1978 Types[j]->getType())) {
1979 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1980 diag::err_assoc_compatible_types)
1981 << Types[j]->getTypeLoc().getSourceRange()
1982 << Types[j]->getType()
1983 << Types[i]->getType();
1984 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1985 diag::note_compat_assoc)
1986 << Types[i]->getTypeLoc().getSourceRange()
1987 << Types[i]->getType();
1988 TypeErrorFound = true;
1989 }
1990 }
1991 }
1992 }
1993 if (TypeErrorFound)
1994 return ExprError();
1995
1996 // If we determined that the generic selection is result-dependent, don't
1997 // try to compute the result expression.
1998 if (IsResultDependent) {
1999 if (ControllingExpr)
2000 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
2001 Types, Exprs, DefaultLoc, RParenLoc,
2002 ContainsUnexpandedParameterPack);
2003 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
2004 Exprs, DefaultLoc, RParenLoc,
2005 ContainsUnexpandedParameterPack);
2006 }
2007
2008 SmallVector<unsigned, 1> CompatIndices;
2009 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2010 // Look at the canonical type of the controlling expression in case it was a
2011 // deduced type like __auto_type. However, when issuing diagnostics, use the
2012 // type the user wrote in source rather than the canonical one.
2013 for (unsigned i = 0; i < NumAssocs; ++i) {
2014 if (!Types[i])
2015 DefaultIndex = i;
2016 else {
2017 bool Compatible;
2018 QualType ControllingQT =
2019 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2020 : ControllingType->getType().getCanonicalType();
2021 QualType AssocQT = Types[i]->getType();
2022
2023 Compatible =
2024 areTypesCompatibleForGeneric(Context, ControllingQT, AssocQT);
2025
2026 if (Compatible)
2027 CompatIndices.push_back(i);
2028 }
2029 }
2030
2031 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2032 TypeSourceInfo *ControllingType) {
2033 // We strip parens here because the controlling expression is typically
2034 // parenthesized in macro definitions.
2035 if (ControllingExpr)
2036 ControllingExpr = ControllingExpr->IgnoreParens();
2037
2038 SourceRange SR = ControllingExpr
2039 ? ControllingExpr->getSourceRange()
2040 : ControllingType->getTypeLoc().getSourceRange();
2041 QualType QT = ControllingExpr ? ControllingExpr->getType()
2042 : ControllingType->getType();
2043
2044 return std::make_pair(SR, QT);
2045 };
2046
2047 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2048 // type compatible with at most one of the types named in its generic
2049 // association list."
2050 if (CompatIndices.size() > 1) {
2051 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2052 SourceRange SR = P.first;
2053 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
2054 << SR << P.second << (unsigned)CompatIndices.size();
2055 for (unsigned I : CompatIndices) {
2056 Diag(Types[I]->getTypeLoc().getBeginLoc(),
2057 diag::note_compat_assoc)
2058 << Types[I]->getTypeLoc().getSourceRange()
2059 << Types[I]->getType();
2060 }
2061 return ExprError();
2062 }
2063
2064 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2065 // its controlling expression shall have type compatible with exactly one of
2066 // the types named in its generic association list."
2067 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2068 CompatIndices.size() == 0) {
2069 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2070 SourceRange SR = P.first;
2071 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
2072 return ExprError();
2073 }
2074
2075 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2076 // type name that is compatible with the type of the controlling expression,
2077 // then the result expression of the generic selection is the expression
2078 // in that generic association. Otherwise, the result expression of the
2079 // generic selection is the expression in the default generic association."
2080 unsigned ResultIndex =
2081 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2082
2083 if (ControllingExpr) {
2085 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
2086 ContainsUnexpandedParameterPack, ResultIndex);
2087 }
2089 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
2090 ContainsUnexpandedParameterPack, ResultIndex);
2091}
2092
2094 switch (Kind) {
2095 default:
2096 llvm_unreachable("unexpected TokenKind");
2097 case tok::kw___func__:
2098 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2099 case tok::kw___FUNCTION__:
2101 case tok::kw___FUNCDNAME__:
2102 return PredefinedIdentKind::FuncDName; // [MS]
2103 case tok::kw___FUNCSIG__:
2104 return PredefinedIdentKind::FuncSig; // [MS]
2105 case tok::kw_L__FUNCTION__:
2106 return PredefinedIdentKind::LFunction; // [MS]
2107 case tok::kw_L__FUNCSIG__:
2108 return PredefinedIdentKind::LFuncSig; // [MS]
2109 case tok::kw___PRETTY_FUNCTION__:
2111 }
2112}
2113
2114/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2115/// to determine the value of a PredefinedExpr. This can be either a
2116/// block, lambda, captured statement, function, otherwise a nullptr.
2119 DC = DC->getParent();
2120 return cast_or_null<Decl>(DC);
2121}
2122
2123/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2124/// location of the token and the offset of the ud-suffix within it.
2126 unsigned Offset) {
2127 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
2128 S.getLangOpts());
2129}
2130
2131/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2132/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2134 IdentifierInfo *UDSuffix,
2135 SourceLocation UDSuffixLoc,
2136 ArrayRef<Expr*> Args,
2137 SourceLocation LitEndLoc) {
2138 assert(Args.size() <= 2 && "too many arguments for literal operator");
2139
2140 QualType ArgTy[2];
2141 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2142 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2143 if (ArgTy[ArgIdx]->isArrayType())
2144 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
2145 }
2146
2147 DeclarationName OpName =
2149 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2150 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2151
2152 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2153 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
2154 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2155 /*AllowStringTemplatePack*/ false,
2156 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2157 return ExprError();
2158
2159 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
2160}
2161
2163 // StringToks needs backing storage as it doesn't hold array elements itself
2164 std::vector<Token> ExpandedToks;
2165 if (getLangOpts().MicrosoftExt)
2166 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2167
2168 StringLiteralParser Literal(StringToks, PP,
2170 if (Literal.hadError)
2171 return ExprError();
2172
2173 SmallVector<SourceLocation, 4> StringTokLocs;
2174 for (const Token &Tok : StringToks)
2175 StringTokLocs.push_back(Tok.getLocation());
2176
2177 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2179 false, {}, StringTokLocs);
2180
2181 if (!Literal.getUDSuffix().empty()) {
2182 SourceLocation UDSuffixLoc =
2183 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2184 Literal.getUDSuffixOffset());
2185 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2186 }
2187
2188 return Lit;
2189}
2190
2191std::vector<Token>
2193 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2194 // local macros that expand to string literals that may be concatenated.
2195 // These macros are expanded here (in Sema), because StringLiteralParser
2196 // (in Lex) doesn't know the enclosing function (because it hasn't been
2197 // parsed yet).
2198 assert(getLangOpts().MicrosoftExt);
2199
2200 // Note: Although function local macros are defined only inside functions,
2201 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2202 // expansion of macros into empty string literals without additional checks.
2203 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2204 if (!CurrentDecl)
2205 CurrentDecl = Context.getTranslationUnitDecl();
2206
2207 std::vector<Token> ExpandedToks;
2208 ExpandedToks.reserve(Toks.size());
2209 for (const Token &Tok : Toks) {
2211 assert(tok::isStringLiteral(Tok.getKind()));
2212 ExpandedToks.emplace_back(Tok);
2213 continue;
2214 }
2215 if (isa<TranslationUnitDecl>(CurrentDecl))
2216 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2217 // Stringify predefined expression
2218 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2219 << Tok.getKind();
2220 SmallString<64> Str;
2221 llvm::raw_svector_ostream OS(Str);
2222 Token &Exp = ExpandedToks.emplace_back();
2223 Exp.startToken();
2224 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2225 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2226 OS << 'L';
2227 Exp.setKind(tok::wide_string_literal);
2228 } else {
2229 Exp.setKind(tok::string_literal);
2230 }
2231 OS << '"'
2233 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2234 << '"';
2235 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2236 }
2237 return ExpandedToks;
2238}
2239
2242 assert(!StringToks.empty() && "Must have at least one string!");
2243
2244 // StringToks needs backing storage as it doesn't hold array elements itself
2245 std::vector<Token> ExpandedToks;
2246 if (getLangOpts().MicrosoftExt)
2247 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2248
2249 StringLiteralParser Literal(
2251 if (Literal.hadError)
2252 return ExprError();
2253
2254 SmallVector<SourceLocation, 4> StringTokLocs;
2255 for (const Token &Tok : StringToks)
2256 StringTokLocs.push_back(Tok.getLocation());
2257
2258 QualType CharTy = Context.CharTy;
2260 if (Literal.isWide()) {
2261 CharTy = Context.getWideCharType();
2263 } else if (Literal.isUTF8()) {
2264 if (getLangOpts().Char8)
2265 CharTy = Context.Char8Ty;
2266 else if (getLangOpts().C23)
2267 CharTy = Context.UnsignedCharTy;
2269 } else if (Literal.isUTF16()) {
2270 CharTy = Context.Char16Ty;
2272 } else if (Literal.isUTF32()) {
2273 CharTy = Context.Char32Ty;
2275 } else if (Literal.isPascal()) {
2276 CharTy = Context.UnsignedCharTy;
2277 }
2278
2279 // Warn on u8 string literals before C++20 and C23, whose type
2280 // was an array of char before but becomes an array of char8_t.
2281 // In C++20, it cannot be used where a pointer to char is expected.
2282 // In C23, it might have an unexpected value if char was signed.
2283 if (Kind == StringLiteralKind::UTF8 &&
2285 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2286 : !getLangOpts().C23)) {
2287 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2288 ? diag::warn_cxx20_compat_utf8_string
2289 : diag::warn_c23_compat_utf8_string);
2290
2291 // Create removals for all 'u8' prefixes in the string literal(s). This
2292 // ensures C++20/C23 compatibility (but may change the program behavior when
2293 // built by non-Clang compilers for which the execution character set is
2294 // not always UTF-8).
2295 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2296 SourceLocation RemovalDiagLoc;
2297 for (const Token &Tok : StringToks) {
2298 if (Tok.getKind() == tok::utf8_string_literal) {
2299 if (RemovalDiagLoc.isInvalid())
2300 RemovalDiagLoc = Tok.getLocation();
2302 Tok.getLocation(),
2303 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2305 }
2306 }
2307 Diag(RemovalDiagLoc, RemovalDiag);
2308 }
2309
2310 QualType StrTy =
2311 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2312
2313 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2315 Context, Literal.GetString(), Kind, Literal.Pascal, StrTy, StringTokLocs);
2316 if (Literal.getUDSuffix().empty())
2317 return Lit;
2318
2319 // We're building a user-defined literal.
2320 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2321 SourceLocation UDSuffixLoc =
2322 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2323 Literal.getUDSuffixOffset());
2324
2325 // Make sure we're allowed user-defined literals here.
2326 if (!UDLScope)
2327 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2328
2329 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2330 // operator "" X (str, len)
2331 QualType SizeType = Context.getSizeType();
2332
2333 DeclarationName OpName =
2334 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2335 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2336 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2337
2338 QualType ArgTy[] = {
2339 Context.getArrayDecayedType(StrTy), SizeType
2340 };
2341
2342 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2343 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2344 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2345 /*AllowStringTemplatePack*/ true,
2346 /*DiagnoseMissing*/ true, Lit)) {
2347
2348 case LOLR_Cooked: {
2349 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2350 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2351 StringTokLocs[0]);
2352 Expr *Args[] = { Lit, LenArg };
2353
2354 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2355 }
2356
2357 case LOLR_Template: {
2358 TemplateArgumentListInfo ExplicitArgs;
2359 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2360 TemplateArgumentLocInfo ArgInfo(Lit);
2361 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2362 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2363 &ExplicitArgs);
2364 }
2365
2367 TemplateArgumentListInfo ExplicitArgs;
2368
2369 unsigned CharBits = Context.getIntWidth(CharTy);
2370 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2371 llvm::APSInt Value(CharBits, CharIsUnsigned);
2372
2373 TemplateArgument TypeArg(CharTy);
2374 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2375 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2376
2377 SourceLocation Loc = StringTokLocs.back();
2378 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2379 Value = Lit->getCodeUnit(I);
2380 TemplateArgument Arg(Context, Value, CharTy);
2382 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2383 }
2384 return BuildLiteralOperatorCall(R, OpNameInfo, {}, Loc, &ExplicitArgs);
2385 }
2386 case LOLR_Raw:
2388 llvm_unreachable("unexpected literal operator lookup result");
2389 case LOLR_Error:
2390 return ExprError();
2391 }
2392 llvm_unreachable("unexpected literal operator lookup result");
2393}
2394
2397 SourceLocation Loc,
2398 const CXXScopeSpec *SS) {
2399 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2400 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2401}
2402
2405 const DeclarationNameInfo &NameInfo,
2406 const CXXScopeSpec *SS, NamedDecl *FoundD,
2407 SourceLocation TemplateKWLoc,
2408 const TemplateArgumentListInfo *TemplateArgs) {
2411 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2412 TemplateArgs);
2413}
2414
2415// CUDA/HIP: Check whether a captured reference variable is referencing a
2416// host variable in a device or host device lambda.
2418 VarDecl *VD) {
2419 if (!S.getLangOpts().CUDA || !VD->hasInit())
2420 return false;
2421 assert(VD->getType()->isReferenceType());
2422
2423 // Check whether the reference variable is referencing a host variable.
2424 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2425 if (!DRE)
2426 return false;
2427 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2428 if (!Referee || !Referee->hasGlobalStorage() ||
2429 Referee->hasAttr<CUDADeviceAttr>())
2430 return false;
2431
2432 // Check whether the current function is a device or host device lambda.
2433 // Check whether the reference variable is a capture by getDeclContext()
2434 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2435 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2436 if (MD && MD->getParent()->isLambda() &&
2437 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2438 VD->getDeclContext() != MD)
2439 return true;
2440
2441 return false;
2442}
2443
2445 // A declaration named in an unevaluated operand never constitutes an odr-use.
2447 return NOUR_Unevaluated;
2448
2449 // C++2a [basic.def.odr]p4:
2450 // A variable x whose name appears as a potentially-evaluated expression e
2451 // is odr-used by e unless [...] x is a reference that is usable in
2452 // constant expressions.
2453 // CUDA/HIP:
2454 // If a reference variable referencing a host variable is captured in a
2455 // device or host device lambda, the value of the referee must be copied
2456 // to the capture and the reference variable must be treated as odr-use
2457 // since the value of the referee is not known at compile time and must
2458 // be loaded from the captured.
2459 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2460 if (VD->getType()->isReferenceType() &&
2461 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2463 VD->isUsableInConstantExpressions(Context))
2464 return NOUR_Constant;
2465 }
2466
2467 // All remaining non-variable cases constitute an odr-use. For variables, we
2468 // need to wait and see how the expression is used.
2469 return NOUR_None;
2470}
2471
2474 const DeclarationNameInfo &NameInfo,
2475 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2476 SourceLocation TemplateKWLoc,
2477 const TemplateArgumentListInfo *TemplateArgs) {
2478 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2479 NeedToCaptureVariable(D, NameInfo.getLoc());
2480
2482 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2483 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2485
2486 // C++ [except.spec]p17:
2487 // An exception-specification is considered to be needed when:
2488 // - in an expression, the function is the unique lookup result or
2489 // the selected member of a set of overloaded functions.
2490 //
2491 // We delay doing this until after we've built the function reference and
2492 // marked it as used so that:
2493 // a) if the function is defaulted, we get errors from defining it before /
2494 // instead of errors from computing its exception specification, and
2495 // b) if the function is a defaulted comparison, we can use the body we
2496 // build when defining it as input to the exception specification
2497 // computation rather than computing a new body.
2498 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2499 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2500 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2501 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2502 }
2503 }
2504
2505 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2507 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2509
2510 const auto *FD = dyn_cast<FieldDecl>(D);
2511 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2512 FD = IFD->getAnonField();
2513 if (FD) {
2514 UnusedPrivateFields.remove(FD);
2515 // Just in case we're building an illegal pointer-to-member.
2516 if (FD->isBitField())
2518 }
2519
2520 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2521 // designates a bit-field.
2522 if (const auto *BD = dyn_cast<BindingDecl>(D))
2523 if (const auto *BE = BD->getBinding())
2524 E->setObjectKind(BE->getObjectKind());
2525
2526 return E;
2527}
2528
2529void
2532 DeclarationNameInfo &NameInfo,
2533 const TemplateArgumentListInfo *&TemplateArgs) {
2535 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2536 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2537
2538 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2539 Id.TemplateId->NumArgs);
2540 translateTemplateArguments(TemplateArgsPtr, Buffer);
2541
2542 TemplateName TName = Id.TemplateId->Template.get();
2544 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2545 TemplateArgs = &Buffer;
2546 } else {
2547 NameInfo = GetNameFromUnqualifiedId(Id);
2548 TemplateArgs = nullptr;
2549 }
2550}
2551
2553 // During a default argument instantiation the CurContext points
2554 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2555 // function parameter list, hence add an explicit check.
2556 bool isDefaultArgument =
2557 !CodeSynthesisContexts.empty() &&
2558 CodeSynthesisContexts.back().Kind ==
2560 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2561 bool isInstance = CurMethod && CurMethod->isInstance() &&
2562 R.getNamingClass() == CurMethod->getParent() &&
2563 !isDefaultArgument;
2564
2565 // There are two ways we can find a class-scope declaration during template
2566 // instantiation that we did not find in the template definition: if it is a
2567 // member of a dependent base class, or if it is declared after the point of
2568 // use in the same class. Distinguish these by comparing the class in which
2569 // the member was found to the naming class of the lookup.
2570 unsigned DiagID = diag::err_found_in_dependent_base;
2571 unsigned NoteID = diag::note_member_declared_at;
2572 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2573 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2574 : diag::err_found_later_in_class;
2575 } else if (getLangOpts().MSVCCompat) {
2576 DiagID = diag::ext_found_in_dependent_base;
2577 NoteID = diag::note_dependent_member_use;
2578 }
2579
2580 if (isInstance) {
2581 // Give a code modification hint to insert 'this->'.
2582 Diag(R.getNameLoc(), DiagID)
2583 << R.getLookupName()
2584 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2585 CheckCXXThisCapture(R.getNameLoc());
2586 } else {
2587 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2588 // they're not shadowed).
2589 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2590 }
2591
2592 for (const NamedDecl *D : R)
2593 Diag(D->getLocation(), NoteID);
2594
2595 // Return true if we are inside a default argument instantiation
2596 // and the found name refers to an instance member function, otherwise
2597 // the caller will try to create an implicit member call and this is wrong
2598 // for default arguments.
2599 //
2600 // FIXME: Is this special case necessary? We could allow the caller to
2601 // diagnose this.
2602 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2603 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2604 return true;
2605 }
2606
2607 // Tell the callee to try to recover.
2608 return false;
2609}
2610
2613 TemplateArgumentListInfo *ExplicitTemplateArgs,
2614 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2615 DeclarationName Name = R.getLookupName();
2616 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2617
2618 unsigned diagnostic = diag::err_undeclared_var_use;
2619 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2623 diagnostic = diag::err_undeclared_use;
2624 diagnostic_suggest = diag::err_undeclared_use_suggest;
2625 }
2626
2627 // If the original lookup was an unqualified lookup, fake an
2628 // unqualified lookup. This is useful when (for example) the
2629 // original lookup would not have found something because it was a
2630 // dependent name.
2631 DeclContext *DC =
2632 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2633 while (DC) {
2634 if (isa<CXXRecordDecl>(DC)) {
2635 if (ExplicitTemplateArgs) {
2637 R, S, SS, Context.getCanonicalTagType(cast<CXXRecordDecl>(DC)),
2638 /*EnteringContext*/ false, TemplateNameIsRequired,
2639 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2640 return true;
2641 } else {
2642 LookupQualifiedName(R, DC);
2643 }
2644
2645 if (!R.empty()) {
2646 // Don't give errors about ambiguities in this lookup.
2647 R.suppressDiagnostics();
2648
2649 // If there's a best viable function among the results, only mention
2650 // that one in the notes.
2651 OverloadCandidateSet Candidates(R.getNameLoc(),
2653 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2655 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2656 OR_Success) {
2657 R.clear();
2658 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2659 R.resolveKind();
2660 }
2661
2663 }
2664
2665 R.clear();
2666 }
2667
2668 DC = DC->getLookupParent();
2669 }
2670
2671 // We didn't find anything, so try to correct for a typo.
2672 TypoCorrection Corrected;
2673 if (S && (Corrected =
2674 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2675 CCC, CorrectTypoKind::ErrorRecovery, LookupCtx))) {
2676 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2677 bool DroppedSpecifier =
2678 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2679 R.setLookupName(Corrected.getCorrection());
2680
2681 bool AcceptableWithRecovery = false;
2682 bool AcceptableWithoutRecovery = false;
2683 NamedDecl *ND = Corrected.getFoundDecl();
2684 if (ND) {
2685 if (Corrected.isOverloaded()) {
2686 OverloadCandidateSet OCS(R.getNameLoc(),
2689 for (NamedDecl *CD : Corrected) {
2690 if (FunctionTemplateDecl *FTD =
2691 dyn_cast<FunctionTemplateDecl>(CD))
2693 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2694 Args, OCS);
2695 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2696 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2698 Args, OCS);
2699 }
2700 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2701 case OR_Success:
2702 ND = Best->FoundDecl;
2703 Corrected.setCorrectionDecl(ND);
2704 break;
2705 default:
2706 // FIXME: Arbitrarily pick the first declaration for the note.
2707 Corrected.setCorrectionDecl(ND);
2708 break;
2709 }
2710 }
2711 R.addDecl(ND);
2712 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2715 if (!Record)
2718 R.setNamingClass(Record);
2719 }
2720
2721 auto *UnderlyingND = ND->getUnderlyingDecl();
2722 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2723 isa<FunctionTemplateDecl>(UnderlyingND);
2724 // FIXME: If we ended up with a typo for a type name or
2725 // Objective-C class name, we're in trouble because the parser
2726 // is in the wrong place to recover. Suggest the typo
2727 // correction, but don't make it a fix-it since we're not going
2728 // to recover well anyway.
2729 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2730 getAsTypeTemplateDecl(UnderlyingND) ||
2731 isa<ObjCInterfaceDecl>(UnderlyingND);
2732 } else {
2733 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2734 // because we aren't able to recover.
2735 AcceptableWithoutRecovery = true;
2736 }
2737
2738 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2739 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2740 ? diag::note_implicit_param_decl
2741 : diag::note_previous_decl;
2742 if (SS.isEmpty())
2743 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name << NameRange,
2744 PDiag(NoteID), AcceptableWithRecovery);
2745 else
2746 diagnoseTypo(Corrected,
2747 PDiag(diag::err_no_member_suggest)
2748 << Name << computeDeclContext(SS, false)
2749 << DroppedSpecifier << NameRange,
2750 PDiag(NoteID), AcceptableWithRecovery);
2751
2752 if (Corrected.WillReplaceSpecifier()) {
2754 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2755 SS.MakeTrivial(Context, NNS,
2756 NNS ? NameRange.getBegin() : SourceRange());
2757 }
2758
2759 // Tell the callee whether to try to recover.
2760 return !AcceptableWithRecovery;
2761 }
2762 }
2763 R.clear();
2764
2765 // Emit a special diagnostic for failed member lookups.
2766 // FIXME: computing the declaration context might fail here (?)
2767 if (!SS.isEmpty()) {
2768 Diag(R.getNameLoc(), diag::err_no_member)
2769 << Name << computeDeclContext(SS, false) << NameRange;
2770 return true;
2771 }
2772
2773 // Give up, we can't recover.
2774 Diag(R.getNameLoc(), diagnostic) << Name << NameRange;
2775 return true;
2776}
2777
2778/// In Microsoft mode, if we are inside a template class whose parent class has
2779/// dependent base classes, and we can't resolve an unqualified identifier, then
2780/// assume the identifier is a member of a dependent base class. We can only
2781/// recover successfully in static methods, instance methods, and other contexts
2782/// where 'this' is available. This doesn't precisely match MSVC's
2783/// instantiation model, but it's close enough.
2784static Expr *
2786 DeclarationNameInfo &NameInfo,
2787 SourceLocation TemplateKWLoc,
2788 const TemplateArgumentListInfo *TemplateArgs) {
2789 // Only try to recover from lookup into dependent bases in static methods or
2790 // contexts where 'this' is available.
2791 QualType ThisType = S.getCurrentThisType();
2792 const CXXRecordDecl *RD = nullptr;
2793 if (!ThisType.isNull())
2794 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2795 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2796 RD = MD->getParent();
2797 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2798 return nullptr;
2799
2800 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2801 // is available, suggest inserting 'this->' as a fixit.
2802 SourceLocation Loc = NameInfo.getLoc();
2803 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2804 DB << NameInfo.getName() << RD;
2805
2806 if (!ThisType.isNull()) {
2807 DB << FixItHint::CreateInsertion(Loc, "this->");
2809 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2810 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2811 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2812 }
2813
2814 // Synthesize a fake NNS that points to the derived class. This will
2815 // perform name lookup during template instantiation.
2816 CXXScopeSpec SS;
2817 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD)->getTypePtr());
2818 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2820 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2821 TemplateArgs);
2822}
2823
2825 SourceLocation TemplateKWLoc,
2826 UnqualifiedId &Id, bool HasTrailingLParen,
2827 bool IsAddressOfOperand,
2829 bool IsInlineAsmIdentifier) {
2830 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2831 "cannot be direct & operand and have a trailing lparen");
2832 if (SS.isInvalid())
2833 return ExprError();
2834
2835 TemplateArgumentListInfo TemplateArgsBuffer;
2836
2837 // Decompose the UnqualifiedId into the following data.
2838 DeclarationNameInfo NameInfo;
2839 const TemplateArgumentListInfo *TemplateArgs;
2840 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2841
2842 DeclarationName Name = NameInfo.getName();
2844 SourceLocation NameLoc = NameInfo.getLoc();
2845
2846 if (II && II->isEditorPlaceholder()) {
2847 // FIXME: When typed placeholders are supported we can create a typed
2848 // placeholder expression node.
2849 return ExprError();
2850 }
2851
2852 // This specially handles arguments of attributes appertains to a type of C
2853 // struct field such that the name lookup within a struct finds the member
2854 // name, which is not the case for other contexts in C.
2855 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2856 // See if this is reference to a field of struct.
2857 LookupResult R(*this, NameInfo, LookupMemberName);
2858 // LookupName handles a name lookup from within anonymous struct.
2859 if (LookupName(R, S)) {
2860 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2861 QualType type = VD->getType().getNonReferenceType();
2862 // This will eventually be translated into MemberExpr upon
2863 // the use of instantiated struct fields.
2864 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2865 }
2866 }
2867 }
2868
2869 // Perform the required lookup.
2870 LookupResult R(*this, NameInfo,
2874 if (TemplateKWLoc.isValid() || TemplateArgs) {
2875 // Lookup the template name again to correctly establish the context in
2876 // which it was found. This is really unfortunate as we already did the
2877 // lookup to determine that it was a template name in the first place. If
2878 // this becomes a performance hit, we can work harder to preserve those
2879 // results until we get here but it's likely not worth it.
2880 AssumedTemplateKind AssumedTemplate;
2881 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2882 /*EnteringContext=*/false, TemplateKWLoc,
2883 &AssumedTemplate))
2884 return ExprError();
2885
2886 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2887 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2888 IsAddressOfOperand, TemplateArgs);
2889 } else {
2890 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2891 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2892 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2893
2894 // If the result might be in a dependent base class, this is a dependent
2895 // id-expression.
2896 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2897 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2898 IsAddressOfOperand, TemplateArgs);
2899
2900 // If this reference is in an Objective-C method, then we need to do
2901 // some special Objective-C lookup, too.
2902 if (IvarLookupFollowUp) {
2903 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2904 if (E.isInvalid())
2905 return ExprError();
2906
2907 if (Expr *Ex = E.getAs<Expr>())
2908 return Ex;
2909 }
2910 }
2911
2912 if (R.isAmbiguous())
2913 return ExprError();
2914
2915 // This could be an implicitly declared function reference if the language
2916 // mode allows it as a feature.
2917 if (R.empty() && HasTrailingLParen && II &&
2918 getLangOpts().implicitFunctionsAllowed()) {
2919 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2920 if (D) R.addDecl(D);
2921 }
2922
2923 // Determine whether this name might be a candidate for
2924 // argument-dependent lookup.
2925 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2926
2927 if (R.empty() && !ADL) {
2928 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2929 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2930 TemplateKWLoc, TemplateArgs))
2931 return E;
2932 }
2933
2934 // Don't diagnose an empty lookup for inline assembly.
2935 if (IsInlineAsmIdentifier)
2936 return ExprError();
2937
2938 // If this name wasn't predeclared and if this is not a function
2939 // call, diagnose the problem.
2940 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2941 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2942 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2943 "Typo correction callback misconfigured");
2944 if (CCC) {
2945 // Make sure the callback knows what the typo being diagnosed is.
2946 CCC->setTypoName(II);
2947 if (SS.isValid())
2948 CCC->setTypoNNS(SS.getScopeRep());
2949 }
2950 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2951 // a template name, but we happen to have always already looked up the name
2952 // before we get here if it must be a template name.
2953 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2954 {}, nullptr))
2955 return ExprError();
2956
2957 assert(!R.empty() &&
2958 "DiagnoseEmptyLookup returned false but added no results");
2959
2960 // If we found an Objective-C instance variable, let
2961 // LookupInObjCMethod build the appropriate expression to
2962 // reference the ivar.
2963 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2964 R.clear();
2965 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2966 // In a hopelessly buggy code, Objective-C instance variable
2967 // lookup fails and no expression will be built to reference it.
2968 if (!E.isInvalid() && !E.get())
2969 return ExprError();
2970 return E;
2971 }
2972 }
2973
2974 // This is guaranteed from this point on.
2975 assert(!R.empty() || ADL);
2976
2977 // Check whether this might be a C++ implicit instance member access.
2978 // C++ [class.mfct.non-static]p3:
2979 // When an id-expression that is not part of a class member access
2980 // syntax and not used to form a pointer to member is used in the
2981 // body of a non-static member function of class X, if name lookup
2982 // resolves the name in the id-expression to a non-static non-type
2983 // member of some class C, the id-expression is transformed into a
2984 // class member access expression using (*this) as the
2985 // postfix-expression to the left of the . operator.
2986 //
2987 // But we don't actually need to do this for '&' operands if R
2988 // resolved to a function or overloaded function set, because the
2989 // expression is ill-formed if it actually works out to be a
2990 // non-static member function:
2991 //
2992 // C++ [expr.ref]p4:
2993 // Otherwise, if E1.E2 refers to a non-static member function. . .
2994 // [t]he expression can be used only as the left-hand operand of a
2995 // member function call.
2996 //
2997 // There are other safeguards against such uses, but it's important
2998 // to get this right here so that we don't end up making a
2999 // spuriously dependent expression if we're inside a dependent
3000 // instance method.
3001 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3002 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
3003 S);
3004
3005 if (TemplateArgs || TemplateKWLoc.isValid()) {
3006
3007 // In C++1y, if this is a variable template id, then check it
3008 // in BuildTemplateIdExpr().
3009 // The single lookup result must be a variable template declaration.
3013 assert(R.getAsSingle<TemplateDecl>() &&
3014 "There should only be one declaration found.");
3015 }
3016
3017 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
3018 }
3019
3020 return BuildDeclarationNameExpr(SS, R, ADL);
3021}
3022
3024 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3025 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3026 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3027 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
3028
3029 if (R.isAmbiguous())
3030 return ExprError();
3031
3032 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3033 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3034 NameInfo, /*TemplateArgs=*/nullptr);
3035
3036 if (R.empty()) {
3037 // Don't diagnose problems with invalid record decl, the secondary no_member
3038 // diagnostic during template instantiation is likely bogus, e.g. if a class
3039 // is invalid because it's derived from an invalid base class, then missing
3040 // members were likely supposed to be inherited.
3042 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
3043 if (CD->isInvalidDecl() || CD->isBeingDefined())
3044 return ExprError();
3045 Diag(NameInfo.getLoc(), diag::err_no_member)
3046 << NameInfo.getName() << DC << SS.getRange();
3047 return ExprError();
3048 }
3049
3050 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3051 QualType ET;
3052 TypeLocBuilder TLB;
3053 if (auto *TagD = dyn_cast<TagDecl>(TD)) {
3054 ET = SemaRef.Context.getTagType(ElaboratedTypeKeyword::None,
3055 SS.getScopeRep(), TagD,
3056 /*OwnsTag=*/false);
3057 auto TL = TLB.push<TagTypeLoc>(ET);
3059 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3060 TL.setNameLoc(NameInfo.getLoc());
3061 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(TD)) {
3062 ET = SemaRef.Context.getTypedefType(ElaboratedTypeKeyword::None,
3063 SS.getScopeRep(), TypedefD);
3064 TLB.push<TypedefTypeLoc>(ET).set(
3065 /*ElaboratedKeywordLoc=*/SourceLocation(),
3066 SS.getWithLocInContext(Context), NameInfo.getLoc());
3067 } else {
3068 // FIXME: What else can appear here?
3069 ET = SemaRef.Context.getTypeDeclType(TD);
3070 TLB.pushTypeSpec(ET).setNameLoc(NameInfo.getLoc());
3071 assert(SS.isEmpty());
3072 }
3073
3074 // Diagnose a missing typename if this resolved unambiguously to a type in
3075 // a dependent context. If we can recover with a type, downgrade this to
3076 // a warning in Microsoft compatibility mode.
3077 unsigned DiagID = diag::err_typename_missing;
3078 if (RecoveryTSI && getLangOpts().MSVCCompat)
3079 DiagID = diag::ext_typename_missing;
3080 SourceLocation Loc = SS.getBeginLoc();
3081 auto D = Diag(Loc, DiagID);
3082 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3083
3084 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3085 // context.
3086 if (!RecoveryTSI)
3087 return ExprError();
3088
3089 // Only issue the fixit if we're prepared to recover.
3090 D << FixItHint::CreateInsertion(Loc, "typename ");
3091
3092 // Recover by pretending this was an elaborated type.
3093 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3094
3095 return ExprEmpty();
3096 }
3097
3098 // If necessary, build an implicit class member access.
3099 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3101 /*TemplateKWLoc=*/SourceLocation(),
3102 R, /*TemplateArgs=*/nullptr,
3103 /*S=*/nullptr);
3104
3105 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
3106}
3107
3109 NestedNameSpecifier Qualifier,
3110 NamedDecl *FoundDecl,
3111 NamedDecl *Member) {
3112 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3113 if (!RD)
3114 return From;
3115
3116 QualType DestRecordType;
3117 QualType DestType;
3118 QualType FromRecordType;
3119 QualType FromType = From->getType();
3120 bool PointerConversions = false;
3121 if (isa<FieldDecl>(Member)) {
3122 DestRecordType = Context.getCanonicalTagType(RD);
3123 auto FromPtrType = FromType->getAs<PointerType>();
3124 DestRecordType = Context.getAddrSpaceQualType(
3125 DestRecordType, FromPtrType
3126 ? FromType->getPointeeType().getAddressSpace()
3127 : FromType.getAddressSpace());
3128
3129 if (FromPtrType) {
3130 DestType = Context.getPointerType(DestRecordType);
3131 FromRecordType = FromPtrType->getPointeeType();
3132 PointerConversions = true;
3133 } else {
3134 DestType = DestRecordType;
3135 FromRecordType = FromType;
3136 }
3137 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3138 if (!Method->isImplicitObjectMemberFunction())
3139 return From;
3140
3141 DestType = Method->getThisType().getNonReferenceType();
3142 DestRecordType = Method->getFunctionObjectParameterType();
3143
3144 if (FromType->getAs<PointerType>()) {
3145 FromRecordType = FromType->getPointeeType();
3146 PointerConversions = true;
3147 } else {
3148 FromRecordType = FromType;
3149 DestType = DestRecordType;
3150 }
3151
3152 LangAS FromAS = FromRecordType.getAddressSpace();
3153 LangAS DestAS = DestRecordType.getAddressSpace();
3154 if (FromAS != DestAS) {
3155 QualType FromRecordTypeWithoutAS =
3156 Context.removeAddrSpaceQualType(FromRecordType);
3157 QualType FromTypeWithDestAS =
3158 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3159 if (PointerConversions)
3160 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3161 From = ImpCastExprToType(From, FromTypeWithDestAS,
3162 CK_AddressSpaceConversion, From->getValueKind())
3163 .get();
3164 }
3165 } else {
3166 // No conversion necessary.
3167 return From;
3168 }
3169
3170 if (DestType->isDependentType() || FromType->isDependentType())
3171 return From;
3172
3173 // If the unqualified types are the same, no conversion is necessary.
3174 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3175 return From;
3176
3177 SourceRange FromRange = From->getSourceRange();
3178 SourceLocation FromLoc = FromRange.getBegin();
3179
3180 ExprValueKind VK = From->getValueKind();
3181
3182 // C++ [class.member.lookup]p8:
3183 // [...] Ambiguities can often be resolved by qualifying a name with its
3184 // class name.
3185 //
3186 // If the member was a qualified name and the qualified referred to a
3187 // specific base subobject type, we'll cast to that intermediate type
3188 // first and then to the object in which the member is declared. That allows
3189 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3190 //
3191 // class Base { public: int x; };
3192 // class Derived1 : public Base { };
3193 // class Derived2 : public Base { };
3194 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3195 //
3196 // void VeryDerived::f() {
3197 // x = 17; // error: ambiguous base subobjects
3198 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3199 // }
3200 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3201 QualType QType = QualType(Qualifier.getAsType(), 0);
3202 assert(QType->isRecordType() && "lookup done with non-record type");
3203
3204 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3205
3206 // In C++98, the qualifier type doesn't actually have to be a base
3207 // type of the object type, in which case we just ignore it.
3208 // Otherwise build the appropriate casts.
3209 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3210 CXXCastPath BasePath;
3211 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3212 FromLoc, FromRange, &BasePath))
3213 return ExprError();
3214
3215 if (PointerConversions)
3216 QType = Context.getPointerType(QType);
3217 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3218 VK, &BasePath).get();
3219
3220 FromType = QType;
3221 FromRecordType = QRecordType;
3222
3223 // If the qualifier type was the same as the destination type,
3224 // we're done.
3225 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3226 return From;
3227 }
3228 }
3229
3230 CXXCastPath BasePath;
3231 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3232 FromLoc, FromRange, &BasePath,
3233 /*IgnoreAccess=*/true))
3234 return ExprError();
3235
3236 // Propagate qualifiers to base subobjects as per:
3237 // C++ [basic.type.qualifier]p1.2:
3238 // A volatile object is [...] a subobject of a volatile object.
3239 Qualifiers FromTypeQuals = FromType.getQualifiers();
3240 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3241 DestType = Context.getQualifiedType(DestType, FromTypeQuals);
3242
3243 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, VK,
3244 &BasePath);
3245}
3246
3248 const LookupResult &R,
3249 bool HasTrailingLParen) {
3250 // Only when used directly as the postfix-expression of a call.
3251 if (!HasTrailingLParen)
3252 return false;
3253
3254 // Never if a scope specifier was provided.
3255 if (SS.isNotEmpty())
3256 return false;
3257
3258 // Only in C++ or ObjC++.
3259 if (!getLangOpts().CPlusPlus)
3260 return false;
3261
3262 // Turn off ADL when we find certain kinds of declarations during
3263 // normal lookup:
3264 for (const NamedDecl *D : R) {
3265 // C++0x [basic.lookup.argdep]p3:
3266 // -- a declaration of a class member
3267 // Since using decls preserve this property, we check this on the
3268 // original decl.
3269 if (D->isCXXClassMember())
3270 return false;
3271
3272 // C++0x [basic.lookup.argdep]p3:
3273 // -- a block-scope function declaration that is not a
3274 // using-declaration
3275 // NOTE: we also trigger this for function templates (in fact, we
3276 // don't check the decl type at all, since all other decl types
3277 // turn off ADL anyway).
3278 if (isa<UsingShadowDecl>(D))
3279 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3280 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3281 return false;
3282
3283 // C++0x [basic.lookup.argdep]p3:
3284 // -- a declaration that is neither a function or a function
3285 // template
3286 // And also for builtin functions.
3287 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3288 // But also builtin functions.
3289 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3290 return false;
3291 } else if (!isa<FunctionTemplateDecl>(D))
3292 return false;
3293 }
3294
3295 return true;
3296}
3297
3298
3299/// Diagnoses obvious problems with the use of the given declaration
3300/// as an expression. This is only actually called for lookups that
3301/// were not overloaded, and it doesn't promise that the declaration
3302/// will in fact be used.
3304 bool AcceptInvalid) {
3305 if (D->isInvalidDecl() && !AcceptInvalid)
3306 return true;
3307
3308 if (isa<TypedefNameDecl>(D)) {
3309 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3310 return true;
3311 }
3312
3313 if (isa<ObjCInterfaceDecl>(D)) {
3314 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3315 return true;
3316 }
3317
3318 if (isa<NamespaceDecl>(D)) {
3319 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3320 return true;
3321 }
3322
3323 return false;
3324}
3325
3326// Certain multiversion types should be treated as overloaded even when there is
3327// only one result.
3329 assert(R.isSingleResult() && "Expected only a single result");
3330 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3331 return FD &&
3332 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3333}
3334
3336 LookupResult &R, bool NeedsADL,
3337 bool AcceptInvalidDecl) {
3338 // If this is a single, fully-resolved result and we don't need ADL,
3339 // just build an ordinary singleton decl ref.
3340 if (!NeedsADL && R.isSingleResult() &&
3341 !R.getAsSingle<FunctionTemplateDecl>() &&
3343 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3344 R.getRepresentativeDecl(), nullptr,
3345 AcceptInvalidDecl);
3346
3347 // We only need to check the declaration if there's exactly one
3348 // result, because in the overloaded case the results can only be
3349 // functions and function templates.
3350 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3351 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3352 AcceptInvalidDecl))
3353 return ExprError();
3354
3355 // Otherwise, just build an unresolved lookup expression. Suppress
3356 // any lookup-related diagnostics; we'll hash these out later, when
3357 // we've picked a target.
3358 R.suppressDiagnostics();
3359
3361 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
3362 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3363 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3364
3365 return ULE;
3366}
3367
3369 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3370 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3371 bool AcceptInvalidDecl) {
3372 assert(D && "Cannot refer to a NULL declaration");
3373 assert(!isa<FunctionTemplateDecl>(D) &&
3374 "Cannot refer unambiguously to a function template");
3375
3376 SourceLocation Loc = NameInfo.getLoc();
3377 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3378 // Recovery from invalid cases (e.g. D is an invalid Decl).
3379 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3380 // diagnostics, as invalid decls use int as a fallback type.
3381 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3382 }
3383
3384 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3385 // Specifically diagnose references to class templates that are missing
3386 // a template argument list.
3387 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3388 return ExprError();
3389 }
3390
3391 // Make sure that we're referring to a value.
3393 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3394 Diag(D->getLocation(), diag::note_declared_at);
3395 return ExprError();
3396 }
3397
3398 // Check whether this declaration can be used. Note that we suppress
3399 // this check when we're going to perform argument-dependent lookup
3400 // on this function name, because this might not be the function
3401 // that overload resolution actually selects.
3402 if (DiagnoseUseOfDecl(D, Loc))
3403 return ExprError();
3404
3405 auto *VD = cast<ValueDecl>(D);
3406
3407 // Only create DeclRefExpr's for valid Decl's.
3408 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3409 return ExprError();
3410
3411 // Handle members of anonymous structs and unions. If we got here,
3412 // and the reference is to a class member indirect field, then this
3413 // must be the subject of a pointer-to-member expression.
3414 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3415 IndirectField && !IndirectField->isCXXClassMember())
3417 IndirectField);
3418
3419 QualType type = VD->getType();
3420 if (type.isNull())
3421 return ExprError();
3422 ExprValueKind valueKind = VK_PRValue;
3423
3424 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3425 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3426 // is expanded by some outer '...' in the context of the use.
3427 type = type.getNonPackExpansionType();
3428
3429 switch (D->getKind()) {
3430 // Ignore all the non-ValueDecl kinds.
3431#define ABSTRACT_DECL(kind)
3432#define VALUE(type, base)
3433#define DECL(type, base) case Decl::type:
3434#include "clang/AST/DeclNodes.inc"
3435 llvm_unreachable("invalid value decl kind");
3436
3437 // These shouldn't make it here.
3438 case Decl::ObjCAtDefsField:
3439 llvm_unreachable("forming non-member reference to ivar?");
3440
3441 // Enum constants are always r-values and never references.
3442 // Unresolved using declarations are dependent.
3443 case Decl::EnumConstant:
3444 case Decl::UnresolvedUsingValue:
3445 case Decl::OMPDeclareReduction:
3446 case Decl::OMPDeclareMapper:
3447 valueKind = VK_PRValue;
3448 break;
3449
3450 // Fields and indirect fields that got here must be for
3451 // pointer-to-member expressions; we just call them l-values for
3452 // internal consistency, because this subexpression doesn't really
3453 // exist in the high-level semantics.
3454 case Decl::Field:
3455 case Decl::IndirectField:
3456 case Decl::ObjCIvar:
3457 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3458 "building reference to field in C?");
3459
3460 // These can't have reference type in well-formed programs, but
3461 // for internal consistency we do this anyway.
3462 type = type.getNonReferenceType();
3463 valueKind = VK_LValue;
3464 break;
3465
3466 // Non-type template parameters are either l-values or r-values
3467 // depending on the type.
3468 case Decl::NonTypeTemplateParm: {
3469 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3470 type = reftype->getPointeeType();
3471 valueKind = VK_LValue; // even if the parameter is an r-value reference
3472 break;
3473 }
3474
3475 // [expr.prim.id.unqual]p2:
3476 // If the entity is a template parameter object for a template
3477 // parameter of type T, the type of the expression is const T.
3478 // [...] The expression is an lvalue if the entity is a [...] template
3479 // parameter object.
3480 if (type->isRecordType()) {
3481 type = type.getUnqualifiedType().withConst();
3482 valueKind = VK_LValue;
3483 break;
3484 }
3485
3486 // For non-references, we need to strip qualifiers just in case
3487 // the template parameter was declared as 'const int' or whatever.
3488 valueKind = VK_PRValue;
3489 type = type.getUnqualifiedType();
3490 break;
3491 }
3492
3493 case Decl::Var:
3494 case Decl::VarTemplateSpecialization:
3495 case Decl::VarTemplatePartialSpecialization:
3496 case Decl::Decomposition:
3497 case Decl::Binding:
3498 case Decl::OMPCapturedExpr:
3499 // In C, "extern void blah;" is valid and is an r-value.
3500 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3501 type->isVoidType()) {
3502 valueKind = VK_PRValue;
3503 break;
3504 }
3505 [[fallthrough]];
3506
3507 case Decl::ImplicitParam:
3508 case Decl::ParmVar: {
3509 // These are always l-values.
3510 valueKind = VK_LValue;
3511 type = type.getNonReferenceType();
3512
3513 // FIXME: Does the addition of const really only apply in
3514 // potentially-evaluated contexts? Since the variable isn't actually
3515 // captured in an unevaluated context, it seems that the answer is no.
3516 if (!isUnevaluatedContext()) {
3517 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3518 if (!CapturedType.isNull())
3519 type = CapturedType;
3520 }
3521 break;
3522 }
3523
3524 case Decl::Function: {
3525 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3526 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3527 type = Context.BuiltinFnTy;
3528 valueKind = VK_PRValue;
3529 break;
3530 }
3531 }
3532
3533 const FunctionType *fty = type->castAs<FunctionType>();
3534
3535 // If we're referring to a function with an __unknown_anytype
3536 // result type, make the entire expression __unknown_anytype.
3537 if (fty->getReturnType() == Context.UnknownAnyTy) {
3538 type = Context.UnknownAnyTy;
3539 valueKind = VK_PRValue;
3540 break;
3541 }
3542
3543 // Functions are l-values in C++.
3544 if (getLangOpts().CPlusPlus) {
3545 valueKind = VK_LValue;
3546 break;
3547 }
3548
3549 // C99 DR 316 says that, if a function type comes from a
3550 // function definition (without a prototype), that type is only
3551 // used for checking compatibility. Therefore, when referencing
3552 // the function, we pretend that we don't have the full function
3553 // type.
3554 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3555 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3556 fty->getExtInfo());
3557
3558 // Functions are r-values in C.
3559 valueKind = VK_PRValue;
3560 break;
3561 }
3562
3563 case Decl::CXXDeductionGuide:
3564 llvm_unreachable("building reference to deduction guide");
3565
3566 case Decl::MSProperty:
3567 case Decl::MSGuid:
3568 case Decl::TemplateParamObject:
3569 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3570 // capture in OpenMP, or duplicated between host and device?
3571 valueKind = VK_LValue;
3572 break;
3573
3574 case Decl::UnnamedGlobalConstant:
3575 valueKind = VK_LValue;
3576 break;
3577
3578 case Decl::CXXMethod:
3579 // If we're referring to a method with an __unknown_anytype
3580 // result type, make the entire expression __unknown_anytype.
3581 // This should only be possible with a type written directly.
3582 if (const FunctionProtoType *proto =
3583 dyn_cast<FunctionProtoType>(VD->getType()))
3584 if (proto->getReturnType() == Context.UnknownAnyTy) {
3585 type = Context.UnknownAnyTy;
3586 valueKind = VK_PRValue;
3587 break;
3588 }
3589
3590 // C++ methods are l-values if static, r-values if non-static.
3591 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3592 valueKind = VK_LValue;
3593 break;
3594 }
3595 [[fallthrough]];
3596
3597 case Decl::CXXConversion:
3598 case Decl::CXXDestructor:
3599 case Decl::CXXConstructor:
3600 valueKind = VK_PRValue;
3601 break;
3602 }
3603
3604 auto *E =
3605 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3606 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3607 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3608 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3609 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3610 // diagnostics).
3611 if (VD->isInvalidDecl() && E)
3612 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3613 return E;
3614}
3615
3616static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3618 Target.resize(CharByteWidth * (Source.size() + 1));
3619 char *ResultPtr = &Target[0];
3620 const llvm::UTF8 *ErrorPtr;
3621 bool success =
3622 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3623 (void)success;
3624 assert(success);
3625 Target.resize(ResultPtr - &Target[0]);
3626}
3627
3630 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3631 if (!currentDecl) {
3632 Diag(Loc, diag::ext_predef_outside_function);
3633 currentDecl = Context.getTranslationUnitDecl();
3634 }
3635
3636 QualType ResTy;
3637 StringLiteral *SL = nullptr;
3638 if (cast<DeclContext>(currentDecl)->isDependentContext())
3639 ResTy = Context.DependentTy;
3640 else {
3641 // Pre-defined identifiers are of type char[x], where x is the length of
3642 // the string.
3643 bool ForceElaboratedPrinting =
3644 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3645 auto Str =
3646 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3647 unsigned Length = Str.length();
3648
3649 llvm::APInt LengthI(32, Length + 1);
3652 ResTy =
3653 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3654 SmallString<32> RawChars;
3655 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3656 Str, RawChars);
3657 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3659 /*IndexTypeQuals*/ 0);
3661 /*Pascal*/ false, ResTy, Loc);
3662 } else {
3663 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3664 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3666 /*IndexTypeQuals*/ 0);
3668 /*Pascal*/ false, ResTy, Loc);
3669 }
3670 }
3671
3672 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3673 SL);
3674}
3675
3679
3681 SmallString<16> CharBuffer;
3682 bool Invalid = false;
3683 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3684 if (Invalid)
3685 return ExprError();
3686
3687 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3688 PP, Tok.getKind());
3689 if (Literal.hadError())
3690 return ExprError();
3691
3692 QualType Ty;
3693 if (Literal.isWide())
3694 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3695 else if (Literal.isUTF8() && getLangOpts().C23)
3696 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3697 else if (Literal.isUTF8() && getLangOpts().Char8)
3698 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3699 else if (Literal.isUTF16())
3700 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3701 else if (Literal.isUTF32())
3702 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3703 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3704 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3705 else
3706 Ty = Context.CharTy; // 'x' -> char in C++;
3707 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3708
3710 if (Literal.isWide())
3712 else if (Literal.isUTF16())
3714 else if (Literal.isUTF32())
3716 else if (Literal.isUTF8())
3718
3719 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3720 Tok.getLocation());
3721
3722 if (Literal.getUDSuffix().empty())
3723 return Lit;
3724
3725 // We're building a user-defined literal.
3726 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3727 SourceLocation UDSuffixLoc =
3728 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3729
3730 // Make sure we're allowed user-defined literals here.
3731 if (!UDLScope)
3732 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3733
3734 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3735 // operator "" X (ch)
3736 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3737 Lit, Tok.getLocation());
3738}
3739
3741 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3743 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3744 Context.IntTy, Loc);
3745}
3746
3748 ExprResult Inner;
3749 if (getLangOpts().CPlusPlus) {
3750 Inner = ActOnCXXBoolLiteral(Loc, Value ? tok::kw_true : tok::kw_false);
3751 } else {
3752 // C doesn't actually have a way to represent literal values of type
3753 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
3754 Inner = ActOnIntegerConstant(Loc, Value ? 1 : 0);
3755 Inner =
3756 ImpCastExprToType(Inner.get(), Context.BoolTy, CK_IntegralToBoolean);
3757 }
3758 return Inner;
3759}
3760
3762 QualType Ty, SourceLocation Loc) {
3763 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3764
3765 using llvm::APFloat;
3766 APFloat Val(Format);
3767
3768 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3769 if (RM == llvm::RoundingMode::Dynamic)
3770 RM = llvm::RoundingMode::NearestTiesToEven;
3771 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3772
3773 // Overflow is always an error, but underflow is only an error if
3774 // we underflowed to zero (APFloat reports denormals as underflow).
3775 if ((result & APFloat::opOverflow) ||
3776 ((result & APFloat::opUnderflow) && Val.isZero())) {
3777 unsigned diagnostic;
3778 SmallString<20> buffer;
3779 if (result & APFloat::opOverflow) {
3780 diagnostic = diag::warn_float_overflow;
3781 APFloat::getLargest(Format).toString(buffer);
3782 } else {
3783 diagnostic = diag::warn_float_underflow;
3784 APFloat::getSmallest(Format).toString(buffer);
3785 }
3786
3787 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3788 }
3789
3790 bool isExact = (result == APFloat::opOK);
3791 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3792}
3793
3794bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3795 assert(E && "Invalid expression");
3796
3797 if (E->isValueDependent())
3798 return false;
3799
3800 QualType QT = E->getType();
3801 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3802 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3803 return true;
3804 }
3805
3806 llvm::APSInt ValueAPS;
3808
3809 if (R.isInvalid())
3810 return true;
3811
3812 // GCC allows the value of unroll count to be 0.
3813 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3814 // "The values of 0 and 1 block any unrolling of the loop."
3815 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3816 // '#pragma unroll' cases.
3817 bool ValueIsPositive =
3818 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3819 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3820 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3821 << toString(ValueAPS, 10) << ValueIsPositive;
3822 return true;
3823 }
3824
3825 return false;
3826}
3827
3829 // Fast path for a single digit (which is quite common). A single digit
3830 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3831 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3832 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3833 return ActOnIntegerConstant(Tok.getLocation(), Val);
3834 }
3835
3836 SmallString<128> SpellingBuffer;
3837 // NumericLiteralParser wants to overread by one character. Add padding to
3838 // the buffer in case the token is copied to the buffer. If getSpelling()
3839 // returns a StringRef to the memory buffer, it should have a null char at
3840 // the EOF, so it is also safe.
3841 SpellingBuffer.resize(Tok.getLength() + 1);
3842
3843 // Get the spelling of the token, which eliminates trigraphs, etc.
3844 bool Invalid = false;
3845 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3846 if (Invalid)
3847 return ExprError();
3848
3849 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3850 PP.getSourceManager(), PP.getLangOpts(),
3851 PP.getTargetInfo(), PP.getDiagnostics());
3852 if (Literal.hadError)
3853 return ExprError();
3854
3855 if (Literal.hasUDSuffix()) {
3856 // We're building a user-defined literal.
3857 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3858 SourceLocation UDSuffixLoc =
3859 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3860
3861 // Make sure we're allowed user-defined literals here.
3862 if (!UDLScope)
3863 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3864
3865 QualType CookedTy;
3866 if (Literal.isFloatingLiteral()) {
3867 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3868 // long double, the literal is treated as a call of the form
3869 // operator "" X (f L)
3870 CookedTy = Context.LongDoubleTy;
3871 } else {
3872 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3873 // unsigned long long, the literal is treated as a call of the form
3874 // operator "" X (n ULL)
3875 CookedTy = Context.UnsignedLongLongTy;
3876 }
3877
3878 DeclarationName OpName =
3879 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3880 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3881 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3882
3883 SourceLocation TokLoc = Tok.getLocation();
3884
3885 // Perform literal operator lookup to determine if we're building a raw
3886 // literal or a cooked one.
3887 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3888 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3889 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3890 /*AllowStringTemplatePack*/ false,
3891 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3893 // Lookup failure for imaginary constants isn't fatal, there's still the
3894 // GNU extension producing _Complex types.
3895 break;
3896 case LOLR_Error:
3897 return ExprError();
3898 case LOLR_Cooked: {
3899 Expr *Lit;
3900 if (Literal.isFloatingLiteral()) {
3901 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3902 } else {
3903 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3904 if (Literal.GetIntegerValue(ResultVal))
3905 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3906 << /* Unsigned */ 1;
3907 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3908 Tok.getLocation());
3909 }
3910 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3911 }
3912
3913 case LOLR_Raw: {
3914 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3915 // literal is treated as a call of the form
3916 // operator "" X ("n")
3917 unsigned Length = Literal.getUDSuffixOffset();
3918 QualType StrTy = Context.getConstantArrayType(
3919 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3920 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3921 Expr *Lit =
3922 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3924 /*Pascal*/ false, StrTy, TokLoc);
3925 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3926 }
3927
3928 case LOLR_Template: {
3929 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3930 // template), L is treated as a call fo the form
3931 // operator "" X <'c1', 'c2', ... 'ck'>()
3932 // where n is the source character sequence c1 c2 ... ck.
3933 TemplateArgumentListInfo ExplicitArgs;
3934 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3935 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3936 llvm::APSInt Value(CharBits, CharIsUnsigned);
3937 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3938 Value = TokSpelling[I];
3939 TemplateArgument Arg(Context, Value, Context.CharTy);
3941 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3942 }
3943 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
3944 }
3946 llvm_unreachable("unexpected literal operator lookup result");
3947 }
3948 }
3949
3950 Expr *Res;
3951
3952 if (Literal.isFixedPointLiteral()) {
3953 QualType Ty;
3954
3955 if (Literal.isAccum) {
3956 if (Literal.isHalf) {
3957 Ty = Context.ShortAccumTy;
3958 } else if (Literal.isLong) {
3959 Ty = Context.LongAccumTy;
3960 } else {
3961 Ty = Context.AccumTy;
3962 }
3963 } else if (Literal.isFract) {
3964 if (Literal.isHalf) {
3965 Ty = Context.ShortFractTy;
3966 } else if (Literal.isLong) {
3967 Ty = Context.LongFractTy;
3968 } else {
3969 Ty = Context.FractTy;
3970 }
3971 }
3972
3973 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3974
3975 bool isSigned = !Literal.isUnsigned;
3976 unsigned scale = Context.getFixedPointScale(Ty);
3977 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3978
3979 llvm::APInt Val(bit_width, 0, isSigned);
3980 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3981 bool ValIsZero = Val.isZero() && !Overflowed;
3982
3983 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3984 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3985 // Clause 6.4.4 - The value of a constant shall be in the range of
3986 // representable values for its type, with exception for constants of a
3987 // fract type with a value of exactly 1; such a constant shall denote
3988 // the maximal value for the type.
3989 --Val;
3990 else if (Val.ugt(MaxVal) || Overflowed)
3991 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3992
3994 Tok.getLocation(), scale);
3995 } else if (Literal.isFloatingLiteral()) {
3996 QualType Ty;
3997 if (Literal.isHalf){
3998 if (getLangOpts().HLSL ||
3999 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
4000 Ty = Context.HalfTy;
4001 else {
4002 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
4003 return ExprError();
4004 }
4005 } else if (Literal.isFloat)
4006 Ty = Context.FloatTy;
4007 else if (Literal.isLong)
4008 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
4009 else if (Literal.isFloat16)
4010 Ty = Context.Float16Ty;
4011 else if (Literal.isFloat128)
4012 Ty = Context.Float128Ty;
4013 else if (getLangOpts().HLSL)
4014 Ty = Context.FloatTy;
4015 else
4016 Ty = Context.DoubleTy;
4017
4018 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
4019
4020 if (Ty == Context.DoubleTy) {
4021 if (getLangOpts().SinglePrecisionConstants) {
4022 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4023 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4024 }
4025 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4026 "cl_khr_fp64", getLangOpts())) {
4027 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4028 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4030 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4031 }
4032 }
4033 } else if (!Literal.isIntegerLiteral()) {
4034 return ExprError();
4035 } else {
4036 QualType Ty;
4037
4038 // 'z/uz' literals are a C++23 feature.
4039 if (Literal.isSizeT)
4040 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
4042 ? diag::warn_cxx20_compat_size_t_suffix
4043 : diag::ext_cxx23_size_t_suffix
4044 : diag::err_cxx23_size_t_suffix);
4045
4046 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4047 // but we do not currently support the suffix in C++ mode because it's not
4048 // entirely clear whether WG21 will prefer this suffix to return a library
4049 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4050 // literals are a C++ extension.
4051 if (Literal.isBitInt)
4052 PP.Diag(Tok.getLocation(),
4053 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4054 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4055 : diag::ext_c23_bitint_suffix);
4056
4057 // Get the value in the widest-possible width. What is "widest" depends on
4058 // whether the literal is a bit-precise integer or not. For a bit-precise
4059 // integer type, try to scan the source to determine how many bits are
4060 // needed to represent the value. This may seem a bit expensive, but trying
4061 // to get the integer value from an overly-wide APInt is *extremely*
4062 // expensive, so the naive approach of assuming
4063 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4064 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4065 if (Literal.isBitInt)
4066 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4067 Literal.getLiteralDigits(), Literal.getRadix());
4068 if (Literal.MicrosoftInteger) {
4069 if (Literal.MicrosoftInteger == 128 &&
4070 !Context.getTargetInfo().hasInt128Type())
4071 PP.Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4072 << Literal.isUnsigned;
4073 BitsNeeded = Literal.MicrosoftInteger;
4074 }
4075
4076 llvm::APInt ResultVal(BitsNeeded, 0);
4077
4078 if (Literal.GetIntegerValue(ResultVal)) {
4079 // If this value didn't fit into uintmax_t, error and force to ull.
4080 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4081 << /* Unsigned */ 1;
4082 Ty = Context.UnsignedLongLongTy;
4083 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4084 "long long is not intmax_t?");
4085 } else {
4086 // If this value fits into a ULL, try to figure out what else it fits into
4087 // according to the rules of C99 6.4.4.1p5.
4088
4089 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4090 // be an unsigned int.
4091 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4092
4093 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4094 // suffix for portability of code with C++, but both `l` and `ll` are
4095 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4096 // same.
4097 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4098 Literal.isLong = true;
4099 Literal.isLongLong = false;
4100 }
4101
4102 // Check from smallest to largest, picking the smallest type we can.
4103 unsigned Width = 0;
4104
4105 // Microsoft specific integer suffixes are explicitly sized.
4106 if (Literal.MicrosoftInteger) {
4107 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4108 Width = 8;
4109 Ty = Context.CharTy;
4110 } else {
4111 Width = Literal.MicrosoftInteger;
4112 Ty = Context.getIntTypeForBitwidth(Width,
4113 /*Signed=*/!Literal.isUnsigned);
4114 }
4115 }
4116
4117 // Bit-precise integer literals are automagically-sized based on the
4118 // width required by the literal.
4119 if (Literal.isBitInt) {
4120 // The signed version has one more bit for the sign value. There are no
4121 // zero-width bit-precise integers, even if the literal value is 0.
4122 Width = std::max(ResultVal.getActiveBits(), 1u) +
4123 (Literal.isUnsigned ? 0u : 1u);
4124
4125 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4126 // and reset the type to the largest supported width.
4127 unsigned int MaxBitIntWidth =
4128 Context.getTargetInfo().getMaxBitIntWidth();
4129 if (Width > MaxBitIntWidth) {
4130 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4131 << Literal.isUnsigned;
4132 Width = MaxBitIntWidth;
4133 }
4134
4135 // Reset the result value to the smaller APInt and select the correct
4136 // type to be used. Note, we zext even for signed values because the
4137 // literal itself is always an unsigned value (a preceeding - is a
4138 // unary operator, not part of the literal).
4139 ResultVal = ResultVal.zextOrTrunc(Width);
4140 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4141 }
4142
4143 // Check C++23 size_t literals.
4144 if (Literal.isSizeT) {
4145 assert(!Literal.MicrosoftInteger &&
4146 "size_t literals can't be Microsoft literals");
4147 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4148 Context.getTargetInfo().getSizeType());
4149
4150 // Does it fit in size_t?
4151 if (ResultVal.isIntN(SizeTSize)) {
4152 // Does it fit in ssize_t?
4153 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4154 Ty = Context.getSignedSizeType();
4155 else if (AllowUnsigned)
4156 Ty = Context.getSizeType();
4157 Width = SizeTSize;
4158 }
4159 }
4160
4161 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4162 !Literal.isSizeT) {
4163 // Are int/unsigned possibilities?
4164 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4165
4166 // Does it fit in a unsigned int?
4167 if (ResultVal.isIntN(IntSize)) {
4168 // Does it fit in a signed int?
4169 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4170 Ty = Context.IntTy;
4171 else if (AllowUnsigned)
4172 Ty = Context.UnsignedIntTy;
4173 Width = IntSize;
4174 }
4175 }
4176
4177 // Are long/unsigned long possibilities?
4178 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4179 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4180
4181 // Does it fit in a unsigned long?
4182 if (ResultVal.isIntN(LongSize)) {
4183 // Does it fit in a signed long?
4184 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4185 Ty = Context.LongTy;
4186 else if (AllowUnsigned)
4187 Ty = Context.UnsignedLongTy;
4188 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4189 // is compatible.
4190 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4191 const unsigned LongLongSize =
4192 Context.getTargetInfo().getLongLongWidth();
4193 Diag(Tok.getLocation(),
4195 ? Literal.isLong
4196 ? diag::warn_old_implicitly_unsigned_long_cxx
4197 : /*C++98 UB*/ diag::
4198 ext_old_implicitly_unsigned_long_cxx
4199 : diag::warn_old_implicitly_unsigned_long)
4200 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4201 : /*will be ill-formed*/ 1);
4202 Ty = Context.UnsignedLongTy;
4203 }
4204 Width = LongSize;
4205 }
4206 }
4207
4208 // Check long long if needed.
4209 if (Ty.isNull() && !Literal.isSizeT) {
4210 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4211
4212 // Does it fit in a unsigned long long?
4213 if (ResultVal.isIntN(LongLongSize)) {
4214 // Does it fit in a signed long long?
4215 // To be compatible with MSVC, hex integer literals ending with the
4216 // LL or i64 suffix are always signed in Microsoft mode.
4217 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4218 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4219 Ty = Context.LongLongTy;
4220 else if (AllowUnsigned)
4221 Ty = Context.UnsignedLongLongTy;
4222 Width = LongLongSize;
4223
4224 // 'long long' is a C99 or C++11 feature, whether the literal
4225 // explicitly specified 'long long' or we needed the extra width.
4226 if (getLangOpts().CPlusPlus)
4227 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4228 ? diag::warn_cxx98_compat_longlong
4229 : diag::ext_cxx11_longlong);
4230 else if (!getLangOpts().C99)
4231 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4232 }
4233 }
4234
4235 // If we still couldn't decide a type, we either have 'size_t' literal
4236 // that is out of range, or a decimal literal that does not fit in a
4237 // signed long long and has no U suffix.
4238 if (Ty.isNull()) {
4239 if (Literal.isSizeT)
4240 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4241 << Literal.isUnsigned;
4242 else
4243 Diag(Tok.getLocation(),
4244 diag::ext_integer_literal_too_large_for_signed);
4245 Ty = Context.UnsignedLongLongTy;
4246 Width = Context.getTargetInfo().getLongLongWidth();
4247 }
4248
4249 if (ResultVal.getBitWidth() != Width)
4250 ResultVal = ResultVal.trunc(Width);
4251 }
4252 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4253 }
4254
4255 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4256 if (Literal.isImaginary) {
4257 Res = new (Context) ImaginaryLiteral(Res,
4258 Context.getComplexType(Res->getType()));
4259
4260 // In C++, this is a GNU extension. In C, it's a C2y extension.
4261 unsigned DiagId;
4262 if (getLangOpts().CPlusPlus)
4263 DiagId = diag::ext_gnu_imaginary_constant;
4264 else if (getLangOpts().C2y)
4265 DiagId = diag::warn_c23_compat_imaginary_constant;
4266 else
4267 DiagId = diag::ext_c2y_imaginary_constant;
4268 Diag(Tok.getLocation(), DiagId);
4269 }
4270 return Res;
4271}
4272
4274 assert(E && "ActOnParenExpr() missing expr");
4275 QualType ExprTy = E->getType();
4276 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4277 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4278 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4279 return new (Context) ParenExpr(L, R, E);
4280}
4281
4283 SourceLocation Loc,
4284 SourceRange ArgRange) {
4285 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4286 // scalar or vector data type argument..."
4287 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4288 // type (C99 6.2.5p18) or void.
4289 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4290 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4291 << T << ArgRange;
4292 return true;
4293 }
4294
4295 assert((T->isVoidType() || !T->isIncompleteType()) &&
4296 "Scalar types should always be complete");
4297 return false;
4298}
4299
4301 SourceLocation Loc,
4302 SourceRange ArgRange) {
4303 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4304 if (!T->isVectorType() && !T->isSizelessVectorType())
4305 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4306 << ""
4307 << "__builtin_vectorelements" << T << ArgRange;
4308
4309 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
4310 if (T->isSVESizelessBuiltinType()) {
4311 llvm::StringMap<bool> CallerFeatureMap;
4312 S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
4313 return S.ARM().checkSVETypeSupport(T, Loc, FD, CallerFeatureMap);
4314 }
4315 }
4316
4317 return false;
4318}
4319
4321 SourceLocation Loc,
4322 SourceRange ArgRange) {
4323 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4324 return true;
4325
4326 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4327 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4328 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4329 return true;
4330 }
4331
4332 return false;
4333}
4334
4336 SourceLocation Loc,
4337 SourceRange ArgRange,
4338 UnaryExprOrTypeTrait TraitKind) {
4339 // Invalid types must be hard errors for SFINAE in C++.
4340 if (S.LangOpts.CPlusPlus)
4341 return true;
4342
4343 // C99 6.5.3.4p1:
4344 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4345 TraitKind == UETT_PreferredAlignOf) {
4346
4347 // sizeof(function)/alignof(function) is allowed as an extension.
4348 if (T->isFunctionType()) {
4349 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4350 << getTraitSpelling(TraitKind) << ArgRange;
4351 return false;
4352 }
4353
4354 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4355 // this is an error (OpenCL v1.1 s6.3.k)
4356 if (T->isVoidType()) {
4357 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4358 : diag::ext_sizeof_alignof_void_type;
4359 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4360 return false;
4361 }
4362 }
4363 return true;
4364}
4365
4367 SourceLocation Loc,
4368 SourceRange ArgRange,
4369 UnaryExprOrTypeTrait TraitKind) {
4370 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4371 // runtime doesn't allow it.
4372 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4373 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4374 << T << (TraitKind == UETT_SizeOf)
4375 << ArgRange;
4376 return true;
4377 }
4378
4379 return false;
4380}
4381
4382/// Check whether E is a pointer from a decayed array type (the decayed
4383/// pointer type is equal to T) and emit a warning if it is.
4385 const Expr *E) {
4386 // Don't warn if the operation changed the type.
4387 if (T != E->getType())
4388 return;
4389
4390 // Now look for array decays.
4391 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4392 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4393 return;
4394
4395 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4396 << ICE->getType()
4397 << ICE->getSubExpr()->getType();
4398}
4399
4401 UnaryExprOrTypeTrait ExprKind) {
4402 QualType ExprTy = E->getType();
4403 assert(!ExprTy->isReferenceType());
4404
4405 bool IsUnevaluatedOperand =
4406 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4407 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4408 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4409 if (IsUnevaluatedOperand) {
4411 if (Result.isInvalid())
4412 return true;
4413 E = Result.get();
4414 }
4415
4416 // The operand for sizeof and alignof is in an unevaluated expression context,
4417 // so side effects could result in unintended consequences.
4418 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4419 // used to build SFINAE gadgets.
4420 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4421 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4423 !E->getType()->isVariableArrayType() &&
4424 E->HasSideEffects(Context, false))
4425 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4426
4427 if (ExprKind == UETT_VecStep)
4428 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4429 E->getSourceRange());
4430
4431 if (ExprKind == UETT_VectorElements)
4432 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4433 E->getSourceRange());
4434
4435 // Explicitly list some types as extensions.
4436 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4437 E->getSourceRange(), ExprKind))
4438 return false;
4439
4440 // WebAssembly tables are always illegal operands to unary expressions and
4441 // type traits.
4442 if (Context.getTargetInfo().getTriple().isWasm() &&
4444 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4445 << getTraitSpelling(ExprKind);
4446 return true;
4447 }
4448
4449 // 'alignof' applied to an expression only requires the base element type of
4450 // the expression to be complete. 'sizeof' requires the expression's type to
4451 // be complete (and will attempt to complete it if it's an array of unknown
4452 // bound).
4453 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4455 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4456 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4457 getTraitSpelling(ExprKind), E->getSourceRange()))
4458 return true;
4459 } else {
4461 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4462 getTraitSpelling(ExprKind), E->getSourceRange()))
4463 return true;
4464 }
4465
4466 // Completing the expression's type may have changed it.
4467 ExprTy = E->getType();
4468 assert(!ExprTy->isReferenceType());
4469
4470 if (ExprTy->isFunctionType()) {
4471 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4472 << getTraitSpelling(ExprKind) << E->getSourceRange();
4473 return true;
4474 }
4475
4476 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4477 E->getSourceRange(), ExprKind))
4478 return true;
4479
4480 if (ExprKind == UETT_CountOf) {
4481 // The type has to be an array type. We already checked for incomplete
4482 // types above.
4483 QualType ExprType = E->IgnoreParens()->getType();
4484 if (!ExprType->isArrayType()) {
4485 Diag(E->getExprLoc(), diag::err_countof_arg_not_array_type) << ExprType;
4486 return true;
4487 }
4488 // FIXME: warn on _Countof on an array parameter. Not warning on it
4489 // currently because there are papers in WG14 about array types which do
4490 // not decay that could impact this behavior, so we want to see if anything
4491 // changes here before coming up with a warning group for _Countof-related
4492 // diagnostics.
4493 }
4494
4495 if (ExprKind == UETT_SizeOf) {
4496 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4497 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4498 QualType OType = PVD->getOriginalType();
4499 QualType Type = PVD->getType();
4500 if (Type->isPointerType() && OType->isArrayType()) {
4501 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4502 << Type << OType;
4503 Diag(PVD->getLocation(), diag::note_declared_at);
4504 }
4505 }
4506 }
4507
4508 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4509 // decays into a pointer and returns an unintended result. This is most
4510 // likely a typo for "sizeof(array) op x".
4511 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4512 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4513 BO->getLHS());
4514 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4515 BO->getRHS());
4516 }
4517 }
4518
4519 return false;
4520}
4521
4522static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4523 // Cannot know anything else if the expression is dependent.
4524 if (E->isTypeDependent())
4525 return false;
4526
4527 if (E->getObjectKind() == OK_BitField) {
4528 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4529 << 1 << E->getSourceRange();
4530 return true;
4531 }
4532
4533 ValueDecl *D = nullptr;
4534 Expr *Inner = E->IgnoreParens();
4535 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4536 D = DRE->getDecl();
4537 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4538 D = ME->getMemberDecl();
4539 }
4540
4541 // If it's a field, require the containing struct to have a
4542 // complete definition so that we can compute the layout.
4543 //
4544 // This can happen in C++11 onwards, either by naming the member
4545 // in a way that is not transformed into a member access expression
4546 // (in an unevaluated operand, for instance), or by naming the member
4547 // in a trailing-return-type.
4548 //
4549 // For the record, since __alignof__ on expressions is a GCC
4550 // extension, GCC seems to permit this but always gives the
4551 // nonsensical answer 0.
4552 //
4553 // We don't really need the layout here --- we could instead just
4554 // directly check for all the appropriate alignment-lowing
4555 // attributes --- but that would require duplicating a lot of
4556 // logic that just isn't worth duplicating for such a marginal
4557 // use-case.
4558 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4559 // Fast path this check, since we at least know the record has a
4560 // definition if we can find a member of it.
4561 if (!FD->getParent()->isCompleteDefinition()) {
4562 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4563 << E->getSourceRange();
4564 return true;
4565 }
4566
4567 // Otherwise, if it's a field, and the field doesn't have
4568 // reference type, then it must have a complete type (or be a
4569 // flexible array member, which we explicitly want to
4570 // white-list anyway), which makes the following checks trivial.
4571 if (!FD->getType()->isReferenceType())
4572 return false;
4573 }
4574
4575 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4576}
4577
4579 E = E->IgnoreParens();
4580
4581 // Cannot know anything else if the expression is dependent.
4582 if (E->isTypeDependent())
4583 return false;
4584
4585 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4586}
4587
4589 CapturingScopeInfo *CSI) {
4590 assert(T->isVariablyModifiedType());
4591 assert(CSI != nullptr);
4592
4593 // We're going to walk down into the type and look for VLA expressions.
4594 do {
4595 const Type *Ty = T.getTypePtr();
4596 switch (Ty->getTypeClass()) {
4597#define TYPE(Class, Base)
4598#define ABSTRACT_TYPE(Class, Base)
4599#define NON_CANONICAL_TYPE(Class, Base)
4600#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4601#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4602#include "clang/AST/TypeNodes.inc"
4603 T = QualType();
4604 break;
4605 // These types are never variably-modified.
4606 case Type::Builtin:
4607 case Type::Complex:
4608 case Type::Vector:
4609 case Type::ExtVector:
4610 case Type::ConstantMatrix:
4611 case Type::Record:
4612 case Type::Enum:
4613 case Type::TemplateSpecialization:
4614 case Type::ObjCObject:
4615 case Type::ObjCInterface:
4616 case Type::ObjCObjectPointer:
4617 case Type::ObjCTypeParam:
4618 case Type::Pipe:
4619 case Type::BitInt:
4620 case Type::HLSLInlineSpirv:
4621 llvm_unreachable("type class is never variably-modified!");
4622 case Type::Adjusted:
4623 T = cast<AdjustedType>(Ty)->getOriginalType();
4624 break;
4625 case Type::Decayed:
4626 T = cast<DecayedType>(Ty)->getPointeeType();
4627 break;
4628 case Type::ArrayParameter:
4629 T = cast<ArrayParameterType>(Ty)->getElementType();
4630 break;
4631 case Type::Pointer:
4632 T = cast<PointerType>(Ty)->getPointeeType();
4633 break;
4634 case Type::BlockPointer:
4635 T = cast<BlockPointerType>(Ty)->getPointeeType();
4636 break;
4637 case Type::LValueReference:
4638 case Type::RValueReference:
4639 T = cast<ReferenceType>(Ty)->getPointeeType();
4640 break;
4641 case Type::MemberPointer:
4642 T = cast<MemberPointerType>(Ty)->getPointeeType();
4643 break;
4644 case Type::ConstantArray:
4645 case Type::IncompleteArray:
4646 // Losing element qualification here is fine.
4647 T = cast<ArrayType>(Ty)->getElementType();
4648 break;
4649 case Type::VariableArray: {
4650 // Losing element qualification here is fine.
4652
4653 // Unknown size indication requires no size computation.
4654 // Otherwise, evaluate and record it.
4655 auto Size = VAT->getSizeExpr();
4656 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4658 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4659
4660 T = VAT->getElementType();
4661 break;
4662 }
4663 case Type::FunctionProto:
4664 case Type::FunctionNoProto:
4665 T = cast<FunctionType>(Ty)->getReturnType();
4666 break;
4667 case Type::Paren:
4668 case Type::TypeOf:
4669 case Type::UnaryTransform:
4670 case Type::Attributed:
4671 case Type::BTFTagAttributed:
4672 case Type::OverflowBehavior:
4673 case Type::HLSLAttributedResource:
4674 case Type::SubstTemplateTypeParm:
4675 case Type::MacroQualified:
4676 case Type::CountAttributed:
4677 // Keep walking after single level desugaring.
4678 T = T.getSingleStepDesugaredType(Context);
4679 break;
4680 case Type::Typedef:
4681 T = cast<TypedefType>(Ty)->desugar();
4682 break;
4683 case Type::Decltype:
4684 T = cast<DecltypeType>(Ty)->desugar();
4685 break;
4686 case Type::PackIndexing:
4687 T = cast<PackIndexingType>(Ty)->desugar();
4688 break;
4689 case Type::Using:
4690 T = cast<UsingType>(Ty)->desugar();
4691 break;
4692 case Type::Auto:
4693 case Type::DeducedTemplateSpecialization:
4694 T = cast<DeducedType>(Ty)->getDeducedType();
4695 break;
4696 case Type::TypeOfExpr:
4697 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4698 break;
4699 case Type::Atomic:
4700 T = cast<AtomicType>(Ty)->getValueType();
4701 break;
4702 case Type::PredefinedSugar:
4703 T = cast<PredefinedSugarType>(Ty)->desugar();
4704 break;
4705 }
4706 } while (!T.isNull() && T->isVariablyModifiedType());
4707}
4708
4710 SourceLocation OpLoc,
4711 SourceRange ExprRange,
4712 UnaryExprOrTypeTrait ExprKind,
4713 StringRef KWName) {
4714 if (ExprType->isDependentType())
4715 return false;
4716
4717 // C++ [expr.sizeof]p2:
4718 // When applied to a reference or a reference type, the result
4719 // is the size of the referenced type.
4720 // C++11 [expr.alignof]p3:
4721 // When alignof is applied to a reference type, the result
4722 // shall be the alignment of the referenced type.
4723 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4724 ExprType = Ref->getPointeeType();
4725
4726 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4727 // When alignof or _Alignof is applied to an array type, the result
4728 // is the alignment of the element type.
4729 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4730 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4731 // If the trait is 'alignof' in C before C2y, the ability to apply the
4732 // trait to an incomplete array is an extension.
4733 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4734 ExprType->isIncompleteArrayType())
4735 Diag(OpLoc, getLangOpts().C2y
4736 ? diag::warn_c2y_compat_alignof_incomplete_array
4737 : diag::ext_c2y_alignof_incomplete_array);
4738 ExprType = Context.getBaseElementType(ExprType);
4739 }
4740
4741 if (ExprKind == UETT_VecStep)
4742 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4743
4744 if (ExprKind == UETT_VectorElements)
4745 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4746 ExprRange);
4747
4748 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4749 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4750 ExprRange);
4751
4752 // Explicitly list some types as extensions.
4753 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4754 ExprKind))
4755 return false;
4756
4758 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4759 KWName, ExprRange))
4760 return true;
4761
4762 if (ExprType->isFunctionType()) {
4763 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4764 return true;
4765 }
4766
4767 if (ExprKind == UETT_CountOf) {
4768 // The type has to be an array type. We already checked for incomplete
4769 // types above.
4770 if (!ExprType->isArrayType()) {
4771 Diag(OpLoc, diag::err_countof_arg_not_array_type) << ExprType;
4772 return true;
4773 }
4774 }
4775
4776 // WebAssembly tables are always illegal operands to unary expressions and
4777 // type traits.
4778 if (Context.getTargetInfo().getTriple().isWasm() &&
4779 ExprType->isWebAssemblyTableType()) {
4780 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4781 << getTraitSpelling(ExprKind);
4782 return true;
4783 }
4784
4785 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4786 ExprKind))
4787 return true;
4788
4789 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4790 if (auto *TT = ExprType->getAs<TypedefType>()) {
4791 for (auto I = FunctionScopes.rbegin(),
4792 E = std::prev(FunctionScopes.rend());
4793 I != E; ++I) {
4794 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4795 if (CSI == nullptr)
4796 break;
4797 DeclContext *DC = nullptr;
4798 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4799 DC = LSI->CallOperator;
4800 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4801 DC = CRSI->TheCapturedDecl;
4802 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4803 DC = BSI->TheDecl;
4804 if (DC) {
4805 if (DC->containsDecl(TT->getDecl()))
4806 break;
4807 captureVariablyModifiedType(Context, ExprType, CSI);
4808 }
4809 }
4810 }
4811 }
4812
4813 return false;
4814}
4815
4817 SourceLocation OpLoc,
4818 UnaryExprOrTypeTrait ExprKind,
4819 SourceRange R) {
4820 if (!TInfo)
4821 return ExprError();
4822
4823 QualType T = TInfo->getType();
4824
4825 if (!T->isDependentType() &&
4826 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4827 getTraitSpelling(ExprKind)))
4828 return ExprError();
4829
4830 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4831 // properly deal with VLAs in nested calls of sizeof and typeof.
4832 if (currentEvaluationContext().isUnevaluated() &&
4833 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4834 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4835 TInfo->getType()->isVariablyModifiedType())
4836 TInfo = TransformToPotentiallyEvaluated(TInfo);
4837
4838 // It's possible that the transformation above failed.
4839 if (!TInfo)
4840 return ExprError();
4841
4842 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4843 return new (Context) UnaryExprOrTypeTraitExpr(
4844 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4845}
4846
4849 UnaryExprOrTypeTrait ExprKind) {
4851 if (PE.isInvalid())
4852 return ExprError();
4853
4854 E = PE.get();
4855
4856 // Verify that the operand is valid.
4857 bool isInvalid = false;
4858 if (E->isTypeDependent()) {
4859 // Delay type-checking for type-dependent expressions.
4860 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4861 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4862 } else if (ExprKind == UETT_VecStep) {
4864 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4865 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4866 isInvalid = true;
4867 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4868 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4869 isInvalid = true;
4870 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4871 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4873 }
4874
4875 if (isInvalid)
4876 return ExprError();
4877
4878 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4879 E->getType()->isVariableArrayType()) {
4881 if (PE.isInvalid()) return ExprError();
4882 E = PE.get();
4883 }
4884
4885 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4886 return new (Context) UnaryExprOrTypeTraitExpr(
4887 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4888}
4889
4892 UnaryExprOrTypeTrait ExprKind, bool IsType,
4893 void *TyOrEx, SourceRange ArgRange) {
4894 // If error parsing type, ignore.
4895 if (!TyOrEx) return ExprError();
4896
4897 if (IsType) {
4898 TypeSourceInfo *TInfo;
4899 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4900 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4901 }
4902
4903 Expr *ArgEx = (Expr *)TyOrEx;
4904 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4905 return Result;
4906}
4907
4909 SourceLocation OpLoc, SourceRange R) {
4910 if (!TInfo)
4911 return true;
4912 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4913 UETT_AlignOf, KWName);
4914}
4915
4917 SourceLocation OpLoc, SourceRange R) {
4918 TypeSourceInfo *TInfo;
4920 &TInfo);
4921 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4922}
4923
4925 bool IsReal) {
4926 if (V.get()->isTypeDependent())
4927 return S.Context.DependentTy;
4928
4929 // _Real and _Imag are only l-values for normal l-values.
4930 if (V.get()->getObjectKind() != OK_Ordinary) {
4931 V = S.DefaultLvalueConversion(V.get());
4932 if (V.isInvalid())
4933 return QualType();
4934 }
4935
4936 // These operators return the element type of a complex type.
4937 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4938 return CT->getElementType();
4939
4940 // Otherwise they pass through real integer and floating point types here.
4941 if (V.get()->getType()->isArithmeticType())
4942 return V.get()->getType();
4943
4944 // Test for placeholders.
4945 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4946 if (PR.isInvalid()) return QualType();
4947 if (PR.get() != V.get()) {
4948 V = PR;
4949 return CheckRealImagOperand(S, V, Loc, IsReal);
4950 }
4951
4952 // Reject anything else.
4953 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4954 << (IsReal ? "__real" : "__imag");
4955 return QualType();
4956}
4957
4958
4959
4962 tok::TokenKind Kind, Expr *Input) {
4964 switch (Kind) {
4965 default: llvm_unreachable("Unknown unary op!");
4966 case tok::plusplus: Opc = UO_PostInc; break;
4967 case tok::minusminus: Opc = UO_PostDec; break;
4968 }
4969
4970 // Since this might is a postfix expression, get rid of ParenListExprs.
4972 if (Result.isInvalid()) return ExprError();
4973 Input = Result.get();
4974
4975 return BuildUnaryOp(S, OpLoc, Opc, Input);
4976}
4977
4978/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4979///
4980/// \return true on error
4982 SourceLocation opLoc,
4983 Expr *op) {
4984 assert(op->getType()->isObjCObjectPointerType());
4986 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4987 return false;
4988
4989 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4991 << op->getSourceRange();
4992 return true;
4993}
4994
4996 auto *BaseNoParens = Base->IgnoreParens();
4997 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4998 return MSProp->getPropertyDecl()->getType()->isArrayType();
4999 return isa<MSPropertySubscriptExpr>(BaseNoParens);
5000}
5001
5002// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5003// Typically this is DependentTy, but can sometimes be more precise.
5004//
5005// There are cases when we could determine a non-dependent type:
5006// - LHS and RHS may have non-dependent types despite being type-dependent
5007// (e.g. unbounded array static members of the current instantiation)
5008// - one may be a dependent-sized array with known element type
5009// - one may be a dependent-typed valid index (enum in current instantiation)
5010//
5011// We *always* return a dependent type, in such cases it is DependentTy.
5012// This avoids creating type-dependent expressions with non-dependent types.
5013// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5015 const ASTContext &Ctx) {
5016 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5017 QualType LTy = LHS->getType(), RTy = RHS->getType();
5019 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5020 if (const PointerType *PT = LTy->getAs<PointerType>())
5021 Result = PT->getPointeeType();
5022 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5023 Result = AT->getElementType();
5024 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5025 if (const PointerType *PT = RTy->getAs<PointerType>())
5026 Result = PT->getPointeeType();
5027 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5028 Result = AT->getElementType();
5029 }
5030 // Ensure we return a dependent type.
5031 return Result->isDependentType() ? Result : Ctx.DependentTy;
5032}
5033
5035 SourceLocation lbLoc,
5036 MultiExprArg ArgExprs,
5037 SourceLocation rbLoc) {
5038
5039 if (base && !base->getType().isNull() &&
5040 base->hasPlaceholderType(BuiltinType::ArraySection)) {
5041 auto *AS = cast<ArraySectionExpr>(base);
5042 if (AS->isOMPArraySection())
5044 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
5045 /*Length*/ nullptr,
5046 /*Stride=*/nullptr, rbLoc);
5047
5048 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
5049 SourceLocation(), /*Length*/ nullptr,
5050 rbLoc);
5051 }
5052
5053 // Since this might be a postfix expression, get rid of ParenListExprs.
5054 if (isa<ParenListExpr>(base)) {
5056 if (result.isInvalid())
5057 return ExprError();
5058 base = result.get();
5059 }
5060
5061 // Check if base and idx form a MatrixSubscriptExpr.
5062 //
5063 // Helper to check for comma expressions, which are not allowed as indices for
5064 // matrix subscript expressions.
5065 //
5066 // In C++23, we get multiple arguments instead of a comma expression.
5067 auto CheckAndReportCommaError = [&](Expr *E) {
5068 if (ArgExprs.size() > 1 ||
5069 (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp())) {
5070 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
5071 << SourceRange(base->getBeginLoc(), rbLoc);
5072 return true;
5073 }
5074 return false;
5075 };
5076 // The matrix subscript operator ([][])is considered a single operator.
5077 // Separating the index expressions by parenthesis is not allowed.
5078 if (base && !base->getType().isNull() &&
5079 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
5080 !isa<MatrixSubscriptExpr>(base)) {
5081 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
5082 << SourceRange(base->getBeginLoc(), rbLoc);
5083 return ExprError();
5084 }
5085 // If the base is a MatrixSubscriptExpr, try to create a new
5086 // MatrixSubscriptExpr.
5087 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
5088 if (matSubscriptE && matSubscriptE->isIncomplete()) {
5089 if (CheckAndReportCommaError(ArgExprs.front()))
5090 return ExprError();
5091
5092 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
5093 matSubscriptE->getRowIdx(),
5094 ArgExprs.front(), rbLoc);
5095 }
5096 if (base->getType()->isWebAssemblyTableType()) {
5097 Diag(base->getExprLoc(), diag::err_wasm_table_art)
5098 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5099 return ExprError();
5100 }
5101
5102 CheckInvalidBuiltinCountedByRef(base,
5104
5105 // Handle any non-overload placeholder types in the base and index
5106 // expressions. We can't handle overloads here because the other
5107 // operand might be an overloadable type, in which case the overload
5108 // resolution for the operator overload should get the first crack
5109 // at the overload.
5110 bool IsMSPropertySubscript = false;
5111 if (base->getType()->isNonOverloadPlaceholderType()) {
5112 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5113 if (!IsMSPropertySubscript) {
5114 ExprResult result = CheckPlaceholderExpr(base);
5115 if (result.isInvalid())
5116 return ExprError();
5117 base = result.get();
5118 }
5119 }
5120
5121 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5122 if (base->getType()->isMatrixType()) {
5123 if (CheckAndReportCommaError(ArgExprs.front()))
5124 return ExprError();
5125
5126 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5127 rbLoc);
5128 }
5129
5130 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5131 Expr *idx = ArgExprs[0];
5132 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5134 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5135 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5136 << SourceRange(base->getBeginLoc(), rbLoc);
5137 }
5138 }
5139
5140 if (ArgExprs.size() == 1 &&
5141 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5142 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5143 if (result.isInvalid())
5144 return ExprError();
5145 ArgExprs[0] = result.get();
5146 } else {
5147 if (CheckArgsForPlaceholders(ArgExprs))
5148 return ExprError();
5149 }
5150
5151 // Build an unanalyzed expression if either operand is type-dependent.
5152 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5153 (base->isTypeDependent() ||
5155 !isa<PackExpansionExpr>(ArgExprs[0])) {
5156 return new (Context) ArraySubscriptExpr(
5157 base, ArgExprs.front(),
5158 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5159 VK_LValue, OK_Ordinary, rbLoc);
5160 }
5161
5162 // MSDN, property (C++)
5163 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5164 // This attribute can also be used in the declaration of an empty array in a
5165 // class or structure definition. For example:
5166 // __declspec(property(get=GetX, put=PutX)) int x[];
5167 // The above statement indicates that x[] can be used with one or more array
5168 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5169 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5170 if (IsMSPropertySubscript) {
5171 if (ArgExprs.size() > 1) {
5172 Diag(base->getExprLoc(),
5173 diag::err_ms_property_subscript_expects_single_arg);
5174 return ExprError();
5175 }
5176
5177 // Build MS property subscript expression if base is MS property reference
5178 // or MS property subscript.
5179 return new (Context)
5180 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5181 VK_LValue, OK_Ordinary, rbLoc);
5182 }
5183
5184 // Use C++ overloaded-operator rules if either operand has record
5185 // type. The spec says to do this if either type is *overloadable*,
5186 // but enum types can't declare subscript operators or conversion
5187 // operators, so there's nothing interesting for overload resolution
5188 // to do if there aren't any record types involved.
5189 //
5190 // ObjC pointers have their own subscripting logic that is not tied
5191 // to overload resolution and so should not take this path.
5192 //
5193 // Issue a better diagnostic if we tried to pass multiple arguments to
5194 // a builtin subscript operator rather than diagnosing this as a generic
5195 // overload resolution failure.
5196 if (ArgExprs.size() != 1 && !base->getType()->isDependentType() &&
5197 !base->getType()->isRecordType() &&
5198 !base->getType()->isObjCObjectPointerType()) {
5199 Diag(base->getExprLoc(), diag::err_ovl_builtin_subscript_expects_single_arg)
5200 << base->getType() << base->getSourceRange();
5201 return ExprError();
5202 }
5203
5205 ((base->getType()->isRecordType() ||
5206 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5207 ArgExprs[0]->getType()->isRecordType())))) {
5208 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5209 }
5210
5211 ExprResult Res =
5212 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5213
5214 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5215 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5216
5217 return Res;
5218}
5219
5222 InitializationKind Kind =
5224 InitializationSequence InitSeq(*this, Entity, Kind, E);
5225 return InitSeq.Perform(*this, Entity, Kind, E);
5226}
5227
5229 Expr *RowIdx,
5230 SourceLocation RBLoc) {
5232 if (BaseR.isInvalid())
5233 return BaseR;
5234 Base = BaseR.get();
5235
5236 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5237 if (RowR.isInvalid())
5238 return RowR;
5239 RowIdx = RowR.get();
5240
5241 // Build an unanalyzed expression if any of the operands is type-dependent.
5242 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5243 return new (Context)
5244 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5245
5246 // Check that IndexExpr is an integer expression. If it is a constant
5247 // expression, check that it is less than Dim (= the number of elements in the
5248 // corresponding dimension).
5249 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5250 bool IsColumnIdx) -> Expr * {
5251 if (!IndexExpr->getType()->isIntegerType() &&
5252 !IndexExpr->isTypeDependent()) {
5253 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5254 << IsColumnIdx;
5255 return nullptr;
5256 }
5257
5258 if (std::optional<llvm::APSInt> Idx =
5259 IndexExpr->getIntegerConstantExpr(Context)) {
5260 if ((*Idx < 0 || *Idx >= Dim)) {
5261 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5262 << IsColumnIdx << Dim;
5263 return nullptr;
5264 }
5265 }
5266
5267 ExprResult ConvExpr = IndexExpr;
5268 assert(!ConvExpr.isInvalid() &&
5269 "should be able to convert any integer type to size type");
5270 return ConvExpr.get();
5271 };
5272
5273 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5274 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5275 if (!RowIdx)
5276 return ExprError();
5277
5278 QualType RowVecQT =
5279 Context.getExtVectorType(MTy->getElementType(), MTy->getNumColumns());
5280
5281 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5282}
5283
5285 Expr *ColumnIdx,
5286 SourceLocation RBLoc) {
5288 if (BaseR.isInvalid())
5289 return BaseR;
5290 Base = BaseR.get();
5291
5292 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5293 if (RowR.isInvalid())
5294 return RowR;
5295 RowIdx = RowR.get();
5296
5297 if (!ColumnIdx)
5298 return new (Context) MatrixSubscriptExpr(
5299 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5300
5301 // Build an unanalyzed expression if any of the operands is type-dependent.
5302 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5303 ColumnIdx->isTypeDependent())
5304 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5305 Context.DependentTy, RBLoc);
5306
5307 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5308 if (ColumnR.isInvalid())
5309 return ColumnR;
5310 ColumnIdx = ColumnR.get();
5311
5312 // Check that IndexExpr is an integer expression. If it is a constant
5313 // expression, check that it is less than Dim (= the number of elements in the
5314 // corresponding dimension).
5315 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5316 bool IsColumnIdx) -> Expr * {
5317 if (!IndexExpr->getType()->isIntegerType() &&
5318 !IndexExpr->isTypeDependent()) {
5319 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5320 << IsColumnIdx;
5321 return nullptr;
5322 }
5323
5324 if (std::optional<llvm::APSInt> Idx =
5325 IndexExpr->getIntegerConstantExpr(Context)) {
5326 if ((*Idx < 0 || *Idx >= Dim)) {
5327 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5328 << IsColumnIdx << Dim;
5329 return nullptr;
5330 }
5331 }
5332
5333 ExprResult ConvExpr = IndexExpr;
5334 assert(!ConvExpr.isInvalid() &&
5335 "should be able to convert any integer type to size type");
5336 return ConvExpr.get();
5337 };
5338
5339 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5340 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5341 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5342 if (!RowIdx || !ColumnIdx)
5343 return ExprError();
5344
5345 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5346 MTy->getElementType(), RBLoc);
5347}
5348
5349void Sema::CheckAddressOfNoDeref(const Expr *E) {
5350 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5351 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5352
5353 // For expressions like `&(*s).b`, the base is recorded and what should be
5354 // checked.
5355 const MemberExpr *Member = nullptr;
5356 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5357 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5358
5359 LastRecord.PossibleDerefs.erase(StrippedExpr);
5360}
5361
5362void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5364 return;
5365
5366 QualType ResultTy = E->getType();
5367 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5368
5369 // Bail if the element is an array since it is not memory access.
5370 if (isa<ArrayType>(ResultTy))
5371 return;
5372
5373 if (ResultTy->hasAttr(attr::NoDeref)) {
5374 LastRecord.PossibleDerefs.insert(E);
5375 return;
5376 }
5377
5378 // Check if the base type is a pointer to a member access of a struct
5379 // marked with noderef.
5380 const Expr *Base = E->getBase();
5381 QualType BaseTy = Base->getType();
5382 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5383 // Not a pointer access
5384 return;
5385
5386 const MemberExpr *Member = nullptr;
5387 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5388 Member->isArrow())
5389 Base = Member->getBase();
5390
5391 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5392 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5393 LastRecord.PossibleDerefs.insert(E);
5394 }
5395}
5396
5399 Expr *Idx, SourceLocation RLoc) {
5400 Expr *LHSExp = Base;
5401 Expr *RHSExp = Idx;
5402
5405
5406 // Per C++ core issue 1213, the result is an xvalue if either operand is
5407 // a non-lvalue array, and an lvalue otherwise.
5408 if (getLangOpts().CPlusPlus11) {
5409 for (auto *Op : {LHSExp, RHSExp}) {
5410 Op = Op->IgnoreImplicit();
5411 if (Op->getType()->isArrayType() && !Op->isLValue())
5412 VK = VK_XValue;
5413 }
5414 }
5415
5416 // Perform default conversions.
5417 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5419 if (Result.isInvalid())
5420 return ExprError();
5421 LHSExp = Result.get();
5422 }
5424 if (Result.isInvalid())
5425 return ExprError();
5426 RHSExp = Result.get();
5427
5428 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5429
5430 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5431 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5432 // in the subscript position. As a result, we need to derive the array base
5433 // and index from the expression types.
5434 Expr *BaseExpr, *IndexExpr;
5435 QualType ResultType;
5436 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5437 BaseExpr = LHSExp;
5438 IndexExpr = RHSExp;
5439 ResultType =
5441 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5442 BaseExpr = LHSExp;
5443 IndexExpr = RHSExp;
5444 ResultType = PTy->getPointeeType();
5445 } else if (const ObjCObjectPointerType *PTy =
5446 LHSTy->getAs<ObjCObjectPointerType>()) {
5447 BaseExpr = LHSExp;
5448 IndexExpr = RHSExp;
5449
5450 // Use custom logic if this should be the pseudo-object subscript
5451 // expression.
5452 if (!LangOpts.isSubscriptPointerArithmetic())
5453 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5454 nullptr, nullptr);
5455
5456 ResultType = PTy->getPointeeType();
5457 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5458 // Handle the uncommon case of "123[Ptr]".
5459 BaseExpr = RHSExp;
5460 IndexExpr = LHSExp;
5461 ResultType = PTy->getPointeeType();
5462 } else if (const ObjCObjectPointerType *PTy =
5463 RHSTy->getAs<ObjCObjectPointerType>()) {
5464 // Handle the uncommon case of "123[Ptr]".
5465 BaseExpr = RHSExp;
5466 IndexExpr = LHSExp;
5467 ResultType = PTy->getPointeeType();
5468 if (!LangOpts.isSubscriptPointerArithmetic()) {
5469 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5470 << ResultType << BaseExpr->getSourceRange();
5471 return ExprError();
5472 }
5473 } else if (LHSTy->isSubscriptableVectorType()) {
5474 if (LHSTy->isBuiltinType() &&
5475 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5476 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5477 if (BTy->isSVEBool())
5478 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5479 << LHSExp->getSourceRange()
5480 << RHSExp->getSourceRange());
5481 ResultType = BTy->getSveEltType(Context);
5482 } else {
5483 const VectorType *VTy = LHSTy->getAs<VectorType>();
5484 ResultType = VTy->getElementType();
5485 }
5486 BaseExpr = LHSExp; // vectors: V[123]
5487 IndexExpr = RHSExp;
5488 // We apply C++ DR1213 to vector subscripting too.
5489 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5490 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5491 if (Materialized.isInvalid())
5492 return ExprError();
5493 LHSExp = Materialized.get();
5494 }
5495 VK = LHSExp->getValueKind();
5496 if (VK != VK_PRValue)
5497 OK = OK_VectorComponent;
5498
5499 QualType BaseType = BaseExpr->getType();
5500 Qualifiers BaseQuals = BaseType.getQualifiers();
5501 Qualifiers MemberQuals = ResultType.getQualifiers();
5502 Qualifiers Combined = BaseQuals + MemberQuals;
5503 if (Combined != MemberQuals)
5504 ResultType = Context.getQualifiedType(ResultType, Combined);
5505 } else if (LHSTy->isArrayType()) {
5506 // If we see an array that wasn't promoted by
5507 // DefaultFunctionArrayLvalueConversion, it must be an array that
5508 // wasn't promoted because of the C90 rule that doesn't
5509 // allow promoting non-lvalue arrays. Warn, then
5510 // force the promotion here.
5511 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5512 << LHSExp->getSourceRange();
5513 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5514 CK_ArrayToPointerDecay).get();
5515 LHSTy = LHSExp->getType();
5516
5517 BaseExpr = LHSExp;
5518 IndexExpr = RHSExp;
5519 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5520 } else if (RHSTy->isArrayType()) {
5521 // Same as previous, except for 123[f().a] case
5522 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5523 << RHSExp->getSourceRange();
5524 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5525 CK_ArrayToPointerDecay).get();
5526 RHSTy = RHSExp->getType();
5527
5528 BaseExpr = RHSExp;
5529 IndexExpr = LHSExp;
5530 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5531 } else {
5532 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5533 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5534 }
5535 // C99 6.5.2.1p1
5536 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5537 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5538 << IndexExpr->getSourceRange());
5539
5540 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5541 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5542 !IndexExpr->isTypeDependent()) {
5543 std::optional<llvm::APSInt> IntegerContantExpr =
5545 if (!IntegerContantExpr.has_value() ||
5546 IntegerContantExpr.value().isNegative())
5547 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5548 }
5549
5550 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5551 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5552 // type. Note that Functions are not objects, and that (in C99 parlance)
5553 // incomplete types are not object types.
5554 if (ResultType->isFunctionType()) {
5555 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5556 << ResultType << BaseExpr->getSourceRange();
5557 return ExprError();
5558 }
5559
5560 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5561 // GNU extension: subscripting on pointer to void
5562 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5563 << BaseExpr->getSourceRange();
5564
5565 // C forbids expressions of unqualified void type from being l-values.
5566 // See IsCForbiddenLValueType.
5567 if (!ResultType.hasQualifiers())
5568 VK = VK_PRValue;
5569 } else if (!ResultType->isDependentType() &&
5570 !ResultType.isWebAssemblyReferenceType() &&
5572 LLoc, ResultType,
5573 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5574 return ExprError();
5575
5576 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5577 !ResultType.isCForbiddenLValueType());
5578
5580 FunctionScopes.size() > 1) {
5581 if (auto *TT =
5582 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5583 for (auto I = FunctionScopes.rbegin(),
5584 E = std::prev(FunctionScopes.rend());
5585 I != E; ++I) {
5586 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5587 if (CSI == nullptr)
5588 break;
5589 DeclContext *DC = nullptr;
5590 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5591 DC = LSI->CallOperator;
5592 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5593 DC = CRSI->TheCapturedDecl;
5594 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5595 DC = BSI->TheDecl;
5596 if (DC) {
5597 if (DC->containsDecl(TT->getDecl()))
5598 break;
5600 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5601 }
5602 }
5603 }
5604 }
5605
5606 return new (Context)
5607 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5608}
5609
5611 ParmVarDecl *Param, Expr *RewrittenInit,
5612 bool SkipImmediateInvocations) {
5613 if (Param->hasUnparsedDefaultArg()) {
5614 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5615 // If we've already cleared out the location for the default argument,
5616 // that means we're parsing it right now.
5617 if (!UnparsedDefaultArgLocs.count(Param)) {
5618 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5619 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5620 Param->setInvalidDecl();
5621 return true;
5622 }
5623
5624 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5625 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5627 diag::note_default_argument_declared_here);
5628 return true;
5629 }
5630
5631 if (Param->hasUninstantiatedDefaultArg()) {
5632 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5633 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5634 return true;
5635 }
5636
5637 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5638 assert(Init && "default argument but no initializer?");
5639
5640 // If the default expression creates temporaries, we need to
5641 // push them to the current stack of expression temporaries so they'll
5642 // be properly destroyed.
5643 // FIXME: We should really be rebuilding the default argument with new
5644 // bound temporaries; see the comment in PR5810.
5645 // We don't need to do that with block decls, though, because
5646 // blocks in default argument expression can never capture anything.
5647 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5648 // Set the "needs cleanups" bit regardless of whether there are
5649 // any explicit objects.
5650 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5651 // Append all the objects to the cleanup list. Right now, this
5652 // should always be a no-op, because blocks in default argument
5653 // expressions should never be able to capture anything.
5654 assert(!InitWithCleanup->getNumObjects() &&
5655 "default argument expression has capturing blocks?");
5656 }
5657 // C++ [expr.const]p15.1:
5658 // An expression or conversion is in an immediate function context if it is
5659 // potentially evaluated and [...] its innermost enclosing non-block scope
5660 // is a function parameter scope of an immediate function.
5662 *this,
5666 Param);
5667 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5668 SkipImmediateInvocations;
5669 runWithSufficientStackSpace(CallLoc, [&] {
5670 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5671 });
5672 return false;
5673}
5674
5679 }
5680
5681 bool HasImmediateCalls = false;
5682
5683 bool VisitCallExpr(CallExpr *E) override {
5684 if (const FunctionDecl *FD = E->getDirectCallee())
5685 HasImmediateCalls |= FD->isImmediateFunction();
5687 }
5688
5690 if (const FunctionDecl *FD = E->getConstructor())
5691 HasImmediateCalls |= FD->isImmediateFunction();
5693 }
5694
5695 // SourceLocExpr are not immediate invocations
5696 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5697 // need to be rebuilt so that they refer to the correct SourceLocation and
5698 // DeclContext.
5700 HasImmediateCalls = true;
5702 }
5703
5704 // A nested lambda might have parameters with immediate invocations
5705 // in their default arguments, or init-captures that are evaluated in the
5706 // enclosing context.
5707 // The compound statement is not visited (as it does not constitute a
5708 // subexpression).
5709 bool VisitLambdaExpr(LambdaExpr *E) override {
5710 auto Init = E->capture_init_begin();
5711 for (auto C = E->capture_begin(), CEnd = E->capture_end(); C != CEnd;
5712 ++C, ++Init) {
5713 if (E->isInitCapture(C) && !TraverseLambdaCapture(E, C, *Init))
5714 return false;
5715 }
5716 return VisitCXXMethodDecl(E->getCallOperator());
5717 }
5718
5720 return TraverseStmt(E->getExpr());
5721 }
5722
5724 return TraverseStmt(E->getExpr());
5725 }
5726};
5727
5729 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5731
5734
5735 bool AlwaysRebuild() { return true; }
5736 bool ReplacingOriginal() { return true; }
5737
5738 // Lambda bodies are not subexpressions of the enclosing default initializer,
5739 // but init-capture expressions are evaluated in the enclosing context. Keep
5740 // the existing closure type and capture declarations so the existing body
5741 // still refers to the right declarations.
5743 SmallVector<Expr *, 4> CaptureInits(E->capture_inits());
5744
5745 bool Changed = false;
5746 for (unsigned I = 0, N = E->capture_size(); I != N; ++I) {
5747 const LambdaCapture *C = E->capture_begin() + I;
5748 if (!E->isInitCapture(C))
5749 continue;
5750
5751 auto *VD = cast<VarDecl>(C->getCapturedVar());
5752 Expr *Init = CaptureInits[I];
5753 ExprResult NewInit =
5754 TransformInitializer(Init, VD->getInitStyle() == VarDecl::CallInit);
5755 if (NewInit.isInvalid())
5756 return ExprError();
5757 Changed |= NewInit.get() != Init;
5758 CaptureInits[I] = NewInit.get();
5759 }
5760
5761 LambdaExpr *Lambda = E;
5762 if (Changed) {
5763 // Reuse the existing closure class: it owns the capture declarations,
5764 // fields, and call operator body. Only the LambdaExpr's capture
5765 // initializer list is replaced.
5766 Lambda = LambdaExpr::Create(
5767 SemaRef.Context, E->getLambdaClass(), E->getIntroducerRange(),
5769 E->hasExplicitParameters(), E->hasExplicitResultType(), CaptureInits,
5771 }
5772
5773 return SemaRef.MaybeBindToTemporary(Lambda);
5774 }
5776
5777 // Make sure we don't rebuild the this pointer as it would
5778 // cause it to incorrectly point it to the outermost class
5779 // in the case of nested struct initialization.
5781
5782 // Rewrite to source location to refer to the context in which they are used.
5784 DeclContext *DC = E->getParentContext();
5785 if (DC == SemaRef.CurContext)
5786 return E;
5787
5788 // FIXME: During instantiation, because the rebuild of defaults arguments
5789 // is not always done in the context of the template instantiator,
5790 // we run the risk of producing a dependent source location
5791 // that would never be rebuilt.
5792 // This usually happens during overload resolution, or in contexts
5793 // where the value of the source location does not matter.
5794 // However, we should find a better way to deal with source location
5795 // of function templates.
5796 if (!SemaRef.CurrentInstantiationScope ||
5797 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5798 DC = SemaRef.CurContext;
5799
5800 return getDerived().RebuildSourceLocExpr(
5801 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5802 }
5803};
5804
5806 FunctionDecl *FD, ParmVarDecl *Param,
5807 Expr *Init) {
5808 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5809
5810 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5811 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5812 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5813 InitializationContext =
5815 if (!InitializationContext.has_value())
5816 InitializationContext.emplace(CallLoc, Param, CurContext);
5817
5818 if (!Init && !Param->hasUnparsedDefaultArg()) {
5819 // Mark that we are replacing a default argument first.
5820 // If we are instantiating a template we won't have to
5821 // retransform immediate calls.
5822 // C++ [expr.const]p15.1:
5823 // An expression or conversion is in an immediate function context if it
5824 // is potentially evaluated and [...] its innermost enclosing non-block
5825 // scope is a function parameter scope of an immediate function.
5827 *this,
5831 Param);
5832
5833 if (Param->hasUninstantiatedDefaultArg()) {
5834 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5835 return ExprError();
5836 }
5837 // CWG2631
5838 // An immediate invocation that is not evaluated where it appears is
5839 // evaluated and checked for whether it is a constant expression at the
5840 // point where the enclosing initializer is used in a function call.
5842 if (!NestedDefaultChecking)
5843 V.TraverseDecl(Param);
5844
5845 // Rewrite the call argument that was created from the corresponding
5846 // parameter's default argument.
5847 if (V.HasImmediateCalls ||
5848 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5849 if (V.HasImmediateCalls)
5850 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5851 CallLoc, Param, CurContext};
5852 // Pass down lifetime extending flag, and collect temporaries in
5853 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5857 ExprResult Res;
5858 runWithSufficientStackSpace(CallLoc, [&] {
5859 Res = Immediate.TransformInitializer(Param->getInit(),
5860 /*NotCopy=*/false);
5861 });
5862 if (Res.isInvalid())
5863 return ExprError();
5864 Res = ConvertParamDefaultArgument(Param, Res.get(),
5865 Res.get()->getBeginLoc());
5866 if (Res.isInvalid())
5867 return ExprError();
5868 Init = Res.get();
5869 }
5870 }
5871
5873 CallLoc, FD, Param, Init,
5874 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5875 return ExprError();
5876
5877 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5878 Init, InitializationContext->Context);
5879}
5880
5882 FieldDecl *Field) {
5883 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5884 return Pattern;
5885 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5886 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5888 ClassPattern->lookup(Field->getDeclName());
5889 auto Rng = llvm::make_filter_range(
5890 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5891 if (Rng.empty())
5892 return nullptr;
5893 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5894 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5895 // && "Duplicated instantiation pattern for field decl");
5896 return cast<FieldDecl>(*Rng.begin());
5897}
5898
5900 assert(Field->hasInClassInitializer());
5901
5902 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5903
5904 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5905
5906 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5907 InitializationContext =
5909 if (!InitializationContext.has_value())
5910 InitializationContext.emplace(Loc, Field, CurContext);
5911
5912 Expr *Init = nullptr;
5913
5914 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5915 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5918
5919 if (!Field->getInClassInitializer()) {
5920 // Maybe we haven't instantiated the in-class initializer. Go check the
5921 // pattern FieldDecl to see if it has one.
5922 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5923 FieldDecl *Pattern =
5925 assert(Pattern && "We must have set the Pattern!");
5926 if (!Pattern->hasInClassInitializer() ||
5927 InstantiateInClassInitializer(Loc, Field, Pattern,
5929 Field->setInvalidDecl();
5930 return ExprError();
5931 }
5932 }
5933 }
5934
5935 // CWG2631
5936 // An immediate invocation that is not evaluated where it appears is
5937 // evaluated and checked for whether it is a constant expression at the
5938 // point where the enclosing initializer is used in a [...] a constructor
5939 // definition, or an aggregate initialization.
5941 if (!NestedDefaultChecking)
5942 V.TraverseDecl(Field);
5943
5944 // CWG1815
5945 // Support lifetime extension of temporary created by aggregate
5946 // initialization using a default member initializer. We should rebuild
5947 // the initializer in a lifetime extension context if the initializer
5948 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5949 // extension code recurses into the default initializer and does lifetime
5950 // extension when warranted.
5951 bool ContainsAnyTemporaries =
5952 isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());
5953 if (Field->getInClassInitializer() &&
5954 !Field->getInClassInitializer()->containsErrors() &&
5955 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5956 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5957 CurContext};
5958 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5959 NestedDefaultChecking;
5960 // Pass down lifetime extending flag, and collect temporaries in
5961 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5965 ExprResult Res;
5967 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5968 /*CXXDirectInit=*/false);
5969 });
5970 if (!Res.isInvalid())
5971 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5972 if (Res.isInvalid()) {
5973 Field->setInvalidDecl();
5974 return ExprError();
5975 }
5976 Init = Res.get();
5977 }
5978
5979 if (Field->getInClassInitializer()) {
5980 Expr *E = Init ? Init : Field->getInClassInitializer();
5981 if (!NestedDefaultChecking)
5983 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5984 });
5987 // C++11 [class.base.init]p7:
5988 // The initialization of each base and member constitutes a
5989 // full-expression.
5990 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5991 if (Res.isInvalid()) {
5992 Field->setInvalidDecl();
5993 return ExprError();
5994 }
5995 Init = Res.get();
5996
5997 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5998 Field, InitializationContext->Context,
5999 Init);
6000 }
6001
6002 // DR1351:
6003 // If the brace-or-equal-initializer of a non-static data member
6004 // invokes a defaulted default constructor of its class or of an
6005 // enclosing class in a potentially evaluated subexpression, the
6006 // program is ill-formed.
6007 //
6008 // This resolution is unworkable: the exception specification of the
6009 // default constructor can be needed in an unevaluated context, in
6010 // particular, in the operand of a noexcept-expression, and we can be
6011 // unable to compute an exception specification for an enclosed class.
6012 //
6013 // Any attempt to resolve the exception specification of a defaulted default
6014 // constructor before the initializer is lexically complete will ultimately
6015 // come here at which point we can diagnose it.
6016 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
6017 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
6018 << OutermostClass << Field;
6019 Diag(Field->getEndLoc(),
6020 diag::note_default_member_initializer_not_yet_parsed);
6021 // Recover by marking the field invalid, unless we're in a SFINAE context.
6022 if (!isSFINAEContext())
6023 Field->setInvalidDecl();
6024 return ExprError();
6025}
6026
6028 const FunctionProtoType *Proto,
6029 Expr *Fn) {
6030 if (Proto && Proto->isVariadic()) {
6031 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
6033 else if (Fn && Fn->getType()->isBlockPointerType())
6035 else if (FDecl) {
6036 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6037 if (Method->isInstance())
6039 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
6042 }
6044}
6045
6046namespace {
6047class FunctionCallCCC final : public FunctionCallFilterCCC {
6048public:
6049 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6050 unsigned NumArgs, MemberExpr *ME)
6051 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6052 FunctionName(FuncName) {}
6053
6054 bool ValidateCandidate(const TypoCorrection &candidate) override {
6055 if (!candidate.getCorrectionSpecifier() ||
6056 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6057 return false;
6058 }
6059
6061 }
6062
6063 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6064 return std::make_unique<FunctionCallCCC>(*this);
6065 }
6066
6067private:
6068 const IdentifierInfo *const FunctionName;
6069};
6070}
6071
6073 FunctionDecl *FDecl,
6074 ArrayRef<Expr *> Args) {
6075 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
6076 DeclarationName FuncName = FDecl->getDeclName();
6077 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6078
6079 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6080 if (TypoCorrection Corrected = S.CorrectTypo(
6082 S.getScopeForContext(S.CurContext), nullptr, CCC,
6084 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6085 if (Corrected.isOverloaded()) {
6088 for (NamedDecl *CD : Corrected) {
6089 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6091 OCS);
6092 }
6093 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6094 case OR_Success:
6095 ND = Best->FoundDecl;
6096 Corrected.setCorrectionDecl(ND);
6097 break;
6098 default:
6099 break;
6100 }
6101 }
6102 ND = ND->getUnderlyingDecl();
6104 return Corrected;
6105 }
6106 }
6107 return TypoCorrection();
6108}
6109
6110// [C++26][[expr.unary.op]/p4
6111// A pointer to member is only formed when an explicit &
6112// is used and its operand is a qualified-id not enclosed in parentheses.
6114 if (!isa<ParenExpr>(Fn))
6115 return false;
6116
6117 Fn = Fn->IgnoreParens();
6118
6119 auto *UO = dyn_cast<UnaryOperator>(Fn);
6120 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6121 return false;
6122 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
6123 return DRE->hasQualifier();
6124 }
6125 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
6126 return bool(OVL->getQualifier());
6127 return false;
6128}
6129
6130bool
6132 FunctionDecl *FDecl,
6133 const FunctionProtoType *Proto,
6134 ArrayRef<Expr *> Args,
6135 SourceLocation RParenLoc,
6136 bool IsExecConfig) {
6137 // Bail out early if calling a builtin with custom typechecking.
6138 // For HLSL builtin aliases, argument conversion is still needed because
6139 // overload resolution may have selected a conversion sequence (e.g.,
6140 // vector-to-scalar truncation) that must be applied before the custom
6141 // type checker runs.
6142 if (FDecl)
6143 if (unsigned ID = FDecl->getBuiltinID())
6144 if (Context.BuiltinInfo.hasCustomTypechecking(ID) &&
6145 !(Context.getLangOpts().HLSL && FDecl->hasAttr<BuiltinAliasAttr>()))
6146 return false;
6147
6148 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6149 // assignment, to the types of the corresponding parameter, ...
6150
6151 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6152 bool HasExplicitObjectParameter =
6153 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6154 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6155 unsigned NumParams = Proto->getNumParams();
6156 bool Invalid = false;
6157 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6158 unsigned FnKind = Fn->getType()->isBlockPointerType()
6159 ? 1 /* block */
6160 : (IsExecConfig ? 3 /* kernel function (exec config) */
6161 : 0 /* function */);
6162
6163 // If too few arguments are available (and we don't have default
6164 // arguments for the remaining parameters), don't make the call.
6165 if (Args.size() < NumParams) {
6166 if (Args.size() < MinArgs) {
6167 TypoCorrection TC;
6168 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6169 unsigned diag_id =
6170 MinArgs == NumParams && !Proto->isVariadic()
6171 ? diag::err_typecheck_call_too_few_args_suggest
6172 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6174 TC, PDiag(diag_id)
6175 << FnKind << MinArgs - ExplicitObjectParameterOffset
6176 << static_cast<unsigned>(Args.size()) -
6177 ExplicitObjectParameterOffset
6178 << HasExplicitObjectParameter << TC.getCorrectionRange());
6179 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6180 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6181 ->getDeclName())
6182 Diag(RParenLoc,
6183 MinArgs == NumParams && !Proto->isVariadic()
6184 ? diag::err_typecheck_call_too_few_args_one
6185 : diag::err_typecheck_call_too_few_args_at_least_one)
6186 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6187 << HasExplicitObjectParameter << Fn->getSourceRange();
6188 else
6189 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6190 ? diag::err_typecheck_call_too_few_args
6191 : diag::err_typecheck_call_too_few_args_at_least)
6192 << FnKind << MinArgs - ExplicitObjectParameterOffset
6193 << static_cast<unsigned>(Args.size()) -
6194 ExplicitObjectParameterOffset
6195 << HasExplicitObjectParameter << Fn->getSourceRange();
6196
6197 // Emit the location of the prototype.
6198 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6199 Diag(FDecl->getLocation(), diag::note_callee_decl)
6200 << FDecl << FDecl->getParametersSourceRange();
6201
6202 return true;
6203 }
6204 // We reserve space for the default arguments when we create
6205 // the call expression, before calling ConvertArgumentsForCall.
6206 assert((Call->getNumArgs() == NumParams) &&
6207 "We should have reserved space for the default arguments before!");
6208 }
6209
6210 // If too many are passed and not variadic, error on the extras and drop
6211 // them.
6212 if (Args.size() > NumParams) {
6213 if (!Proto->isVariadic()) {
6214 TypoCorrection TC;
6215 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6216 unsigned diag_id =
6217 MinArgs == NumParams && !Proto->isVariadic()
6218 ? diag::err_typecheck_call_too_many_args_suggest
6219 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6221 TC, PDiag(diag_id)
6222 << FnKind << NumParams - ExplicitObjectParameterOffset
6223 << static_cast<unsigned>(Args.size()) -
6224 ExplicitObjectParameterOffset
6225 << HasExplicitObjectParameter << TC.getCorrectionRange());
6226 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6227 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6228 ->getDeclName())
6229 Diag(Args[NumParams]->getBeginLoc(),
6230 MinArgs == NumParams
6231 ? diag::err_typecheck_call_too_many_args_one
6232 : diag::err_typecheck_call_too_many_args_at_most_one)
6233 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6234 << static_cast<unsigned>(Args.size()) -
6235 ExplicitObjectParameterOffset
6236 << HasExplicitObjectParameter << Fn->getSourceRange()
6237 << SourceRange(Args[NumParams]->getBeginLoc(),
6238 Args.back()->getEndLoc());
6239 else
6240 Diag(Args[NumParams]->getBeginLoc(),
6241 MinArgs == NumParams
6242 ? diag::err_typecheck_call_too_many_args
6243 : diag::err_typecheck_call_too_many_args_at_most)
6244 << FnKind << NumParams - ExplicitObjectParameterOffset
6245 << static_cast<unsigned>(Args.size()) -
6246 ExplicitObjectParameterOffset
6247 << HasExplicitObjectParameter << Fn->getSourceRange()
6248 << SourceRange(Args[NumParams]->getBeginLoc(),
6249 Args.back()->getEndLoc());
6250
6251 // Emit the location of the prototype.
6252 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6253 Diag(FDecl->getLocation(), diag::note_callee_decl)
6254 << FDecl << FDecl->getParametersSourceRange();
6255
6256 // This deletes the extra arguments.
6257 Call->shrinkNumArgs(NumParams);
6258 return true;
6259 }
6260 }
6261 SmallVector<Expr *, 8> AllArgs;
6262 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6263
6264 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
6265 AllArgs, CallType);
6266 if (Invalid)
6267 return true;
6268 unsigned TotalNumArgs = AllArgs.size();
6269 for (unsigned i = 0; i < TotalNumArgs; ++i)
6270 Call->setArg(i, AllArgs[i]);
6271
6272 Call->computeDependence();
6273 return false;
6274}
6275
6277 const FunctionProtoType *Proto,
6278 unsigned FirstParam, ArrayRef<Expr *> Args,
6279 SmallVectorImpl<Expr *> &AllArgs,
6280 VariadicCallType CallType, bool AllowExplicit,
6281 bool IsListInitialization) {
6282 unsigned NumParams = Proto->getNumParams();
6283 bool Invalid = false;
6284 size_t ArgIx = 0;
6285 // Continue to check argument types (even if we have too few/many args).
6286 for (unsigned i = FirstParam; i < NumParams; i++) {
6287 QualType ProtoArgType = Proto->getParamType(i);
6288
6289 Expr *Arg;
6290 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6291 if (ArgIx < Args.size()) {
6292 Arg = Args[ArgIx++];
6293
6294 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6295 diag::err_call_incomplete_argument, Arg))
6296 return true;
6297
6298 // Strip the unbridged-cast placeholder expression off, if applicable.
6299 bool CFAudited = false;
6300 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6301 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6302 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6303 Arg = ObjC().stripARCUnbridgedCast(Arg);
6304 else if (getLangOpts().ObjCAutoRefCount &&
6305 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6306 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6307 CFAudited = true;
6308
6309 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6310 ProtoArgType->isBlockPointerType())
6311 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6312 BE->getBlockDecl()->setDoesNotEscape();
6313 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
6315 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6316 if (ArgExpr.isInvalid())
6317 return true;
6318 Arg = ArgExpr.getAs<Expr>();
6319 }
6320
6321 InitializedEntity Entity =
6323 ProtoArgType)
6325 Context, ProtoArgType, Proto->isParamConsumed(i));
6326
6327 // Remember that parameter belongs to a CF audited API.
6328 if (CFAudited)
6329 Entity.setParameterCFAudited();
6330
6331 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6332 // function boundaries is a common oversight.
6333 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6334 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6335 bool isPedantic =
6336 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6337 Diag(Arg->getExprLoc(),
6338 isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6339 : diag::warn_obt_discarded_at_function_boundary)
6340 << Arg->getType() << ProtoArgType;
6341 }
6342
6344 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6345 if (ArgE.isInvalid())
6346 return true;
6347
6348 Arg = ArgE.getAs<Expr>();
6349 } else {
6350 assert(Param && "can't use default arguments without a known callee");
6351
6352 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6353 if (ArgExpr.isInvalid())
6354 return true;
6355
6356 Arg = ArgExpr.getAs<Expr>();
6357 }
6358
6359 // Check for array bounds violations for each argument to the call. This
6360 // check only triggers warnings when the argument isn't a more complex Expr
6361 // with its own checking, such as a BinaryOperator.
6362 CheckArrayAccess(Arg);
6363
6364 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6365 CheckStaticArrayArgument(CallLoc, Param, Arg);
6366
6367 AllArgs.push_back(Arg);
6368 }
6369
6370 // If this is a variadic call, handle args passed through "...".
6371 if (CallType != VariadicCallType::DoesNotApply) {
6372 // Assume that extern "C" functions with variadic arguments that
6373 // return __unknown_anytype aren't *really* variadic.
6374 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6375 FDecl->isExternC()) {
6376 for (Expr *A : Args.slice(ArgIx)) {
6377 QualType paramType; // ignored
6378 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6379 Invalid |= arg.isInvalid();
6380 AllArgs.push_back(arg.get());
6381 }
6382
6383 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6384 } else {
6385 for (Expr *A : Args.slice(ArgIx)) {
6386 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6387 Invalid |= Arg.isInvalid();
6388 AllArgs.push_back(Arg.get());
6389 }
6390 }
6391
6392 // Check for array bounds violations.
6393 for (Expr *A : Args.slice(ArgIx))
6394 CheckArrayAccess(A);
6395 }
6396 return Invalid;
6397}
6398
6400 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6401 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6402 TL = DTL.getOriginalLoc();
6403 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6404 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6405 << ATL.getLocalSourceRange();
6406}
6407
6408void
6410 ParmVarDecl *Param,
6411 const Expr *ArgExpr) {
6412 // Static array parameters are not supported in C++.
6413 if (!Param || getLangOpts().CPlusPlus)
6414 return;
6415
6416 QualType OrigTy = Param->getOriginalType();
6417
6418 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6419 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6420 return;
6421
6422 if (ArgExpr->isNullPointerConstant(Context,
6424 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6425 DiagnoseCalleeStaticArrayParam(*this, Param);
6426 return;
6427 }
6428
6429 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6430 if (!CAT)
6431 return;
6432
6433 const ConstantArrayType *ArgCAT =
6434 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6435 if (!ArgCAT)
6436 return;
6437
6438 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6439 ArgCAT->getElementType())) {
6440 if (ArgCAT->getSize().ult(CAT->getSize())) {
6441 Diag(CallLoc, diag::warn_static_array_too_small)
6442 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6443 << (unsigned)CAT->getZExtSize() << 0;
6444 DiagnoseCalleeStaticArrayParam(*this, Param);
6445 }
6446 return;
6447 }
6448
6449 std::optional<CharUnits> ArgSize =
6451 std::optional<CharUnits> ParmSize =
6453 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6454 Diag(CallLoc, diag::warn_static_array_too_small)
6455 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6456 << (unsigned)ParmSize->getQuantity() << 1;
6457 DiagnoseCalleeStaticArrayParam(*this, Param);
6458 }
6459}
6460
6461/// Given a function expression of unknown-any type, try to rebuild it
6462/// to have a function type.
6464
6465/// Is the given type a placeholder that we need to lower out
6466/// immediately during argument processing?
6468 // Placeholders are never sugared.
6469 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6470 if (!placeholder) return false;
6471
6472 switch (placeholder->getKind()) {
6473 // Ignore all the non-placeholder types.
6474#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6475 case BuiltinType::Id:
6476#include "clang/Basic/OpenCLImageTypes.def"
6477#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6478 case BuiltinType::Id:
6479#include "clang/Basic/OpenCLExtensionTypes.def"
6480 // In practice we'll never use this, since all SVE types are sugared
6481 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6482#define SVE_TYPE(Name, Id, SingletonId) \
6483 case BuiltinType::Id:
6484#include "clang/Basic/AArch64ACLETypes.def"
6485#define PPC_VECTOR_TYPE(Name, Id, Size) \
6486 case BuiltinType::Id:
6487#include "clang/Basic/PPCTypes.def"
6488#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6489#include "clang/Basic/RISCVVTypes.def"
6490#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6491#include "clang/Basic/WebAssemblyReferenceTypes.def"
6492#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6493#include "clang/Basic/AMDGPUTypes.def"
6494#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6495#include "clang/Basic/HLSLIntangibleTypes.def"
6496#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6497#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6498#include "clang/AST/BuiltinTypes.def"
6499 return false;
6500
6501 case BuiltinType::UnresolvedTemplate:
6502 // We cannot lower out overload sets; they might validly be resolved
6503 // by the call machinery.
6504 case BuiltinType::Overload:
6505 return false;
6506
6507 // Unbridged casts in ARC can be handled in some call positions and
6508 // should be left in place.
6509 case BuiltinType::ARCUnbridgedCast:
6510 return false;
6511
6512 // Pseudo-objects should be converted as soon as possible.
6513 case BuiltinType::PseudoObject:
6514 return true;
6515
6516 // The debugger mode could theoretically but currently does not try
6517 // to resolve unknown-typed arguments based on known parameter types.
6518 case BuiltinType::UnknownAny:
6519 return true;
6520
6521 // These are always invalid as call arguments and should be reported.
6522 case BuiltinType::BoundMember:
6523 case BuiltinType::BuiltinFn:
6524 case BuiltinType::IncompleteMatrixIdx:
6525 case BuiltinType::ArraySection:
6526 case BuiltinType::OMPArrayShaping:
6527 case BuiltinType::OMPIterator:
6528 return true;
6529
6530 }
6531 llvm_unreachable("bad builtin type kind");
6532}
6533
6535 // Apply this processing to all the arguments at once instead of
6536 // dying at the first failure.
6537 bool hasInvalid = false;
6538 for (size_t i = 0, e = args.size(); i != e; i++) {
6539 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6540 ExprResult result = CheckPlaceholderExpr(args[i]);
6541 if (result.isInvalid()) hasInvalid = true;
6542 else args[i] = result.get();
6543 }
6544 }
6545 return hasInvalid;
6546}
6547
6548/// If a builtin function has a pointer argument with no explicit address
6549/// space, then it should be able to accept a pointer to any address
6550/// space as input. In order to do this, we need to replace the
6551/// standard builtin declaration with one that uses the same address space
6552/// as the call.
6553///
6554/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6555/// it does not contain any pointer arguments without
6556/// an address space qualifer. Otherwise the rewritten
6557/// FunctionDecl is returned.
6558/// TODO: Handle pointer return types.
6560 FunctionDecl *FDecl,
6561 MultiExprArg ArgExprs) {
6562
6563 QualType DeclType = FDecl->getType();
6564 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6565
6566 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6567 ArgExprs.size() < FT->getNumParams())
6568 return nullptr;
6569
6570 bool NeedsNewDecl = false;
6571 unsigned i = 0;
6572 SmallVector<QualType, 8> OverloadParams;
6573
6574 {
6575 // The lvalue conversions in this loop are only for type resolution and
6576 // don't actually occur.
6579 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6580
6581 for (QualType ParamType : FT->param_types()) {
6582
6583 // Convert array arguments to pointer to simplify type lookup.
6584 ExprResult ArgRes =
6586 if (ArgRes.isInvalid())
6587 return nullptr;
6588 Expr *Arg = ArgRes.get();
6589 QualType ArgType = Arg->getType();
6590 if (!ParamType->isPointerType() ||
6591 ParamType->getPointeeType().hasAddressSpace() ||
6592 !ArgType->isPointerType() ||
6593 !ArgType->getPointeeType().hasAddressSpace() ||
6594 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6595 OverloadParams.push_back(ParamType);
6596 continue;
6597 }
6598
6599 QualType PointeeType = ParamType->getPointeeType();
6600 NeedsNewDecl = true;
6601 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6602
6603 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6604 OverloadParams.push_back(Context.getPointerType(PointeeType));
6605 }
6606 }
6607
6608 if (!NeedsNewDecl)
6609 return nullptr;
6610
6612 EPI.Variadic = FT->isVariadic();
6613 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6614 OverloadParams, EPI);
6615 DeclContext *Parent = FDecl->getParent();
6616 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6617 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6618 FDecl->getIdentifier(), OverloadTy,
6619 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6620 false,
6621 /*hasPrototype=*/true);
6623 FT = cast<FunctionProtoType>(OverloadTy);
6624 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6625 QualType ParamType = FT->getParamType(i);
6626 ParmVarDecl *Parm =
6627 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6628 SourceLocation(), nullptr, ParamType,
6629 /*TInfo=*/nullptr, SC_None, nullptr);
6630 Parm->setScopeInfo(0, i);
6631 Params.push_back(Parm);
6632 }
6633 OverloadDecl->setParams(Params);
6634 // We cannot merge host/device attributes of redeclarations. They have to
6635 // be consistent when created.
6636 if (Sema->LangOpts.CUDA) {
6637 if (FDecl->hasAttr<CUDAHostAttr>())
6638 OverloadDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
6639 if (FDecl->hasAttr<CUDADeviceAttr>())
6640 OverloadDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
6641 }
6642 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6643 return OverloadDecl;
6644}
6645
6646static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6647 FunctionDecl *Callee,
6648 MultiExprArg ArgExprs) {
6649 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6650 // similar attributes) really don't like it when functions are called with an
6651 // invalid number of args.
6652 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6653 /*PartialOverloading=*/false) &&
6654 !Callee->isVariadic())
6655 return;
6656 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6657 return;
6658
6659 if (const EnableIfAttr *Attr =
6660 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6661 S.Diag(Fn->getBeginLoc(),
6662 isa<CXXMethodDecl>(Callee)
6663 ? diag::err_ovl_no_viable_member_function_in_call
6664 : diag::err_ovl_no_viable_function_in_call)
6665 << Callee << Callee->getSourceRange();
6666 S.Diag(Callee->getLocation(),
6667 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6668 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6669 return;
6670 }
6671}
6672
6674 const UnresolvedMemberExpr *const UME, Sema &S) {
6675
6676 const auto GetFunctionLevelDCIfCXXClass =
6677 [](Sema &S) -> const CXXRecordDecl * {
6678 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6679 if (!DC || !DC->getParent())
6680 return nullptr;
6681
6682 // If the call to some member function was made from within a member
6683 // function body 'M' return return 'M's parent.
6684 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6685 return MD->getParent()->getCanonicalDecl();
6686 // else the call was made from within a default member initializer of a
6687 // class, so return the class.
6688 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6689 return RD->getCanonicalDecl();
6690 return nullptr;
6691 };
6692 // If our DeclContext is neither a member function nor a class (in the
6693 // case of a lambda in a default member initializer), we can't have an
6694 // enclosing 'this'.
6695
6696 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6697 if (!CurParentClass)
6698 return false;
6699
6700 // The naming class for implicit member functions call is the class in which
6701 // name lookup starts.
6702 const CXXRecordDecl *const NamingClass =
6704 assert(NamingClass && "Must have naming class even for implicit access");
6705
6706 // If the unresolved member functions were found in a 'naming class' that is
6707 // related (either the same or derived from) to the class that contains the
6708 // member function that itself contained the implicit member access.
6709
6710 return CurParentClass == NamingClass ||
6711 CurParentClass->isDerivedFrom(NamingClass);
6712}
6713
6714static void
6716 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6717
6718 if (!UME)
6719 return;
6720
6721 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6722 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6723 // already been captured, or if this is an implicit member function call (if
6724 // it isn't, an attempt to capture 'this' should already have been made).
6725 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6726 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6727 return;
6728
6729 // Check if the naming class in which the unresolved members were found is
6730 // related (same as or is a base of) to the enclosing class.
6731
6733 return;
6734
6735
6736 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6737 // If the enclosing function is not dependent, then this lambda is
6738 // capture ready, so if we can capture this, do so.
6739 if (!EnclosingFunctionCtx->isDependentContext()) {
6740 // If the current lambda and all enclosing lambdas can capture 'this' -
6741 // then go ahead and capture 'this' (since our unresolved overload set
6742 // contains at least one non-static member function).
6743 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6744 S.CheckCXXThisCapture(CallLoc);
6745 } else if (S.CurContext->isDependentContext()) {
6746 // ... since this is an implicit member reference, that might potentially
6747 // involve a 'this' capture, mark 'this' for potential capture in
6748 // enclosing lambdas.
6749 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6750 CurLSI->addPotentialThisCapture(CallLoc);
6751 }
6752}
6753
6754// Once a call is fully resolved, warn for unqualified calls to specific
6755// C++ standard functions, like move and forward.
6757 const CallExpr *Call) {
6758 // We are only checking unary move and forward so exit early here.
6759 if (Call->getNumArgs() != 1)
6760 return;
6761
6762 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6763 if (!E || isa<UnresolvedLookupExpr>(E))
6764 return;
6765 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6766 if (!DRE || !DRE->getLocation().isValid())
6767 return;
6768
6769 if (DRE->getQualifier())
6770 return;
6771
6772 const FunctionDecl *FD = Call->getDirectCallee();
6773 if (!FD)
6774 return;
6775
6776 // Only warn for some functions deemed more frequent or problematic.
6777 unsigned BuiltinID = FD->getBuiltinID();
6778 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6779 return;
6780
6781 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6783 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6784}
6785
6787 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6788 Expr *ExecConfig) {
6790 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6791 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6792 if (Call.isInvalid())
6793 return Call;
6794
6795 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6796 // language modes.
6797 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6798 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6799 DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id)
6800 << ULE->getName();
6801 }
6802
6803 if (LangOpts.OpenMP)
6804 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6805 ExecConfig);
6806 if (LangOpts.CPlusPlus) {
6807 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6809
6810 // If we previously found that the id-expression of this call refers to a
6811 // consteval function but the call is dependent, we should not treat is an
6812 // an invalid immediate call.
6813 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6814 DRE && Call.get()->isValueDependent()) {
6816 }
6817 }
6818 return Call;
6819}
6820
6821// Any type that could be used to form a callable expression
6822static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6823 QualType T = E->getType();
6824 if (T->isDependentType())
6825 return true;
6826
6827 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6828 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6829 T->isFunctionType() || T->isFunctionReferenceType() ||
6830 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6831 T->isBlockPointerType() || T->isRecordType())
6832 return true;
6833
6836}
6837
6839 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6840 Expr *ExecConfig, bool IsExecConfig,
6841 bool AllowRecovery) {
6842 // Since this might be a postfix expression, get rid of ParenListExprs.
6844 if (Result.isInvalid()) return ExprError();
6845 Fn = Result.get();
6846
6847 // The __builtin_amdgcn_is_invocable builtin is special, and will be resolved
6848 // later, when we check boolean conditions, for now we merely forward it
6849 // without any additional checking.
6850 if (Fn->getType() == Context.BuiltinFnTy && ArgExprs.size() == 1 &&
6851 ArgExprs[0]->getType() == Context.BuiltinFnTy) {
6852 const auto *FD = cast<FunctionDecl>(Fn->getReferencedDeclOfCallee());
6853
6854 if (FD->getName() == "__builtin_amdgcn_is_invocable") {
6855 QualType FnPtrTy = Context.getPointerType(FD->getType());
6856 Expr *R = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6857 return CallExpr::Create(
6858 Context, R, ArgExprs, Context.AMDGPUFeaturePredicateTy,
6860 }
6861 }
6862
6863 if (CheckArgsForPlaceholders(ArgExprs))
6864 return ExprError();
6865
6866 // The result of __builtin_counted_by_ref cannot be used as a function
6867 // argument. It allows leaking and modification of bounds safety information.
6868 for (const Expr *Arg : ArgExprs)
6869 if (CheckInvalidBuiltinCountedByRef(Arg,
6871 return ExprError();
6872
6873 if (getLangOpts().CPlusPlus) {
6874 // If this is a pseudo-destructor expression, build the call immediately.
6876 if (!ArgExprs.empty()) {
6877 // Pseudo-destructor calls should not have any arguments.
6878 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6880 SourceRange(ArgExprs.front()->getBeginLoc(),
6881 ArgExprs.back()->getEndLoc()));
6882 }
6883
6884 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6885 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6886 }
6887 if (Fn->getType() == Context.PseudoObjectTy) {
6888 ExprResult result = CheckPlaceholderExpr(Fn);
6889 if (result.isInvalid()) return ExprError();
6890 Fn = result.get();
6891 }
6892
6893 // Determine whether this is a dependent call inside a C++ template,
6894 // in which case we won't do any semantic analysis now.
6895 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6896 if (ExecConfig) {
6898 cast<CallExpr>(ExecConfig), ArgExprs,
6899 Context.DependentTy, VK_PRValue,
6900 RParenLoc, CurFPFeatureOverrides());
6901 } else {
6902
6904 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6905 Fn->getBeginLoc());
6906
6907 // If the type of the function itself is not dependent
6908 // check that it is a reasonable as a function, as type deduction
6909 // later assume the CallExpr has a sensible TYPE.
6910 if (!MayBeFunctionType(Context, Fn))
6911 return ExprError(
6912 Diag(LParenLoc, diag::err_typecheck_call_not_function)
6913 << Fn->getType() << Fn->getSourceRange());
6914
6915 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6916 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6917 }
6918 }
6919
6920 // Determine whether this is a call to an object (C++ [over.call.object]).
6921 if (Fn->getType()->isRecordType())
6922 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6923 RParenLoc);
6924
6925 if (Fn->getType() == Context.UnknownAnyTy) {
6926 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6927 if (result.isInvalid()) return ExprError();
6928 Fn = result.get();
6929 }
6930
6931 if (Fn->getType() == Context.BoundMemberTy) {
6932 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6933 RParenLoc, ExecConfig, IsExecConfig,
6934 AllowRecovery);
6935 }
6936 }
6937
6938 // Check for overloaded calls. This can happen even in C due to extensions.
6939 if (Fn->getType() == Context.OverloadTy) {
6941
6942 // We aren't supposed to apply this logic if there's an '&' involved.
6945 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6946 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6947 OverloadExpr *ovl = find.Expression;
6948 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6950 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6951 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6952 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6953 RParenLoc, ExecConfig, IsExecConfig,
6954 AllowRecovery);
6955 }
6956 }
6957
6958 // If we're directly calling a function, get the appropriate declaration.
6959 if (Fn->getType() == Context.UnknownAnyTy) {
6960 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6961 if (result.isInvalid()) return ExprError();
6962 Fn = result.get();
6963 }
6964
6965 Expr *NakedFn = Fn->IgnoreParens();
6966
6967 bool CallingNDeclIndirectly = false;
6968 NamedDecl *NDecl = nullptr;
6969 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6970 if (UnOp->getOpcode() == UO_AddrOf) {
6971 CallingNDeclIndirectly = true;
6972 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6973 }
6974 }
6975
6976 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6977 NDecl = DRE->getDecl();
6978
6979 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6980 if (FDecl && FDecl->getBuiltinID()) {
6981 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
6982 if (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD) {
6983 if (Context.BuiltinInfo.isTSBuiltin(FDecl->getBuiltinID()) &&
6984 !Context.BuiltinInfo.isAuxBuiltinID(FDecl->getBuiltinID())) {
6986 getFunctionLevelDeclContext(/*AllowLambda=*/true)));
6987 }
6988 }
6989
6990 // Rewrite the function decl for this builtin by replacing parameters
6991 // with no explicit address space with the address space of the arguments
6992 // in ArgExprs.
6993 if ((FDecl =
6994 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6995 NDecl = FDecl;
6997 Context, DRE->getQualifierLoc(), SourceLocation(), FDecl, false,
6998 SourceLocation(), Fn->getType() /* BuiltinFnTy */,
6999 Fn->getValueKind(), FDecl, nullptr, DRE->isNonOdrUse());
7000 }
7001 }
7002 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
7003 NDecl = ME->getMemberDecl();
7004
7005 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
7006 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
7007 FD, /*Complain=*/true, Fn->getBeginLoc()))
7008 return ExprError();
7009
7010 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
7011
7012 // If this expression is a call to a builtin function in HIP compilation,
7013 // allow a pointer-type argument to default address space to be passed as a
7014 // pointer-type parameter to a non-default address space. If Arg is declared
7015 // in the default address space and Param is declared in a non-default
7016 // address space, perform an implicit address space cast to the parameter
7017 // type.
7018 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
7019 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
7020 ++Idx) {
7021 ParmVarDecl *Param = FD->getParamDecl(Idx);
7022 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
7023 !ArgExprs[Idx]->getType()->isPointerType())
7024 continue;
7025
7026 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
7027 auto ArgTy = ArgExprs[Idx]->getType();
7028 auto ArgPtTy = ArgTy->getPointeeType();
7029 auto ArgAS = ArgPtTy.getAddressSpace();
7030
7031 // Add address space cast if target address spaces are different
7032 bool NeedImplicitASC =
7033 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
7034 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
7035 // or from specific AS which has target AS matching that of Param.
7037 if (!NeedImplicitASC)
7038 continue;
7039
7040 // First, ensure that the Arg is an RValue.
7041 if (ArgExprs[Idx]->isGLValue()) {
7042 ExprResult Res = DefaultLvalueConversion(ArgExprs[Idx]);
7043 if (Res.isInvalid())
7044 return ExprError();
7045 ArgExprs[Idx] = Res.get();
7046 }
7047
7048 // Construct a new arg type with address space of Param
7049 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7050 ArgPtQuals.setAddressSpace(ParamAS);
7051 auto NewArgPtTy =
7052 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
7053 auto NewArgTy =
7054 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
7055 ArgTy.getQualifiers());
7056
7057 // Finally perform an implicit address space cast
7058 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
7059 CK_AddressSpaceConversion)
7060 .get();
7061 }
7062 }
7063 }
7064
7065 if (Context.isDependenceAllowed() &&
7066 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
7067 assert(!getLangOpts().CPlusPlus);
7068 assert((Fn->containsErrors() ||
7069 llvm::any_of(ArgExprs,
7070 [](clang::Expr *E) { return E->containsErrors(); })) &&
7071 "should only occur in error-recovery path.");
7072 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7073 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7074 }
7075 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
7076 ExecConfig, IsExecConfig);
7077}
7078
7080 MultiExprArg CallArgs) {
7081 std::string Name = Context.BuiltinInfo.getName(Id);
7082 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7084 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
7085
7086 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7087 assert(BuiltInDecl && "failed to find builtin declaration");
7088
7089 ExprResult DeclRef =
7090 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7091 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7092
7094 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
7095
7096 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7097 return Call.get();
7098}
7099
7101 SourceLocation BuiltinLoc,
7102 SourceLocation RParenLoc) {
7103 QualType DstTy = GetTypeFromParser(ParsedDestTy);
7104 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
7105}
7106
7108 SourceLocation BuiltinLoc,
7109 SourceLocation RParenLoc) {
7112 QualType SrcTy = E->getType();
7113 if (!SrcTy->isDependentType() &&
7114 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7115 return ExprError(
7116 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7117 << DestTy << SrcTy << E->getSourceRange());
7118 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7119}
7120
7122 SourceLocation BuiltinLoc,
7123 SourceLocation RParenLoc) {
7124 TypeSourceInfo *TInfo;
7125 GetTypeFromParser(ParsedDestTy, &TInfo);
7126 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7127}
7128
7130 SourceLocation LParenLoc,
7131 ArrayRef<Expr *> Args,
7132 SourceLocation RParenLoc, Expr *Config,
7133 bool IsExecConfig, ADLCallKind UsesADL) {
7134 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
7135 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7136
7137 auto IsSJLJ = [&] {
7138 switch (BuiltinID) {
7139 case Builtin::BI__builtin_longjmp:
7140 case Builtin::BI__builtin_setjmp:
7141 case Builtin::BI__sigsetjmp:
7142 case Builtin::BI_longjmp:
7143 case Builtin::BI_setjmp:
7144 case Builtin::BIlongjmp:
7145 case Builtin::BIsetjmp:
7146 case Builtin::BIsiglongjmp:
7147 case Builtin::BIsigsetjmp:
7148 return true;
7149 default:
7150 return false;
7151 }
7152 };
7153
7154 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7155 if (!CurrentDefer.empty() && IsSJLJ()) {
7156 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7157 // for more than just blocks (e.g. lambdas, nested classes...).
7158 Scope *DeferParent = CurrentDefer.back().first;
7159 Scope *Block = CurScope->getBlockParent();
7160 if (DeferParent->Contains(*CurScope) &&
7161 (!Block || !DeferParent->Contains(*Block)))
7162 Diag(Fn->getExprLoc(), diag::err_defer_invalid_sjlj) << FDecl;
7163 }
7164
7165 // Functions with 'interrupt' attribute cannot be called directly.
7166 if (FDecl) {
7167 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7168 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7169 return ExprError();
7170 }
7171 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7172 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
7173 return ExprError();
7174 }
7175 }
7176
7177 // X86 interrupt handlers may only call routines with attribute
7178 // no_caller_saved_registers since there is no efficient way to
7179 // save and restore the non-GPR state.
7180 if (auto *Caller = getCurFunctionDecl()) {
7181 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7182 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7183 const TargetInfo &TI = Context.getTargetInfo();
7184 bool HasNonGPRRegisters =
7185 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
7186 if (HasNonGPRRegisters &&
7187 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7188 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
7189 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7190 if (FDecl)
7191 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7192 }
7193 }
7194 }
7195
7196 // Extract the return type from the builtin function pointer type.
7197 QualType ResultTy;
7198 if (BuiltinID)
7199 ResultTy = FDecl->getCallResultType();
7200 else
7201 ResultTy = Context.BoolTy;
7202
7203 // Promote the function operand.
7204 // We special-case function promotion here because we only allow promoting
7205 // builtin functions to function pointers in the callee of a call.
7207 if (BuiltinID &&
7208 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7209 // FIXME Several builtins still have setType in
7210 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7211 // Builtins.td to ensure they are correct before removing setType calls.
7212 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7213 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7214 } else
7216 if (Result.isInvalid())
7217 return ExprError();
7218 Fn = Result.get();
7219
7220 // Check for a valid function type, but only if it is not a builtin which
7221 // requires custom type checking. These will be handled by
7222 // CheckBuiltinFunctionCall below just after creation of the call expression.
7223 const FunctionType *FuncT = nullptr;
7224 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7225 retry:
7226 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7227 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7228 // have type pointer to function".
7229 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7230 if (!FuncT)
7231 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7232 << Fn->getType() << Fn->getSourceRange());
7233 } else if (const BlockPointerType *BPT =
7234 Fn->getType()->getAs<BlockPointerType>()) {
7235 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7236 } else {
7237 // Handle calls to expressions of unknown-any type.
7238 if (Fn->getType() == Context.UnknownAnyTy) {
7239 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7240 if (rewrite.isInvalid())
7241 return ExprError();
7242 Fn = rewrite.get();
7243 goto retry;
7244 }
7245
7246 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7247 << Fn->getType() << Fn->getSourceRange());
7248 }
7249 }
7250
7251 // Get the number of parameters in the function prototype, if any.
7252 // We will allocate space for max(Args.size(), NumParams) arguments
7253 // in the call expression.
7254 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7255 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7256
7257 CallExpr *TheCall;
7258 if (Config) {
7259 assert(UsesADL == ADLCallKind::NotADL &&
7260 "CUDAKernelCallExpr should not use ADL");
7261 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7262 Args, ResultTy, VK_PRValue, RParenLoc,
7263 CurFPFeatureOverrides(), NumParams);
7264 } else {
7265 TheCall =
7266 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7267 CurFPFeatureOverrides(), NumParams, UsesADL);
7268 }
7269
7270 // Bail out early if calling a builtin with custom type checking.
7271 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7272 // For HLSL builtin aliases, the call was resolved via overload resolution
7273 // which may have selected a conversion sequence (e.g., vector-to-scalar
7274 // truncation). Convert arguments to match the declared prototype before
7275 // the custom type checker runs, otherwise the builtin will operate on
7276 // the unconverted argument types.
7277 if (getLangOpts().HLSL && FDecl && FDecl->hasAttr<BuiltinAliasAttr>()) {
7278 if (const auto *P = FDecl->getType()->getAs<FunctionProtoType>()) {
7279 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, P, Args, RParenLoc,
7280 IsExecConfig))
7281 return ExprError();
7282 }
7283 }
7284 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7285 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
7286 E = CheckForImmediateInvocation(E, FDecl);
7287 return E;
7288 }
7289
7290 if (getLangOpts().CUDA) {
7291 if (Config) {
7292 // CUDA: Kernel calls must be to global functions
7293 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7294 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7295 << FDecl << Fn->getSourceRange());
7296
7297 // CUDA: Kernel function must have 'void' return type
7298 if (!FuncT->getReturnType()->isVoidType() &&
7299 !FuncT->getReturnType()->getAs<AutoType>() &&
7301 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7302 << Fn->getType() << Fn->getSourceRange());
7303 } else {
7304 // CUDA: Calls to global functions must be configured
7305 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7306 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7307 << FDecl << Fn->getSourceRange());
7308 }
7309 }
7310
7311 // Check for a valid return type
7312 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7313 FDecl))
7314 return ExprError();
7315
7316 // We know the result type of the call, set it.
7317 TheCall->setType(FuncT->getCallResultType(Context));
7319
7320 // WebAssembly tables can't be used as arguments.
7321 if (Context.getTargetInfo().getTriple().isWasm()) {
7322 for (const Expr *Arg : Args) {
7323 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7324 return ExprError(Diag(Arg->getExprLoc(),
7325 diag::err_wasm_table_as_function_parameter));
7326 }
7327 }
7328 }
7329
7330 // Check read_image{i|ui} sampler argument before ConvertArgumentsForCall
7331 // replaces sampler DeclRefExprs with their integer initializers.
7332 if (getLangOpts().OpenCL && FDecl) {
7333 OpenCL().checkBuiltinReadImage(FDecl, TheCall);
7334 }
7335
7336 if (Proto) {
7337 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7338 IsExecConfig))
7339 return ExprError();
7340 } else {
7341 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7342
7343 if (FDecl) {
7344 // Check if we have too few/too many template arguments, based
7345 // on our knowledge of the function definition.
7346 const FunctionDecl *Def = nullptr;
7347 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7348 Proto = Def->getType()->getAs<FunctionProtoType>();
7349 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7350 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7351 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7352 }
7353
7354 // If the function we're calling isn't a function prototype, but we have
7355 // a function prototype from a prior declaratiom, use that prototype.
7356 if (!FDecl->hasPrototype())
7357 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7358 }
7359
7360 // If we still haven't found a prototype to use but there are arguments to
7361 // the call, diagnose this as calling a function without a prototype.
7362 // However, if we found a function declaration, check to see if
7363 // -Wdeprecated-non-prototype was disabled where the function was declared.
7364 // If so, we will silence the diagnostic here on the assumption that this
7365 // interface is intentional and the user knows what they're doing. We will
7366 // also silence the diagnostic if there is a function declaration but it
7367 // was implicitly defined (the user already gets diagnostics about the
7368 // creation of the implicit function declaration, so the additional warning
7369 // is not helpful).
7370 if (!Proto && !Args.empty() &&
7371 (!FDecl || (!FDecl->isImplicit() &&
7372 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7373 FDecl->getLocation()))))
7374 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7375 << (FDecl != nullptr) << FDecl;
7376
7377 // Promote the arguments (C99 6.5.2.2p6).
7378 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7379 Expr *Arg = Args[i];
7380
7381 if (Proto && i < Proto->getNumParams()) {
7383 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7384 ExprResult ArgE =
7386 if (ArgE.isInvalid())
7387 return true;
7388
7389 Arg = ArgE.getAs<Expr>();
7390
7391 } else {
7393
7394 if (ArgE.isInvalid())
7395 return true;
7396
7397 Arg = ArgE.getAs<Expr>();
7398 }
7399
7400 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7401 diag::err_call_incomplete_argument, Arg))
7402 return ExprError();
7403
7404 TheCall->setArg(i, Arg);
7405 }
7406 TheCall->computeDependence();
7407 }
7408
7409 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7410 if (Method->isImplicitObjectMemberFunction())
7411 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7412 << Fn->getSourceRange() << 0);
7413
7414 // Check for sentinels
7415 if (NDecl)
7416 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7417
7418 // Warn for unions passing across security boundary (CMSE).
7419 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7420 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7421 if (const auto *RT =
7422 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7423 if (RT->getDecl()->isOrContainsUnion())
7424 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7425 << 0 << i;
7426 }
7427 }
7428 }
7429
7430 // Do special checking on direct calls to functions.
7431 if (FDecl) {
7432 if (CheckFunctionCall(FDecl, TheCall, Proto))
7433 return ExprError();
7434
7435 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7436 checkFortifiedLibcArgument(FDecl, TheCall);
7437
7438 if (BuiltinID)
7439 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7440 } else if (NDecl) {
7441 if (CheckPointerCall(NDecl, TheCall, Proto))
7442 return ExprError();
7443 } else {
7444 if (CheckOtherCall(TheCall, Proto))
7445 return ExprError();
7446 }
7447
7448 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7449}
7450
7453 SourceLocation RParenLoc, Expr *InitExpr) {
7454 assert(Ty && "ActOnCompoundLiteral(): missing type");
7455 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7456
7457 TypeSourceInfo *TInfo;
7458 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7459 if (!TInfo)
7460 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7461
7462 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7463}
7464
7467 SourceLocation RParenLoc, Expr *LiteralExpr) {
7468 QualType literalType = TInfo->getType();
7469
7470 if (literalType->isArrayType()) {
7472 LParenLoc, Context.getBaseElementType(literalType),
7473 diag::err_array_incomplete_or_sizeless_type,
7474 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7475 return ExprError();
7476 if (literalType->isVariableArrayType()) {
7477 // C23 6.7.10p4: An entity of variable length array type shall not be
7478 // initialized except by an empty initializer.
7479 //
7480 // The C extension warnings are issued from ParseBraceInitializer() and
7481 // do not need to be issued here. However, we continue to issue an error
7482 // in the case there are initializers or we are compiling C++. We allow
7483 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7484 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7485 // FIXME: should we allow this construct in C++ when it makes sense to do
7486 // so?
7487 //
7488 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7489 // shall specify an object type or an array of unknown size, but not a
7490 // variable length array type. This seems odd, as it allows 'int a[size] =
7491 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7492 // says, this is what's implemented here for C (except for the extension
7493 // that permits constant foldable size arrays)
7494
7495 auto diagID = LangOpts.CPlusPlus
7496 ? diag::err_variable_object_no_init
7497 : diag::err_compound_literal_with_vla_type;
7498 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7499 diagID))
7500 return ExprError();
7501 }
7502 } else if (!literalType->isDependentType() &&
7503 RequireCompleteType(LParenLoc, literalType,
7504 diag::err_typecheck_decl_incomplete_type,
7505 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7506 return ExprError();
7507
7508 InitializedEntity Entity
7512 SourceRange(LParenLoc, RParenLoc),
7513 /*InitList=*/true);
7514 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7515 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7516 &literalType);
7517 if (Result.isInvalid())
7518 return ExprError();
7519 LiteralExpr = Result.get();
7520
7521 // We treat the compound literal as being at file scope if it's not in a
7522 // function or method body, or within the function's prototype scope. This
7523 // means the following compound literal is not at file scope:
7524 // void func(char *para[(int [1]){ 0 }[0]);
7525 const Scope *S = getCurScope();
7526 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7527 !S->isInCFunctionScope() &&
7528 (!S || !S->isFunctionPrototypeScope());
7529
7530 // In C, compound literals are l-values for some reason.
7531 // For GCC compatibility, in C++, file-scope array compound literals with
7532 // constant initializers are also l-values, and compound literals are
7533 // otherwise prvalues.
7534 //
7535 // (GCC also treats C++ list-initialized file-scope array prvalues with
7536 // constant initializers as l-values, but that's non-conforming, so we don't
7537 // follow it there.)
7538 //
7539 // FIXME: It would be better to handle the lvalue cases as materializing and
7540 // lifetime-extending a temporary object, but our materialized temporaries
7541 // representation only supports lifetime extension from a variable, not "out
7542 // of thin air".
7543 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7544 // is bound to the result of applying array-to-pointer decay to the compound
7545 // literal.
7546 // FIXME: GCC supports compound literals of reference type, which should
7547 // obviously have a value kind derived from the kind of reference involved.
7549 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7550 ? VK_PRValue
7551 : VK_LValue;
7552
7553 // C99 6.5.2.5
7554 // "If the compound literal occurs outside the body of a function, the
7555 // initializer list shall consist of constant expressions."
7556 if (IsFileScope)
7557 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7558 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7559 Expr *Init = ILE->getInit(i);
7560 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7561 !Init->isConstantInitializer(Context)) {
7562 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7563 << Init->getSourceBitField();
7564 return ExprError();
7565 }
7566
7567 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7568 }
7569
7570 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7571 LiteralExpr, IsFileScope);
7572 if (IsFileScope) {
7573 if (!LiteralExpr->isTypeDependent() &&
7574 !LiteralExpr->isValueDependent() &&
7575 !literalType->isDependentType()) // C99 6.5.2.5p3
7576 if (CheckForConstantInitializer(LiteralExpr))
7577 return ExprError();
7578 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7579 literalType.getAddressSpace() != LangAS::Default) {
7580 // Embedded-C extensions to C99 6.5.2.5:
7581 // "If the compound literal occurs inside the body of a function, the
7582 // type name shall not be qualified by an address-space qualifier."
7583 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7584 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7585 return ExprError();
7586 }
7587
7588 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7589 // Compound literals that have automatic storage duration are destroyed at
7590 // the end of the scope in C; in C++, they're just temporaries.
7591
7592 // Emit diagnostics if it is or contains a C union type that is non-trivial
7593 // to destruct.
7598
7599 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7600 if (literalType.isDestructedType()) {
7601 Cleanup.setExprNeedsCleanups(true);
7602 ExprCleanupObjects.push_back(E);
7604 }
7605 }
7606
7609 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7610 E->getInitializer()->getExprLoc());
7611
7612 return MaybeBindToTemporary(E);
7613}
7614
7617 SourceLocation RBraceLoc) {
7618 // Only produce each kind of designated initialization diagnostic once.
7619 SourceLocation FirstDesignator;
7620 bool DiagnosedArrayDesignator = false;
7621 bool DiagnosedNestedDesignator = false;
7622 bool DiagnosedMixedDesignator = false;
7623
7624 // Check that any designated initializers are syntactically valid in the
7625 // current language mode.
7626 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7627 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7628 if (FirstDesignator.isInvalid())
7629 FirstDesignator = DIE->getBeginLoc();
7630
7631 if (!getLangOpts().CPlusPlus)
7632 break;
7633
7634 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7635 DiagnosedNestedDesignator = true;
7636 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7637 << DIE->getDesignatorsSourceRange();
7638 }
7639
7640 for (auto &Desig : DIE->designators()) {
7641 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7642 DiagnosedArrayDesignator = true;
7643 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7644 << Desig.getSourceRange();
7645 }
7646 }
7647
7648 if (!DiagnosedMixedDesignator &&
7649 !isa<DesignatedInitExpr>(InitArgList[0])) {
7650 DiagnosedMixedDesignator = true;
7651 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7652 << DIE->getSourceRange();
7653 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7654 << InitArgList[0]->getSourceRange();
7655 }
7656 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7657 isa<DesignatedInitExpr>(InitArgList[0])) {
7658 DiagnosedMixedDesignator = true;
7659 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7660 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7661 << DIE->getSourceRange();
7662 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7663 << InitArgList[I]->getSourceRange();
7664 }
7665 }
7666
7667 if (FirstDesignator.isValid()) {
7668 // Only diagnose designated initiaization as a C++20 extension if we didn't
7669 // already diagnose use of (non-C++20) C99 designator syntax.
7670 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7671 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7672 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7673 ? diag::warn_cxx17_compat_designated_init
7674 : diag::ext_cxx_designated_init);
7675 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7676 Diag(FirstDesignator, diag::ext_designated_init);
7677 }
7678 }
7679
7680 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc, /*IsExplicit=*/true);
7681}
7682
7684 MultiExprArg InitArgList,
7685 SourceLocation RBraceLoc, bool IsExplicit) {
7686 // Semantic analysis for initializers is done by ActOnDeclarator() and
7687 // CheckInitializer() - it requires knowledge of the object being initialized.
7688
7689 // Immediately handle non-overload placeholders. Overloads can be
7690 // resolved contextually, but everything else here can't.
7691 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7692 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7693 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7694
7695 // Ignore failures; dropping the entire initializer list because
7696 // of one failure would be terrible for indexing/etc.
7697 if (result.isInvalid()) continue;
7698
7699 InitArgList[I] = result.get();
7700 }
7701 }
7702
7703 InitListExpr *E = new (Context)
7704 InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc, IsExplicit);
7705 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7706 return E;
7707}
7708
7710 assert(E.get()->getType()->isBlockPointerType());
7711 assert(E.get()->isPRValue());
7712
7713 // Only do this in an r-value context.
7714 if (!getLangOpts().ObjCAutoRefCount) return;
7715
7717 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7718 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7719 Cleanup.setExprNeedsCleanups(true);
7720}
7721
7723 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7724 // Also, callers should have filtered out the invalid cases with
7725 // pointers. Everything else should be possible.
7726
7727 QualType SrcTy = Src.get()->getType();
7728 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7729 return CK_NoOp;
7730
7731 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7733 llvm_unreachable("member pointer type in C");
7734
7735 case Type::STK_CPointer:
7738 switch (DestTy->getScalarTypeKind()) {
7739 case Type::STK_CPointer: {
7740 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7741 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7742 if (SrcAS != DestAS)
7743 return CK_AddressSpaceConversion;
7744 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7745 return CK_NoOp;
7746 return CK_BitCast;
7747 }
7749 return (SrcKind == Type::STK_BlockPointer
7750 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7752 if (SrcKind == Type::STK_ObjCObjectPointer)
7753 return CK_BitCast;
7754 if (SrcKind == Type::STK_CPointer)
7755 return CK_CPointerToObjCPointerCast;
7757 return CK_BlockPointerToObjCPointerCast;
7758 case Type::STK_Bool:
7759 return CK_PointerToBoolean;
7760 case Type::STK_Integral:
7761 return CK_PointerToIntegral;
7762 case Type::STK_Floating:
7767 llvm_unreachable("illegal cast from pointer");
7768 }
7769 llvm_unreachable("Should have returned before this");
7770
7772 switch (DestTy->getScalarTypeKind()) {
7774 return CK_FixedPointCast;
7775 case Type::STK_Bool:
7776 return CK_FixedPointToBoolean;
7777 case Type::STK_Integral:
7778 return CK_FixedPointToIntegral;
7779 case Type::STK_Floating:
7780 return CK_FixedPointToFloating;
7783 Diag(Src.get()->getExprLoc(),
7784 diag::err_unimplemented_conversion_with_fixed_point_type)
7785 << DestTy;
7786 return CK_IntegralCast;
7787 case Type::STK_CPointer:
7791 llvm_unreachable("illegal cast to pointer type");
7792 }
7793 llvm_unreachable("Should have returned before this");
7794
7795 case Type::STK_Bool: // casting from bool is like casting from an integer
7796 case Type::STK_Integral:
7797 switch (DestTy->getScalarTypeKind()) {
7798 case Type::STK_CPointer:
7803 return CK_NullToPointer;
7804 return CK_IntegralToPointer;
7805 case Type::STK_Bool:
7806 return CK_IntegralToBoolean;
7807 case Type::STK_Integral:
7808 return CK_IntegralCast;
7809 case Type::STK_Floating:
7810 return CK_IntegralToFloating;
7812 Src = ImpCastExprToType(Src.get(),
7813 DestTy->castAs<ComplexType>()->getElementType(),
7814 CK_IntegralCast);
7815 return CK_IntegralRealToComplex;
7817 Src = ImpCastExprToType(Src.get(),
7818 DestTy->castAs<ComplexType>()->getElementType(),
7819 CK_IntegralToFloating);
7820 return CK_FloatingRealToComplex;
7822 llvm_unreachable("member pointer type in C");
7824 return CK_IntegralToFixedPoint;
7825 }
7826 llvm_unreachable("Should have returned before this");
7827
7828 case Type::STK_Floating:
7829 switch (DestTy->getScalarTypeKind()) {
7830 case Type::STK_Floating:
7831 return CK_FloatingCast;
7832 case Type::STK_Bool:
7833 return CK_FloatingToBoolean;
7834 case Type::STK_Integral:
7835 return CK_FloatingToIntegral;
7837 Src = ImpCastExprToType(Src.get(),
7838 DestTy->castAs<ComplexType>()->getElementType(),
7839 CK_FloatingCast);
7840 return CK_FloatingRealToComplex;
7842 Src = ImpCastExprToType(Src.get(),
7843 DestTy->castAs<ComplexType>()->getElementType(),
7844 CK_FloatingToIntegral);
7845 return CK_IntegralRealToComplex;
7846 case Type::STK_CPointer:
7849 llvm_unreachable("valid float->pointer cast?");
7851 llvm_unreachable("member pointer type in C");
7853 return CK_FloatingToFixedPoint;
7854 }
7855 llvm_unreachable("Should have returned before this");
7856
7858 switch (DestTy->getScalarTypeKind()) {
7860 return CK_FloatingComplexCast;
7862 return CK_FloatingComplexToIntegralComplex;
7863 case Type::STK_Floating: {
7864 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7865 if (Context.hasSameType(ET, DestTy))
7866 return CK_FloatingComplexToReal;
7867 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7868 return CK_FloatingCast;
7869 }
7870 case Type::STK_Bool:
7871 return CK_FloatingComplexToBoolean;
7872 case Type::STK_Integral:
7873 Src = ImpCastExprToType(Src.get(),
7874 SrcTy->castAs<ComplexType>()->getElementType(),
7875 CK_FloatingComplexToReal);
7876 return CK_FloatingToIntegral;
7877 case Type::STK_CPointer:
7880 llvm_unreachable("valid complex float->pointer cast?");
7882 llvm_unreachable("member pointer type in C");
7884 Diag(Src.get()->getExprLoc(),
7885 diag::err_unimplemented_conversion_with_fixed_point_type)
7886 << SrcTy;
7887 return CK_IntegralCast;
7888 }
7889 llvm_unreachable("Should have returned before this");
7890
7892 switch (DestTy->getScalarTypeKind()) {
7894 return CK_IntegralComplexToFloatingComplex;
7896 return CK_IntegralComplexCast;
7897 case Type::STK_Integral: {
7898 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7899 if (Context.hasSameType(ET, DestTy))
7900 return CK_IntegralComplexToReal;
7901 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7902 return CK_IntegralCast;
7903 }
7904 case Type::STK_Bool:
7905 return CK_IntegralComplexToBoolean;
7906 case Type::STK_Floating:
7907 Src = ImpCastExprToType(Src.get(),
7908 SrcTy->castAs<ComplexType>()->getElementType(),
7909 CK_IntegralComplexToReal);
7910 return CK_IntegralToFloating;
7911 case Type::STK_CPointer:
7914 llvm_unreachable("valid complex int->pointer cast?");
7916 llvm_unreachable("member pointer type in C");
7918 Diag(Src.get()->getExprLoc(),
7919 diag::err_unimplemented_conversion_with_fixed_point_type)
7920 << SrcTy;
7921 return CK_IntegralCast;
7922 }
7923 llvm_unreachable("Should have returned before this");
7924 }
7925
7926 llvm_unreachable("Unhandled scalar cast");
7927}
7928
7929static bool breakDownVectorType(QualType type, uint64_t &len,
7930 QualType &eltType) {
7931 // Vectors are simple.
7932 if (const VectorType *vecType = type->getAs<VectorType>()) {
7933 len = vecType->getNumElements();
7934 eltType = vecType->getElementType();
7935 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7936 return true;
7937 }
7938
7939 // We allow lax conversion to and from non-vector types, but only if
7940 // they're real types (i.e. non-complex, non-pointer scalar types).
7941 if (!type->isRealType()) return false;
7942
7943 len = 1;
7944 eltType = type;
7945 return true;
7946}
7947
7949 assert(srcTy->isVectorType() || destTy->isVectorType());
7950
7951 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7952 if (!FirstType->isSVESizelessBuiltinType())
7953 return false;
7954
7955 const auto *VecTy = SecondType->getAs<VectorType>();
7956 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7957 };
7958
7959 return ValidScalableConversion(srcTy, destTy) ||
7960 ValidScalableConversion(destTy, srcTy);
7961}
7962
7964 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7965 return false;
7966
7967 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7968 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7969
7970 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7971 matSrcType->getNumColumns() == matDestType->getNumColumns();
7972}
7973
7975 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7976
7977 uint64_t SrcLen, DestLen;
7978 QualType SrcEltTy, DestEltTy;
7979 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7980 return false;
7981 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7982 return false;
7983
7984 // ASTContext::getTypeSize will return the size rounded up to a
7985 // power of 2, so instead of using that, we need to use the raw
7986 // element size multiplied by the element count.
7987 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7988 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7989
7990 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7991}
7992
7994 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7995 "expected at least one type to be a vector here");
7996
7997 bool IsSrcTyAltivec =
7998 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
8000 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8002 (SrcTy->castAs<VectorType>()->getVectorKind() ==
8004
8005 bool IsDestTyAltivec = DestTy->isVectorType() &&
8006 ((DestTy->castAs<VectorType>()->getVectorKind() ==
8008 (DestTy->castAs<VectorType>()->getVectorKind() ==
8010 (DestTy->castAs<VectorType>()->getVectorKind() ==
8012
8013 return (IsSrcTyAltivec || IsDestTyAltivec);
8014}
8015
8017 assert(destTy->isVectorType() || srcTy->isVectorType());
8018
8019 // Disallow lax conversions between scalars and ExtVectors (these
8020 // conversions are allowed for other vector types because common headers
8021 // depend on them). Most scalar OP ExtVector cases are handled by the
8022 // splat path anyway, which does what we want (convert, not bitcast).
8023 // What this rules out for ExtVectors is crazy things like char4*float.
8024 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
8025 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
8026
8027 return areVectorTypesSameSize(srcTy, destTy);
8028}
8029
8031 assert(destTy->isVectorType() || srcTy->isVectorType());
8032
8033 switch (Context.getLangOpts().getLaxVectorConversions()) {
8035 return false;
8036
8038 if (!srcTy->isIntegralOrEnumerationType()) {
8039 auto *Vec = srcTy->getAs<VectorType>();
8040 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8041 return false;
8042 }
8043 if (!destTy->isIntegralOrEnumerationType()) {
8044 auto *Vec = destTy->getAs<VectorType>();
8045 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
8046 return false;
8047 }
8048 // OK, integer (vector) -> integer (vector) bitcast.
8049 break;
8050
8052 break;
8053 }
8054
8055 return areLaxCompatibleVectorTypes(srcTy, destTy);
8056}
8057
8059 CastKind &Kind) {
8060 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8061 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
8062 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
8063 << DestTy << SrcTy << R;
8064 }
8065 } else if (SrcTy->isMatrixType()) {
8066 return Diag(R.getBegin(),
8067 diag::err_invalid_conversion_between_matrix_and_type)
8068 << SrcTy << DestTy << R;
8069 } else if (DestTy->isMatrixType()) {
8070 return Diag(R.getBegin(),
8071 diag::err_invalid_conversion_between_matrix_and_type)
8072 << DestTy << SrcTy << R;
8073 }
8074
8075 Kind = CK_MatrixCast;
8076 return false;
8077}
8078
8080 CastKind &Kind) {
8081 assert(VectorTy->isVectorType() && "Not a vector type!");
8082
8083 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
8084 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8085 return Diag(R.getBegin(),
8086 Ty->isVectorType() ?
8087 diag::err_invalid_conversion_between_vectors :
8088 diag::err_invalid_conversion_between_vector_and_integer)
8089 << VectorTy << Ty << R;
8090 } else
8091 return Diag(R.getBegin(),
8092 diag::err_invalid_conversion_between_vector_and_scalar)
8093 << VectorTy << Ty << R;
8094
8095 Kind = CK_BitCast;
8096 return false;
8097}
8098
8100 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8101
8102 if (DestElemTy == SplattedExpr->getType())
8103 return SplattedExpr;
8104
8105 assert(DestElemTy->isFloatingType() ||
8106 DestElemTy->isIntegralOrEnumerationType());
8107
8108 CastKind CK;
8109 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8110 // OpenCL requires that we convert `true` boolean expressions to -1, but
8111 // only when splatting vectors.
8112 if (DestElemTy->isFloatingType()) {
8113 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8114 // in two steps: boolean to signed integral, then to floating.
8115 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
8116 CK_BooleanToSignedIntegral);
8117 SplattedExpr = CastExprRes.get();
8118 CK = CK_IntegralToFloating;
8119 } else {
8120 CK = CK_BooleanToSignedIntegral;
8121 }
8122 } else {
8123 ExprResult CastExprRes = SplattedExpr;
8124 CK = PrepareScalarCast(CastExprRes, DestElemTy);
8125 if (CastExprRes.isInvalid())
8126 return ExprError();
8127 SplattedExpr = CastExprRes.get();
8128 }
8129 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8130}
8131
8133 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8134
8135 if (DestElemTy == SplattedExpr->getType())
8136 return SplattedExpr;
8137
8138 assert(DestElemTy->isFloatingType() ||
8139 DestElemTy->isIntegralOrEnumerationType());
8140
8141 ExprResult CastExprRes = SplattedExpr;
8142 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
8143 if (CastExprRes.isInvalid())
8144 return ExprError();
8145 SplattedExpr = CastExprRes.get();
8146
8147 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8148}
8149
8151 Expr *CastExpr, CastKind &Kind) {
8152 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8153
8154 QualType SrcTy = CastExpr->getType();
8155
8156 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8157 // an ExtVectorType.
8158 // In OpenCL, casts between vectors of different types are not allowed.
8159 // (See OpenCL 6.2).
8160 if (SrcTy->isVectorType()) {
8161 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8162 (getLangOpts().OpenCL &&
8163 !Context.hasSameUnqualifiedType(DestTy, SrcTy) &&
8164 !Context.areCompatibleVectorTypes(DestTy, SrcTy))) {
8165 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8166 << DestTy << SrcTy << R;
8167 return ExprError();
8168 }
8169 Kind = CK_BitCast;
8170 return CastExpr;
8171 }
8172
8173 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8174 // conversion will take place first from scalar to elt type, and then
8175 // splat from elt type to vector.
8176 if (SrcTy->isPointerType())
8177 return Diag(R.getBegin(),
8178 diag::err_invalid_conversion_between_vector_and_scalar)
8179 << DestTy << SrcTy << R;
8180
8181 Kind = CK_VectorSplat;
8182 return prepareVectorSplat(DestTy, CastExpr);
8183}
8184
8185/// Check that a call to alloc_size function specifies sufficient space for the
8186/// destination type.
8187static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8188 const Expr *E) {
8189 QualType SourceType = E->getType();
8190 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8191 DestType == SourceType)
8192 return;
8193
8194 const auto *CE = dyn_cast<CallExpr>(E->IgnoreParenCasts());
8195 if (!CE)
8196 return;
8197
8198 // Find the total size allocated by the function call.
8199 if (!CE->getCalleeAllocSizeAttr())
8200 return;
8201 std::optional<llvm::APInt> AllocSize =
8202 CE->evaluateBytesReturnedByAllocSizeCall(S.Context);
8203 // Allocations of size zero are permitted as a special case. They are usually
8204 // done intentionally.
8205 if (!AllocSize || AllocSize->isZero())
8206 return;
8207 auto Size = CharUnits::fromQuantity(AllocSize->getZExtValue());
8208
8209 QualType TargetType = DestType->getPointeeType();
8210 // Find the destination size. As a special case function types have size of
8211 // one byte to match the sizeof operator behavior.
8212 auto LhsSize = TargetType->isFunctionType()
8213 ? CharUnits::One()
8214 : S.Context.getTypeSizeInCharsIfKnown(TargetType);
8215 if (LhsSize && Size < LhsSize)
8216 S.Diag(E->getExprLoc(), diag::warn_alloc_size)
8217 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8218}
8219
8222 Declarator &D, ParsedType &Ty,
8223 SourceLocation RParenLoc, Expr *CastExpr) {
8224 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8225 "ActOnCastExpr(): missing type or expr");
8226
8228 if (D.isInvalidType())
8229 return ExprError();
8230
8231 if (getLangOpts().CPlusPlus) {
8232 // Check that there are no default arguments (C++ only).
8234 }
8235
8237
8238 QualType castType = castTInfo->getType();
8239 Ty = CreateParsedType(castType, castTInfo);
8240
8241 bool isVectorLiteral = false;
8242
8243 // Check for an altivec or OpenCL literal,
8244 // i.e. all the elements are integer constants.
8245 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8246 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8247 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8248 && castType->isVectorType() && (PE || PLE)) {
8249 if (PLE && PLE->getNumExprs() == 0) {
8250 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8251 return ExprError();
8252 }
8253 if (PE || PLE->getNumExprs() == 1) {
8254 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8255 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8256 isVectorLiteral = true;
8257 }
8258 else
8259 isVectorLiteral = true;
8260 }
8261
8262 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8263 // then handle it as such.
8264 if (isVectorLiteral)
8265 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8266
8267 // If the Expr being casted is a ParenListExpr, handle it specially.
8268 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8269 // sequence of BinOp comma operators.
8272 if (Result.isInvalid()) return ExprError();
8273 CastExpr = Result.get();
8274 }
8275
8276 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8277 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8278
8280
8282
8284
8285 CheckSufficientAllocSize(*this, castType, CastExpr);
8286
8287 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8288}
8289
8291 SourceLocation RParenLoc, Expr *E,
8292 TypeSourceInfo *TInfo) {
8293 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8294 "Expected paren or paren list expression");
8295
8296 Expr **exprs;
8297 unsigned numExprs;
8298 Expr *subExpr;
8299 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8300 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8301 LiteralLParenLoc = PE->getLParenLoc();
8302 LiteralRParenLoc = PE->getRParenLoc();
8303 exprs = PE->getExprs();
8304 numExprs = PE->getNumExprs();
8305 } else { // isa<ParenExpr> by assertion at function entrance
8306 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8307 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8308 subExpr = cast<ParenExpr>(E)->getSubExpr();
8309 exprs = &subExpr;
8310 numExprs = 1;
8311 }
8312
8313 QualType Ty = TInfo->getType();
8314 assert(Ty->isVectorType() && "Expected vector type");
8315
8316 SmallVector<Expr *, 8> initExprs;
8317 const VectorType *VTy = Ty->castAs<VectorType>();
8318 unsigned numElems = VTy->getNumElements();
8319
8320 // '(...)' form of vector initialization in AltiVec: the number of
8321 // initializers must be one or must match the size of the vector.
8322 // If a single value is specified in the initializer then it will be
8323 // replicated to all the components of the vector
8325 VTy->getElementType()))
8326 return ExprError();
8328 // The number of initializers must be one or must match the size of the
8329 // vector. If a single value is specified in the initializer then it will
8330 // be replicated to all the components of the vector
8331 if (numExprs == 1) {
8332 QualType ElemTy = VTy->getElementType();
8333 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8334 if (Literal.isInvalid())
8335 return ExprError();
8336 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8337 PrepareScalarCast(Literal, ElemTy));
8338 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8339 }
8340 else if (numExprs < numElems) {
8341 Diag(E->getExprLoc(),
8342 diag::err_incorrect_number_of_vector_initializers);
8343 return ExprError();
8344 }
8345 else
8346 initExprs.append(exprs, exprs + numExprs);
8347 }
8348 else {
8349 // For OpenCL, when the number of initializers is a single value,
8350 // it will be replicated to all components of the vector.
8352 numExprs == 1) {
8353 QualType SrcTy = exprs[0]->getType();
8354 if (!SrcTy->isArithmeticType()) {
8355 Diag(exprs[0]->getBeginLoc(), diag::err_typecheck_convert_incompatible)
8356 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8357 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8358 return ExprError();
8359 }
8360 QualType ElemTy = VTy->getElementType();
8361 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8362 if (Literal.isInvalid())
8363 return ExprError();
8364 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8365 PrepareScalarCast(Literal, ElemTy));
8366 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8367 }
8368
8369 initExprs.append(exprs, exprs + numExprs);
8370 }
8371 // FIXME: This means that pretty-printing the final AST will produce curly
8372 // braces instead of the original commas.
8373 InitListExpr *initE =
8374 new (Context) InitListExpr(Context, LiteralLParenLoc, initExprs,
8375 LiteralRParenLoc, /*isExplicit=*/false);
8376 initE->setType(Ty);
8377 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8378}
8379
8382 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8383 if (!E)
8384 return OrigExpr;
8385
8386 ExprResult Result(E->getExpr(0));
8387
8388 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8389 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8390 E->getExpr(i));
8391
8392 if (Result.isInvalid()) return ExprError();
8393
8394 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8395}
8396
8402
8404 unsigned NumUserSpecifiedExprs,
8405 SourceLocation InitLoc,
8406 SourceLocation LParenLoc,
8407 SourceLocation RParenLoc) {
8408 return CXXParenListInitExpr::Create(Context, Args, T, NumUserSpecifiedExprs,
8409 InitLoc, LParenLoc, RParenLoc);
8410}
8411
8412bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8413 SourceLocation QuestionLoc) {
8414 const Expr *NullExpr = LHSExpr;
8415 const Expr *NonPointerExpr = RHSExpr;
8419
8420 if (NullKind == Expr::NPCK_NotNull) {
8421 NullExpr = RHSExpr;
8422 NonPointerExpr = LHSExpr;
8423 NullKind =
8426 }
8427
8428 if (NullKind == Expr::NPCK_NotNull)
8429 return false;
8430
8431 if (NullKind == Expr::NPCK_ZeroExpression)
8432 return false;
8433
8434 if (NullKind == Expr::NPCK_ZeroLiteral) {
8435 // In this case, check to make sure that we got here from a "NULL"
8436 // string in the source code.
8437 NullExpr = NullExpr->IgnoreParenImpCasts();
8438 SourceLocation loc = NullExpr->getExprLoc();
8439 if (!findMacroSpelling(loc, "NULL"))
8440 return false;
8441 }
8442
8443 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8444 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8445 << NonPointerExpr->getType() << DiagType
8446 << NonPointerExpr->getSourceRange();
8447 return true;
8448}
8449
8450/// Return false if the condition expression is valid, true otherwise.
8451static bool checkCondition(Sema &S, const Expr *Cond,
8452 SourceLocation QuestionLoc) {
8453 QualType CondTy = Cond->getType();
8454
8455 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8456 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8457 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8458 << CondTy << Cond->getSourceRange();
8459 return true;
8460 }
8461
8462 // C99 6.5.15p2
8463 if (CondTy->isScalarType()) return false;
8464
8465 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8466 << CondTy << Cond->getSourceRange();
8467 return true;
8468}
8469
8470/// Return false if the NullExpr can be promoted to PointerTy,
8471/// true otherwise.
8473 QualType PointerTy) {
8474 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8475 !NullExpr.get()->isNullPointerConstant(S.Context,
8477 return true;
8478
8479 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8480 return false;
8481}
8482
8483/// Checks compatibility between two pointers and return the resulting
8484/// type.
8486 ExprResult &RHS,
8487 SourceLocation Loc) {
8488 QualType LHSTy = LHS.get()->getType();
8489 QualType RHSTy = RHS.get()->getType();
8490
8491 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8492 // Two identical pointers types are always compatible.
8493 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8494 }
8495
8496 QualType lhptee, rhptee;
8497
8498 // Get the pointee types.
8499 bool IsBlockPointer = false;
8500 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8501 lhptee = LHSBTy->getPointeeType();
8502 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8503 IsBlockPointer = true;
8504 } else {
8505 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8506 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8507 }
8508
8509 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8510 // differently qualified versions of compatible types, the result type is
8511 // a pointer to an appropriately qualified version of the composite
8512 // type.
8513
8514 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8515 // clause doesn't make sense for our extensions. E.g. address space 2 should
8516 // be incompatible with address space 3: they may live on different devices or
8517 // anything.
8518 Qualifiers lhQual = lhptee.getQualifiers();
8519 Qualifiers rhQual = rhptee.getQualifiers();
8520
8521 LangAS ResultAddrSpace = LangAS::Default;
8522 LangAS LAddrSpace = lhQual.getAddressSpace();
8523 LangAS RAddrSpace = rhQual.getAddressSpace();
8524
8525 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8526 // spaces is disallowed.
8527 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8528 ResultAddrSpace = LAddrSpace;
8529 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8530 ResultAddrSpace = RAddrSpace;
8531 else {
8532 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8533 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8534 << RHS.get()->getSourceRange();
8535 return QualType();
8536 }
8537
8538 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8539 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8540 lhQual.removeCVRQualifiers();
8541 rhQual.removeCVRQualifiers();
8542
8543 if (!lhQual.getPointerAuth().isEquivalent(rhQual.getPointerAuth())) {
8544 S.Diag(Loc, diag::err_typecheck_cond_incompatible_ptrauth)
8545 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8546 << RHS.get()->getSourceRange();
8547 return QualType();
8548 }
8549
8550 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8551 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8552 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8553 // qual types are compatible iff
8554 // * corresponded types are compatible
8555 // * CVR qualifiers are equal
8556 // * address spaces are equal
8557 // Thus for conditional operator we merge CVR and address space unqualified
8558 // pointees and if there is a composite type we return a pointer to it with
8559 // merged qualifiers.
8560 LHSCastKind =
8561 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8562 RHSCastKind =
8563 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8564 lhQual.removeAddressSpace();
8565 rhQual.removeAddressSpace();
8566
8567 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8568 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8569
8570 QualType CompositeTy = S.Context.mergeTypes(
8571 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8572 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8573
8574 if (CompositeTy.isNull()) {
8575 // In this situation, we assume void* type. No especially good
8576 // reason, but this is what gcc does, and we do have to pick
8577 // to get a consistent AST.
8578 QualType incompatTy;
8579 incompatTy = S.Context.getPointerType(
8580 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8581 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8582 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8583
8584 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8585 // for casts between types with incompatible address space qualifiers.
8586 // For the following code the compiler produces casts between global and
8587 // local address spaces of the corresponded innermost pointees:
8588 // local int *global *a;
8589 // global int *global *b;
8590 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8591 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8592 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8593 << RHS.get()->getSourceRange();
8594
8595 return incompatTy;
8596 }
8597
8598 // The pointer types are compatible.
8599 // In case of OpenCL ResultTy should have the address space qualifier
8600 // which is a superset of address spaces of both the 2nd and the 3rd
8601 // operands of the conditional operator.
8602 QualType ResultTy = [&, ResultAddrSpace]() {
8603 if (S.getLangOpts().OpenCL) {
8604 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8605 CompositeQuals.setAddressSpace(ResultAddrSpace);
8606 return S.Context
8607 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8608 .withCVRQualifiers(MergedCVRQual);
8609 }
8610 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8611 }();
8612 if (IsBlockPointer)
8613 ResultTy = S.Context.getBlockPointerType(ResultTy);
8614 else
8615 ResultTy = S.Context.getPointerType(ResultTy);
8616
8617 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8618 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8619 return ResultTy;
8620}
8621
8622/// Return the resulting type when the operands are both block pointers.
8624 ExprResult &LHS,
8625 ExprResult &RHS,
8626 SourceLocation Loc) {
8627 QualType LHSTy = LHS.get()->getType();
8628 QualType RHSTy = RHS.get()->getType();
8629
8630 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8631 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8633 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8634 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8635 return destType;
8636 }
8637 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8638 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8639 << RHS.get()->getSourceRange();
8640 return QualType();
8641 }
8642
8643 // We have 2 block pointer types.
8644 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8645}
8646
8647/// Return the resulting type when the operands are both pointers.
8648static QualType
8650 ExprResult &RHS,
8651 SourceLocation Loc) {
8652 // get the pointer types
8653 QualType LHSTy = LHS.get()->getType();
8654 QualType RHSTy = RHS.get()->getType();
8655
8656 // get the "pointed to" types
8657 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8658 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8659
8660 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8661 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8662 // Figure out necessary qualifiers (C99 6.5.15p6)
8663 QualType destPointee
8664 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8665 QualType destType = S.Context.getPointerType(destPointee);
8666 // Add qualifiers if necessary.
8667 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8668 // Promote to void*.
8669 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8670 return destType;
8671 }
8672 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8673 QualType destPointee
8674 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8675 QualType destType = S.Context.getPointerType(destPointee);
8676 // Add qualifiers if necessary.
8677 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8678 // Promote to void*.
8679 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8680 return destType;
8681 }
8682
8683 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8684}
8685
8686/// Return false if the first expression is not an integer and the second
8687/// expression is not a pointer, true otherwise.
8689 Expr* PointerExpr, SourceLocation Loc,
8690 bool IsIntFirstExpr) {
8691 if (!PointerExpr->getType()->isPointerType() ||
8692 !Int.get()->getType()->isIntegerType())
8693 return false;
8694
8695 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8696 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8697
8698 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8699 << Expr1->getType() << Expr2->getType()
8700 << Expr1->getSourceRange() << Expr2->getSourceRange();
8701 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8702 CK_IntegralToPointer);
8703 return true;
8704}
8705
8706/// Simple conversion between integer and floating point types.
8707///
8708/// Used when handling the OpenCL conditional operator where the
8709/// condition is a vector while the other operands are scalar.
8710///
8711/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8712/// types are either integer or floating type. Between the two
8713/// operands, the type with the higher rank is defined as the "result
8714/// type". The other operand needs to be promoted to the same type. No
8715/// other type promotion is allowed. We cannot use
8716/// UsualArithmeticConversions() for this purpose, since it always
8717/// promotes promotable types.
8719 ExprResult &RHS,
8720 SourceLocation QuestionLoc) {
8722 if (LHS.isInvalid())
8723 return QualType();
8725 if (RHS.isInvalid())
8726 return QualType();
8727
8728 // For conversion purposes, we ignore any qualifiers.
8729 // For example, "const float" and "float" are equivalent.
8730 QualType LHSType =
8732 QualType RHSType =
8734
8735 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8736 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8737 << LHSType << LHS.get()->getSourceRange();
8738 return QualType();
8739 }
8740
8741 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8742 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8743 << RHSType << RHS.get()->getSourceRange();
8744 return QualType();
8745 }
8746
8747 // If both types are identical, no conversion is needed.
8748 if (LHSType == RHSType)
8749 return LHSType;
8750
8751 // Now handle "real" floating types (i.e. float, double, long double).
8752 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8753 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8754 /*IsCompAssign = */ false);
8755
8756 // Finally, we have two differing integer types.
8758 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8759}
8760
8761/// Convert scalar operands to a vector that matches the
8762/// condition in length.
8763///
8764/// Used when handling the OpenCL conditional operator where the
8765/// condition is a vector while the other operands are scalar.
8766///
8767/// We first compute the "result type" for the scalar operands
8768/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8769/// into a vector of that type where the length matches the condition
8770/// vector type. s6.11.6 requires that the element types of the result
8771/// and the condition must have the same number of bits.
8772static QualType
8774 QualType CondTy, SourceLocation QuestionLoc) {
8775 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8776 if (ResTy.isNull()) return QualType();
8777
8778 const VectorType *CV = CondTy->getAs<VectorType>();
8779 assert(CV);
8780
8781 // Determine the vector result type
8782 unsigned NumElements = CV->getNumElements();
8783 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8784
8785 // Ensure that all types have the same number of bits
8787 != S.Context.getTypeSize(ResTy)) {
8788 // Since VectorTy is created internally, it does not pretty print
8789 // with an OpenCL name. Instead, we just print a description.
8790 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8791 SmallString<64> Str;
8792 llvm::raw_svector_ostream OS(Str);
8793 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8794 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8795 << CondTy << OS.str();
8796 return QualType();
8797 }
8798
8799 // Convert operands to the vector result type
8800 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8801 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8802
8803 return VectorTy;
8804}
8805
8806/// Return false if this is a valid OpenCL condition vector
8808 SourceLocation QuestionLoc) {
8809 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8810 // integral type.
8811 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8812 assert(CondTy);
8813 QualType EleTy = CondTy->getElementType();
8814 if (EleTy->isIntegerType()) return false;
8815
8816 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8817 << Cond->getType() << Cond->getSourceRange();
8818 return true;
8819}
8820
8821/// Return false if the vector condition type and the vector
8822/// result type are compatible.
8823///
8824/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8825/// number of elements, and their element types have the same number
8826/// of bits.
8827static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8828 SourceLocation QuestionLoc) {
8829 const VectorType *CV = CondTy->getAs<VectorType>();
8830 const VectorType *RV = VecResTy->getAs<VectorType>();
8831 assert(CV && RV);
8832
8833 if (CV->getNumElements() != RV->getNumElements()) {
8834 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8835 << CondTy << VecResTy;
8836 return true;
8837 }
8838
8839 QualType CVE = CV->getElementType();
8840 QualType RVE = RV->getElementType();
8841
8842 // Boolean vectors are permitted outside of OpenCL mode.
8843 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE) &&
8844 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8845 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8846 << CondTy << VecResTy;
8847 return true;
8848 }
8849
8850 return false;
8851}
8852
8853/// Return the resulting type for the conditional operator in
8854/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8855/// s6.3.i) when the condition is a vector type.
8856static QualType
8858 ExprResult &LHS, ExprResult &RHS,
8859 SourceLocation QuestionLoc) {
8861 if (Cond.isInvalid())
8862 return QualType();
8863 QualType CondTy = Cond.get()->getType();
8864
8865 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8866 return QualType();
8867
8868 // If either operand is a vector then find the vector type of the
8869 // result as specified in OpenCL v1.1 s6.3.i.
8870 if (LHS.get()->getType()->isVectorType() ||
8871 RHS.get()->getType()->isVectorType()) {
8872 bool IsBoolVecLang =
8873 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8874 QualType VecResTy =
8875 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8876 /*isCompAssign*/ false,
8877 /*AllowBothBool*/ true,
8878 /*AllowBoolConversions*/ false,
8879 /*AllowBooleanOperation*/ IsBoolVecLang,
8880 /*ReportInvalid*/ true);
8881 if (VecResTy.isNull())
8882 return QualType();
8883 // The result type must match the condition type as specified in
8884 // OpenCL v1.1 s6.11.6.
8885 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8886 return QualType();
8887 return VecResTy;
8888 }
8889
8890 // Both operands are scalar.
8891 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8892}
8893
8894/// Return true if the Expr is block type
8895static bool checkBlockType(Sema &S, const Expr *E) {
8896 if (E->getType()->isBlockPointerType()) {
8897 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8898 return true;
8899 }
8900
8901 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8902 QualType Ty = CE->getCallee()->getType();
8903 if (Ty->isBlockPointerType()) {
8904 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8905 return true;
8906 }
8907 }
8908 return false;
8909}
8910
8911/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8912/// In that case, LHS = cond.
8913/// C99 6.5.15
8916 ExprObjectKind &OK,
8917 SourceLocation QuestionLoc) {
8918
8919 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8920 if (!LHSResult.isUsable()) return QualType();
8921 LHS = LHSResult;
8922
8923 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8924 if (!RHSResult.isUsable()) return QualType();
8925 RHS = RHSResult;
8926
8927 // C++ is sufficiently different to merit its own checker.
8928 if (getLangOpts().CPlusPlus)
8929 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8930
8931 VK = VK_PRValue;
8932 OK = OK_Ordinary;
8933
8934 if (Context.isDependenceAllowed() &&
8935 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8936 RHS.get()->isTypeDependent())) {
8937 assert(!getLangOpts().CPlusPlus);
8938 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8939 RHS.get()->containsErrors()) &&
8940 "should only occur in error-recovery path.");
8941 return Context.DependentTy;
8942 }
8943
8944 // The OpenCL operator with a vector condition is sufficiently
8945 // different to merit its own checker.
8946 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8947 Cond.get()->getType()->isExtVectorType())
8948 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8949
8950 // First, check the condition.
8952 if (Cond.isInvalid())
8953 return QualType();
8954 if (checkCondition(*this, Cond.get(), QuestionLoc))
8955 return QualType();
8956
8957 // Handle vectors.
8958 if (LHS.get()->getType()->isVectorType() ||
8959 RHS.get()->getType()->isVectorType())
8960 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8961 /*AllowBothBool*/ true,
8962 /*AllowBoolConversions*/ false,
8963 /*AllowBooleanOperation*/ false,
8964 /*ReportInvalid*/ true);
8965
8966 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
8968 if (LHS.isInvalid() || RHS.isInvalid())
8969 return QualType();
8970
8971 // WebAssembly tables are not allowed as conditional LHS or RHS.
8972 QualType LHSTy = LHS.get()->getType();
8973 QualType RHSTy = RHS.get()->getType();
8974 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8975 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8976 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8977 return QualType();
8978 }
8979
8980 // Diagnose attempts to convert between __ibm128, __float128 and long double
8981 // where such conversions currently can't be handled.
8982 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8983 Diag(QuestionLoc,
8984 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8985 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8986 return QualType();
8987 }
8988
8989 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8990 // selection operator (?:).
8991 if (getLangOpts().OpenCL &&
8992 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8993 return QualType();
8994 }
8995
8996 // If both operands have arithmetic type, do the usual arithmetic conversions
8997 // to find a common type: C99 6.5.15p3,5.
8998 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8999 // Disallow invalid arithmetic conversions, such as those between bit-
9000 // precise integers types of different sizes, or between a bit-precise
9001 // integer and another type.
9002 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
9003 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9004 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9005 << RHS.get()->getSourceRange();
9006 return QualType();
9007 }
9008
9009 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
9010 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
9011
9012 return ResTy;
9013 }
9014
9015 // If both operands are the same structure or union type, the result is that
9016 // type.
9017 // FIXME: Type of conditional expression must be complete in C mode.
9018 if (LHSTy->isRecordType() &&
9019 Context.hasSameUnqualifiedType(LHSTy, RHSTy)) // C99 6.5.15p3
9020 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
9021 RHSTy.getUnqualifiedType());
9022
9023 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9024 // The following || allows only one side to be void (a GCC-ism).
9025 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
9026 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
9027 // UsualArithmeticConversions already handled the case where both sides
9028 // are the same type.
9029 } else if (RHSTy->isVoidType()) {
9030 ResTy = RHSTy;
9031 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9032 << RHS.get()->getSourceRange();
9033 } else {
9034 ResTy = LHSTy;
9035 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
9036 << LHS.get()->getSourceRange();
9037 }
9038 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
9039 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
9040 return ResTy;
9041 }
9042
9043 // C23 6.5.15p7:
9044 // ... if both the second and third operands have nullptr_t type, the
9045 // result also has that type.
9046 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
9047 return ResTy;
9048
9049 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9050 // the type of the other operand."
9051 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
9052 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
9053
9054 // All objective-c pointer type analysis is done here.
9055 QualType compositeType =
9056 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
9057 if (LHS.isInvalid() || RHS.isInvalid())
9058 return QualType();
9059 if (!compositeType.isNull())
9060 return compositeType;
9061
9062
9063 // Handle block pointer types.
9064 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9065 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
9066 QuestionLoc);
9067
9068 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9069 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9070 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
9071 QuestionLoc);
9072
9073 // GCC compatibility: soften pointer/integer mismatch. Note that
9074 // null pointers have been filtered out by this point.
9075 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
9076 /*IsIntFirstExpr=*/true))
9077 return RHSTy;
9078 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
9079 /*IsIntFirstExpr=*/false))
9080 return LHSTy;
9081
9082 // Emit a better diagnostic if one of the expressions is a null pointer
9083 // constant and the other is not a pointer type. In this case, the user most
9084 // likely forgot to take the address of the other expression.
9085 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
9086 return QualType();
9087
9088 // Finally, if the LHS and RHS types are canonically the same type, we can
9089 // use the common sugared type.
9090 if (Context.hasSameType(LHSTy, RHSTy))
9091 return Context.getCommonSugaredType(LHSTy, RHSTy);
9092
9093 // Otherwise, the operands are not compatible.
9094 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9095 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9096 << RHS.get()->getSourceRange();
9097 return QualType();
9098}
9099
9100/// SuggestParentheses - Emit a note with a fixit hint that wraps
9101/// ParenRange in parentheses.
9103 const PartialDiagnostic &Note,
9104 SourceRange ParenRange) {
9105 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
9106 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9107 EndLoc.isValid()) {
9108 Self.Diag(Loc, Note)
9109 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
9110 << FixItHint::CreateInsertion(EndLoc, ")");
9111 } else {
9112 // We can't display the parentheses, so just show the bare note.
9113 Self.Diag(Loc, Note) << ParenRange;
9114 }
9115}
9116
9118 return BinaryOperator::isAdditiveOp(Opc) ||
9120 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9121 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9122 // not any of the logical operators. Bitwise-xor is commonly used as a
9123 // logical-xor because there is no logical-xor operator. The logical
9124 // operators, including uses of xor, have a high false positive rate for
9125 // precedence warnings.
9126}
9127
9128/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9129/// expression, either using a built-in or overloaded operator,
9130/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9131/// expression.
9132static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9133 const Expr **RHSExprs) {
9134 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9135 E = E->IgnoreImpCasts();
9137 E = E->IgnoreImpCasts();
9138 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9139 E = MTE->getSubExpr();
9140 E = E->IgnoreImpCasts();
9141 }
9142
9143 // Built-in binary operator.
9144 if (const auto *OP = dyn_cast<BinaryOperator>(E);
9145 OP && IsArithmeticOp(OP->getOpcode())) {
9146 *Opcode = OP->getOpcode();
9147 *RHSExprs = OP->getRHS();
9148 return true;
9149 }
9150
9151 // Overloaded operator.
9152 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9153 if (Call->getNumArgs() != 2)
9154 return false;
9155
9156 // Make sure this is really a binary operator that is safe to pass into
9157 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9158 OverloadedOperatorKind OO = Call->getOperator();
9159 if (OO < OO_Plus || OO > OO_Arrow ||
9160 OO == OO_PlusPlus || OO == OO_MinusMinus)
9161 return false;
9162
9164 if (IsArithmeticOp(OpKind)) {
9165 *Opcode = OpKind;
9166 *RHSExprs = Call->getArg(1);
9167 return true;
9168 }
9169 }
9170
9171 return false;
9172}
9173
9174/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9175/// or is a logical expression such as (x==y) which has int type, but is
9176/// commonly interpreted as boolean.
9177static bool ExprLooksBoolean(const Expr *E) {
9178 E = E->IgnoreParenImpCasts();
9179
9180 if (E->getType()->isBooleanType())
9181 return true;
9182 if (const auto *OP = dyn_cast<BinaryOperator>(E))
9183 return OP->isComparisonOp() || OP->isLogicalOp();
9184 if (const auto *OP = dyn_cast<UnaryOperator>(E))
9185 return OP->getOpcode() == UO_LNot;
9186 if (E->getType()->isPointerType())
9187 return true;
9188 // FIXME: What about overloaded operator calls returning "unspecified boolean
9189 // type"s (commonly pointer-to-members)?
9190
9191 return false;
9192}
9193
9194/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9195/// and binary operator are mixed in a way that suggests the programmer assumed
9196/// the conditional operator has higher precedence, for example:
9197/// "int x = a + someBinaryCondition ? 1 : 2".
9199 Expr *Condition, const Expr *LHSExpr,
9200 const Expr *RHSExpr) {
9201 BinaryOperatorKind CondOpcode;
9202 const Expr *CondRHS;
9203
9204 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9205 return;
9206 if (!ExprLooksBoolean(CondRHS))
9207 return;
9208
9209 // The condition is an arithmetic binary expression, with a right-
9210 // hand side that looks boolean, so warn.
9211
9212 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9213 ? diag::warn_precedence_bitwise_conditional
9214 : diag::warn_precedence_conditional;
9215
9216 Self.Diag(OpLoc, DiagID)
9217 << Condition->getSourceRange()
9218 << BinaryOperator::getOpcodeStr(CondOpcode);
9219
9221 Self, OpLoc,
9222 Self.PDiag(diag::note_precedence_silence)
9223 << BinaryOperator::getOpcodeStr(CondOpcode),
9224 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9225
9226 SuggestParentheses(Self, OpLoc,
9227 Self.PDiag(diag::note_precedence_conditional_first),
9228 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9229}
9230
9231/// Compute the nullability of a conditional expression.
9233 QualType LHSTy, QualType RHSTy,
9234 ASTContext &Ctx) {
9235 if (!ResTy->isAnyPointerType())
9236 return ResTy;
9237
9238 auto GetNullability = [](QualType Ty) {
9239 NullabilityKindOrNone Kind = Ty->getNullability();
9240 if (Kind) {
9241 // For our purposes, treat _Nullable_result as _Nullable.
9244 return *Kind;
9245 }
9247 };
9248
9249 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9250 NullabilityKind MergedKind;
9251
9252 // Compute nullability of a binary conditional expression.
9253 if (IsBin) {
9254 if (LHSKind == NullabilityKind::NonNull)
9255 MergedKind = NullabilityKind::NonNull;
9256 else
9257 MergedKind = RHSKind;
9258 // Compute nullability of a normal conditional expression.
9259 } else {
9260 if (LHSKind == NullabilityKind::Nullable ||
9261 RHSKind == NullabilityKind::Nullable)
9262 MergedKind = NullabilityKind::Nullable;
9263 else if (LHSKind == NullabilityKind::NonNull)
9264 MergedKind = RHSKind;
9265 else if (RHSKind == NullabilityKind::NonNull)
9266 MergedKind = LHSKind;
9267 else
9268 MergedKind = NullabilityKind::Unspecified;
9269 }
9270
9271 // Return if ResTy already has the correct nullability.
9272 if (GetNullability(ResTy) == MergedKind)
9273 return ResTy;
9274
9275 // Strip all nullability from ResTy.
9276 while (ResTy->getNullability())
9277 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9278
9279 // Create a new AttributedType with the new nullability kind.
9280 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
9281}
9282
9284 SourceLocation ColonLoc,
9285 Expr *CondExpr, Expr *LHSExpr,
9286 Expr *RHSExpr) {
9287 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9288 // was the condition.
9289 OpaqueValueExpr *opaqueValue = nullptr;
9290 Expr *commonExpr = nullptr;
9291 if (!LHSExpr) {
9292 commonExpr = CondExpr;
9293 // Lower out placeholder types first. This is important so that we don't
9294 // try to capture a placeholder. This happens in few cases in C++; such
9295 // as Objective-C++'s dictionary subscripting syntax.
9296 if (commonExpr->hasPlaceholderType()) {
9297 ExprResult result = CheckPlaceholderExpr(commonExpr);
9298 if (!result.isUsable()) return ExprError();
9299 commonExpr = result.get();
9300 }
9301 // We usually want to apply unary conversions *before* saving, except
9302 // in the special case of a C++ l-value conditional.
9303 if (!(getLangOpts().CPlusPlus
9304 && !commonExpr->isTypeDependent()
9305 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9306 && commonExpr->isGLValue()
9307 && commonExpr->isOrdinaryOrBitFieldObject()
9308 && RHSExpr->isOrdinaryOrBitFieldObject()
9309 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9310 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9311 if (commonRes.isInvalid())
9312 return ExprError();
9313 commonExpr = commonRes.get();
9314 }
9315
9316 // If the common expression is a class or array prvalue, materialize it
9317 // so that we can safely refer to it multiple times.
9318 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9319 commonExpr->getType()->isArrayType())) {
9320 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9321 if (MatExpr.isInvalid())
9322 return ExprError();
9323 commonExpr = MatExpr.get();
9324 }
9325
9326 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9327 commonExpr->getType(),
9328 commonExpr->getValueKind(),
9329 commonExpr->getObjectKind(),
9330 commonExpr);
9331 LHSExpr = CondExpr = opaqueValue;
9332 }
9333
9334 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9337 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9338 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9339 VK, OK, QuestionLoc);
9340 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9341 RHS.isInvalid())
9342 return ExprError();
9343
9344 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9345 RHS.get());
9346
9347 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9348
9349 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9350 Context);
9351
9352 if (!commonExpr)
9353 return new (Context)
9354 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9355 RHS.get(), result, VK, OK);
9356
9358 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9359 ColonLoc, result, VK, OK);
9360}
9361
9363 unsigned FromAttributes = 0, ToAttributes = 0;
9364 if (const auto *FromFn =
9365 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9366 FromAttributes =
9367 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9368 if (const auto *ToFn =
9369 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9370 ToAttributes =
9371 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9372
9373 return FromAttributes != ToAttributes;
9374}
9375
9376// checkPointerTypesForAssignment - This is a very tricky routine (despite
9377// being closely modeled after the C99 spec:-). The odd characteristic of this
9378// routine is it effectively iqnores the qualifiers on the top level pointee.
9379// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9380// FIXME: add a couple examples in this comment.
9382 QualType LHSType,
9383 QualType RHSType,
9384 SourceLocation Loc) {
9385 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9386 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9387
9388 // get the "pointed to" type (ignoring qualifiers at the top level)
9389 const Type *lhptee, *rhptee;
9390 Qualifiers lhq, rhq;
9391 std::tie(lhptee, lhq) =
9392 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9393 std::tie(rhptee, rhq) =
9394 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9395
9397
9398 // C99 6.5.16.1p1: This following citation is common to constraints
9399 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9400 // qualifiers of the type *pointed to* by the right;
9401
9402 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9403 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9405 // Ignore lifetime for further calculation.
9406 lhq.removeObjCLifetime();
9407 rhq.removeObjCLifetime();
9408 }
9409
9410 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
9411 // Treat address-space mismatches as fatal.
9412 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
9414
9415 // It's okay to add or remove GC or lifetime qualifiers when converting to
9416 // and from void*.
9419 S.getASTContext()) &&
9420 (lhptee->isVoidType() || rhptee->isVoidType()))
9421 ; // keep old
9422
9423 // Treat lifetime mismatches as fatal.
9424 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9426
9427 // Treat pointer-auth mismatches as fatal.
9428 else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth()))
9430
9431 // For GCC/MS compatibility, other qualifier mismatches are treated
9432 // as still compatible in C.
9433 else
9435 }
9436
9437 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9438 // incomplete type and the other is a pointer to a qualified or unqualified
9439 // version of void...
9440 if (lhptee->isVoidType()) {
9441 if (rhptee->isIncompleteOrObjectType())
9442 return ConvTy;
9443
9444 // As an extension, we allow cast to/from void* to function pointer.
9445 assert(rhptee->isFunctionType());
9447 }
9448
9449 if (rhptee->isVoidType()) {
9450 // In C, void * to another pointer type is compatible, but we want to note
9451 // that there will be an implicit conversion happening here.
9452 if (lhptee->isIncompleteOrObjectType())
9453 return ConvTy == AssignConvertType::Compatible &&
9454 !S.getLangOpts().CPlusPlus
9456 : ConvTy;
9457
9458 // As an extension, we allow cast to/from void* to function pointer.
9459 assert(lhptee->isFunctionType());
9461 }
9462
9463 if (!S.Diags.isIgnored(
9464 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9465 Loc) &&
9466 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9467 !S.TryFunctionConversion(RHSType, LHSType, RHSType))
9469
9470 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9471 // unqualified versions of compatible types, ...
9472 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9473
9474 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9475 if (!S.Context.hasSameType(ltrans, rtrans)) {
9476 QualType LUnderlying =
9477 ltrans->isOverflowBehaviorType()
9478 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9479 : ltrans;
9480 QualType RUnderlying =
9481 rtrans->isOverflowBehaviorType()
9482 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9483 : rtrans;
9484
9485 if (S.Context.hasSameType(LUnderlying, RUnderlying))
9487
9488 ltrans = LUnderlying;
9489 rtrans = RUnderlying;
9490 }
9491 }
9492
9493 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9494 // Check if the pointee types are compatible ignoring the sign.
9495 // We explicitly check for char so that we catch "char" vs
9496 // "unsigned char" on systems where "char" is unsigned.
9497 if (lhptee->isCharType())
9498 ltrans = S.Context.UnsignedCharTy;
9499 else if (lhptee->hasSignedIntegerRepresentation())
9500 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9501
9502 if (rhptee->isCharType())
9503 rtrans = S.Context.UnsignedCharTy;
9504 else if (rhptee->hasSignedIntegerRepresentation())
9505 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9506
9507 if (ltrans == rtrans) {
9508 // Types are compatible ignoring the sign. Qualifier incompatibility
9509 // takes priority over sign incompatibility because the sign
9510 // warning can be disabled.
9511 if (!S.IsAssignConvertCompatible(ConvTy))
9512 return ConvTy;
9513
9515 }
9516
9517 // If we are a multi-level pointer, it's possible that our issue is simply
9518 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9519 // the eventual target type is the same and the pointers have the same
9520 // level of indirection, this must be the issue.
9521 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9522 do {
9523 std::tie(lhptee, lhq) =
9524 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9525 std::tie(rhptee, rhq) =
9526 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9527
9528 // Inconsistent address spaces at this point is invalid, even if the
9529 // address spaces would be compatible.
9530 // FIXME: This doesn't catch address space mismatches for pointers of
9531 // different nesting levels, like:
9532 // __local int *** a;
9533 // int ** b = a;
9534 // It's not clear how to actually determine when such pointers are
9535 // invalidly incompatible.
9536 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9537 return AssignConvertType::
9538 IncompatibleNestedPointerAddressSpaceMismatch;
9539
9540 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9541
9542 if (lhptee == rhptee)
9544 }
9545
9546 // General pointer incompatibility takes priority over qualifiers.
9547 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9550 }
9551 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9552 // hasSameType, so we can skip further checks.
9553 const auto *LFT = ltrans->getAs<FunctionType>();
9554 const auto *RFT = rtrans->getAs<FunctionType>();
9555 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9556 // The invocation of IsFunctionConversion below will try to transform rtrans
9557 // to obtain an exact match for ltrans. This should not fail because of
9558 // mismatches in result type and parameter types, they were already checked
9559 // by typesAreCompatible above. So we will recreate rtrans (or where
9560 // appropriate ltrans) using the result type and parameter types from ltrans
9561 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9562 const auto *LFPT = dyn_cast<FunctionProtoType>(LFT);
9563 const auto *RFPT = dyn_cast<FunctionProtoType>(RFT);
9564 if (LFPT && RFPT) {
9565 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9566 LFPT->getParamTypes(),
9567 RFPT->getExtProtoInfo());
9568 } else if (LFPT) {
9570 EPI.ExtInfo = RFT->getExtInfo();
9571 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9572 LFPT->getParamTypes(), EPI);
9573 } else if (RFPT) {
9574 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9575 // all of its ExtProtoInfo. Transform ltrans instead.
9577 EPI.ExtInfo = LFT->getExtInfo();
9578 ltrans = S.Context.getFunctionType(RFPT->getReturnType(),
9579 RFPT->getParamTypes(), EPI);
9580 } else {
9581 rtrans = S.Context.getFunctionNoProtoType(LFT->getReturnType(),
9582 RFT->getExtInfo());
9583 }
9584 if (!S.Context.hasSameUnqualifiedType(rtrans, ltrans) &&
9585 !S.IsFunctionConversion(rtrans, ltrans))
9587 }
9588 return ConvTy;
9589}
9590
9591/// checkBlockPointerTypesForAssignment - This routine determines whether two
9592/// block pointer types are compatible or whether a block and normal pointer
9593/// are compatible. It is more restrict than comparing two function pointer
9594// types.
9596 QualType LHSType,
9597 QualType RHSType) {
9598 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9599 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9600
9601 QualType lhptee, rhptee;
9602
9603 // get the "pointed to" type (ignoring qualifiers at the top level)
9604 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9605 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9606
9607 // In C++, the types have to match exactly.
9608 if (S.getLangOpts().CPlusPlus)
9610
9612
9613 // For blocks we enforce that qualifiers are identical.
9614 Qualifiers LQuals = lhptee.getLocalQualifiers();
9615 Qualifiers RQuals = rhptee.getLocalQualifiers();
9616 if (S.getLangOpts().OpenCL) {
9617 LQuals.removeAddressSpace();
9618 RQuals.removeAddressSpace();
9619 }
9620 if (LQuals != RQuals)
9622
9623 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9624 // assignment.
9625 // The current behavior is similar to C++ lambdas. A block might be
9626 // assigned to a variable iff its return type and parameters are compatible
9627 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9628 // an assignment. Presumably it should behave in way that a function pointer
9629 // assignment does in C, so for each parameter and return type:
9630 // * CVR and address space of LHS should be a superset of CVR and address
9631 // space of RHS.
9632 // * unqualified types should be compatible.
9633 if (S.getLangOpts().OpenCL) {
9635 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9636 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9638 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9640
9641 return ConvTy;
9642}
9643
9644/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9645/// for assignment compatibility.
9647 QualType LHSType,
9648 QualType RHSType) {
9649 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9650 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9651
9652 if (LHSType->isObjCBuiltinType()) {
9653 // Class is not compatible with ObjC object pointers.
9654 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9655 !RHSType->isObjCQualifiedClassType())
9658 }
9659 if (RHSType->isObjCBuiltinType()) {
9660 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9661 !LHSType->isObjCQualifiedClassType())
9664 }
9665 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9666 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9667
9668 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9669 // make an exception for id<P>
9670 !LHSType->isObjCQualifiedIdType())
9672
9673 if (S.Context.typesAreCompatible(LHSType, RHSType))
9675 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9678}
9679
9681 QualType LHSType,
9682 QualType RHSType) {
9683 // Fake up an opaque expression. We don't actually care about what
9684 // cast operations are required, so if CheckAssignmentConstraints
9685 // adds casts to this they'll be wasted, but fortunately that doesn't
9686 // usually happen on valid code.
9687 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9688 ExprResult RHSPtr = &RHSExpr;
9689 CastKind K;
9690
9691 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9692}
9693
9694/// This helper function returns true if QT is a vector type that has element
9695/// type ElementType.
9696static bool isVector(QualType QT, QualType ElementType) {
9697 if (const VectorType *VT = QT->getAs<VectorType>())
9698 return VT->getElementType().getCanonicalType() == ElementType;
9699 return false;
9700}
9701
9702/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9703/// has code to accommodate several GCC extensions when type checking
9704/// pointers. Here are some objectionable examples that GCC considers warnings:
9705///
9706/// int a, *pint;
9707/// short *pshort;
9708/// struct foo *pfoo;
9709///
9710/// pint = pshort; // warning: assignment from incompatible pointer type
9711/// a = pint; // warning: assignment makes integer from pointer without a cast
9712/// pint = a; // warning: assignment makes pointer from integer without a cast
9713/// pint = pfoo; // warning: assignment from incompatible pointer type
9714///
9715/// As a result, the code for dealing with pointers is more complex than the
9716/// C99 spec dictates.
9717///
9718/// Sets 'Kind' for any result kind except Incompatible.
9720 ExprResult &RHS,
9721 CastKind &Kind,
9722 bool ConvertRHS) {
9723 QualType RHSType = RHS.get()->getType();
9724 QualType OrigLHSType = LHSType;
9725
9726 // Get canonical types. We're not formatting these types, just comparing
9727 // them.
9728 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9729 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9730
9731 // Common case: no conversion required.
9732 if (LHSType == RHSType) {
9733 Kind = CK_NoOp;
9735 }
9736
9737 // If the LHS has an __auto_type, there are no additional type constraints
9738 // to be worried about.
9739 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9740 if (AT->isGNUAutoType()) {
9741 Kind = CK_NoOp;
9743 }
9744 }
9745
9746 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHSType, RHSType);
9747 switch (OBTResult) {
9749 Kind = CK_NoOp;
9752 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9756 break;
9757 }
9758
9759 // Check for incompatible OBT types in pointer pointee types
9760 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9761 QualType LHSPointee = LHSType->getPointeeType();
9762 QualType RHSPointee = RHSType->getPointeeType();
9763 if ((LHSPointee->isOverflowBehaviorType() ||
9764 RHSPointee->isOverflowBehaviorType()) &&
9765 !Context.areCompatibleOverflowBehaviorTypes(LHSPointee, RHSPointee)) {
9766 Kind = CK_NoOp;
9768 }
9769 }
9770
9771 // If we have an atomic type, try a non-atomic assignment, then just add an
9772 // atomic qualification step.
9773 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9775 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9777 return Result;
9778 if (Kind != CK_NoOp && ConvertRHS)
9779 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9780 Kind = CK_NonAtomicToAtomic;
9781 return Result;
9782 }
9783
9784 // If the left-hand side is a reference type, then we are in a
9785 // (rare!) case where we've allowed the use of references in C,
9786 // e.g., as a parameter type in a built-in function. In this case,
9787 // just make sure that the type referenced is compatible with the
9788 // right-hand side type. The caller is responsible for adjusting
9789 // LHSType so that the resulting expression does not have reference
9790 // type.
9791 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9792 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9793 Kind = CK_LValueBitCast;
9795 }
9797 }
9798
9799 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9800 // of an ExtVector type to the same ExtVector type.
9801 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9802 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9803 // Implicit conversions require the same number of elements.
9804 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9806
9807 if (LHSType->isExtVectorBoolType() &&
9808 RHSExtType->getElementType()->isIntegerType()) {
9809 Kind = CK_IntegralToBoolean;
9811 }
9812 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9813 if (Context.getLangOpts().OpenCL &&
9814 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9815 Kind = CK_BitCast;
9817 }
9819 }
9820 if (RHSType->isArithmeticType()) {
9821 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9822 if (ConvertRHS)
9823 RHS = prepareVectorSplat(LHSType, RHS.get());
9824 Kind = CK_VectorSplat;
9826 }
9827 }
9828
9829 // Conversions to or from vector type.
9830 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9831 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9832 // Allow assignments of an AltiVec vector type to an equivalent GCC
9833 // vector type and vice versa
9834 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9835 Kind = CK_BitCast;
9837 }
9838
9839 // If we are allowing lax vector conversions, and LHS and RHS are both
9840 // vectors, the total size only needs to be the same. This is a bitcast;
9841 // no bits are changed but the result type is different.
9842 if (isLaxVectorConversion(RHSType, LHSType)) {
9843 // The default for lax vector conversions with Altivec vectors will
9844 // change, so if we are converting between vector types where
9845 // at least one is an Altivec vector, emit a warning.
9846 if (Context.getTargetInfo().getTriple().isPPC() &&
9847 anyAltivecTypes(RHSType, LHSType) &&
9848 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9849 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9850 << RHSType << LHSType;
9851 Kind = CK_BitCast;
9853 }
9854 }
9855
9856 // When the RHS comes from another lax conversion (e.g. binops between
9857 // scalars and vectors) the result is canonicalized as a vector. When the
9858 // LHS is also a vector, the lax is allowed by the condition above. Handle
9859 // the case where LHS is a scalar.
9860 if (LHSType->isScalarType()) {
9861 const VectorType *VecType = RHSType->getAs<VectorType>();
9862 if (VecType && VecType->getNumElements() == 1 &&
9863 isLaxVectorConversion(RHSType, LHSType)) {
9864 if (Context.getTargetInfo().getTriple().isPPC() &&
9866 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9868 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9869 << RHSType << LHSType;
9870 ExprResult *VecExpr = &RHS;
9871 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9872 Kind = CK_BitCast;
9874 }
9875 }
9876
9877 // Allow assignments between fixed-length and sizeless SVE vectors.
9878 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9879 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9880 if (ARM().areCompatibleSveTypes(LHSType, RHSType) ||
9881 ARM().areLaxCompatibleSveTypes(LHSType, RHSType)) {
9882 Kind = CK_BitCast;
9884 }
9885
9886 // Allow assignments between fixed-length and sizeless RVV vectors.
9887 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9888 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9889 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9890 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9891 Kind = CK_BitCast;
9893 }
9894 }
9895
9897 }
9898
9899 // Diagnose attempts to convert between __ibm128, __float128 and long double
9900 // where such conversions currently can't be handled.
9901 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9903
9904 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9905 // discards the imaginary part.
9906 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9907 !LHSType->getAs<ComplexType>())
9909
9910 // Arithmetic conversions.
9911 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9912 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9913 if (ConvertRHS)
9914 Kind = PrepareScalarCast(RHS, LHSType);
9916 }
9917
9918 // Conversions to normal pointers.
9919 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9920 // U* -> T*
9921 if (isa<PointerType>(RHSType)) {
9922 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9923 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9924 if (AddrSpaceL != AddrSpaceR)
9925 Kind = CK_AddressSpaceConversion;
9926 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9927 Kind = CK_NoOp;
9928 else
9929 Kind = CK_BitCast;
9930 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9931 RHS.get()->getBeginLoc());
9932 }
9933
9934 // int -> T*
9935 if (RHSType->isIntegerType()) {
9936 Kind = CK_IntegralToPointer; // FIXME: null?
9938 }
9939
9940 // C pointers are not compatible with ObjC object pointers,
9941 // with two exceptions:
9942 if (isa<ObjCObjectPointerType>(RHSType)) {
9943 // - conversions to void*
9944 if (LHSPointer->getPointeeType()->isVoidType()) {
9945 Kind = CK_BitCast;
9947 }
9948
9949 // - conversions from 'Class' to the redefinition type
9950 if (RHSType->isObjCClassType() &&
9951 Context.hasSameType(LHSType,
9952 Context.getObjCClassRedefinitionType())) {
9953 Kind = CK_BitCast;
9955 }
9956
9957 Kind = CK_BitCast;
9959 }
9960
9961 // U^ -> void*
9962 if (RHSType->getAs<BlockPointerType>()) {
9963 if (LHSPointer->getPointeeType()->isVoidType()) {
9964 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9965 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9966 ->getPointeeType()
9967 .getAddressSpace();
9968 Kind =
9969 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9971 }
9972 }
9973
9975 }
9976
9977 // Conversions to block pointers.
9978 if (isa<BlockPointerType>(LHSType)) {
9979 // U^ -> T^
9980 if (RHSType->isBlockPointerType()) {
9981 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9982 ->getPointeeType()
9983 .getAddressSpace();
9984 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9985 ->getPointeeType()
9986 .getAddressSpace();
9987 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9988 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9989 }
9990
9991 // int or null -> T^
9992 if (RHSType->isIntegerType()) {
9993 Kind = CK_IntegralToPointer; // FIXME: null
9995 }
9996
9997 // id -> T^
9998 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9999 Kind = CK_AnyPointerToBlockPointerCast;
10001 }
10002
10003 // void* -> T^
10004 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
10005 if (RHSPT->getPointeeType()->isVoidType()) {
10006 Kind = CK_AnyPointerToBlockPointerCast;
10008 }
10009
10011 }
10012
10013 // Conversions to Objective-C pointers.
10014 if (isa<ObjCObjectPointerType>(LHSType)) {
10015 // A* -> B*
10016 if (RHSType->isObjCObjectPointerType()) {
10017 Kind = CK_BitCast;
10018 AssignConvertType result =
10019 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
10020 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10022 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
10024 return result;
10025 }
10026
10027 // int or null -> A*
10028 if (RHSType->isIntegerType()) {
10029 Kind = CK_IntegralToPointer; // FIXME: null
10031 }
10032
10033 // In general, C pointers are not compatible with ObjC object pointers,
10034 // with two exceptions:
10035 if (isa<PointerType>(RHSType)) {
10036 Kind = CK_CPointerToObjCPointerCast;
10037
10038 // - conversions from 'void*'
10039 if (RHSType->isVoidPointerType()) {
10041 }
10042
10043 // - conversions to 'Class' from its redefinition type
10044 if (LHSType->isObjCClassType() &&
10045 Context.hasSameType(RHSType,
10046 Context.getObjCClassRedefinitionType())) {
10048 }
10049
10051 }
10052
10053 // Only under strict condition T^ is compatible with an Objective-C pointer.
10054 if (RHSType->isBlockPointerType() &&
10056 if (ConvertRHS)
10058 Kind = CK_BlockPointerToObjCPointerCast;
10060 }
10061
10063 }
10064
10065 // Conversion to nullptr_t (C23 only)
10066 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10069 // null -> nullptr_t
10070 Kind = CK_NullToPointer;
10072 }
10073
10074 // Conversions from pointers that are not covered by the above.
10075 if (isa<PointerType>(RHSType)) {
10076 // T* -> _Bool
10077 if (LHSType == Context.BoolTy) {
10078 Kind = CK_PointerToBoolean;
10080 }
10081
10082 // T* -> int
10083 if (LHSType->isIntegerType()) {
10084 Kind = CK_PointerToIntegral;
10086 }
10087
10089 }
10090
10091 // Conversions from Objective-C pointers that are not covered by the above.
10092 if (isa<ObjCObjectPointerType>(RHSType)) {
10093 // T* -> _Bool
10094 if (LHSType == Context.BoolTy) {
10095 Kind = CK_PointerToBoolean;
10097 }
10098
10099 // T* -> int
10100 if (LHSType->isIntegerType()) {
10101 Kind = CK_PointerToIntegral;
10103 }
10104
10106 }
10107
10108 // struct A -> struct B
10109 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
10110 if (Context.typesAreCompatible(LHSType, RHSType)) {
10111 Kind = CK_NoOp;
10113 }
10114 }
10115
10116 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10117 Kind = CK_IntToOCLSampler;
10119 }
10120
10122}
10123
10124/// Constructs a transparent union from an expression that is
10125/// used to initialize the transparent union.
10127 ExprResult &EResult, QualType UnionType,
10128 FieldDecl *Field) {
10129 // Build an initializer list that designates the appropriate member
10130 // of the transparent union.
10131 Expr *E = EResult.get();
10133 C, SourceLocation(), E, SourceLocation(), /*isExplicit=*/false);
10134 Initializer->setType(UnionType);
10135 Initializer->setInitializedFieldInUnion(Field);
10136
10137 // Build a compound literal constructing a value of the transparent
10138 // union type from this initializer list.
10139 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10140 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10141 VK_PRValue, Initializer, false);
10142}
10143
10146 ExprResult &RHS) {
10147 QualType RHSType = RHS.get()->getType();
10148
10149 // If the ArgType is a Union type, we want to handle a potential
10150 // transparent_union GCC extension.
10151 const RecordType *UT = ArgType->getAsUnionType();
10152 if (!UT)
10154
10155 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10156 if (!UD->hasAttr<TransparentUnionAttr>())
10158
10159 // The field to initialize within the transparent union.
10160 FieldDecl *InitField = nullptr;
10161 // It's compatible if the expression matches any of the fields.
10162 for (auto *it : UD->fields()) {
10163 if (it->getType()->isPointerType()) {
10164 // If the transparent union contains a pointer type, we allow:
10165 // 1) void pointer
10166 // 2) null pointer constant
10167 if (RHSType->isPointerType())
10168 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10169 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10170 InitField = it;
10171 break;
10172 }
10173
10176 RHS = ImpCastExprToType(RHS.get(), it->getType(),
10177 CK_NullToPointer);
10178 InitField = it;
10179 break;
10180 }
10181 }
10182
10183 CastKind Kind;
10184 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) ==
10186 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10187 InitField = it;
10188 break;
10189 }
10190 }
10191
10192 if (!InitField)
10194
10195 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10197}
10198
10200 ExprResult &CallerRHS,
10201 bool Diagnose,
10202 bool DiagnoseCFAudited,
10203 bool ConvertRHS) {
10204 // We need to be able to tell the caller whether we diagnosed a problem, if
10205 // they ask us to issue diagnostics.
10206 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10207
10208 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10209 // we can't avoid *all* modifications at the moment, so we need some somewhere
10210 // to put the updated value.
10211 ExprResult LocalRHS = CallerRHS;
10212 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10213
10214 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10215 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10216 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10217 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10218 Diag(RHS.get()->getExprLoc(),
10219 diag::warn_noderef_to_dereferenceable_pointer)
10220 << RHS.get()->getSourceRange();
10221 }
10222 }
10223 }
10224
10225 if (getLangOpts().CPlusPlus) {
10226 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10227 // C++ 5.17p3: If the left operand is not of class type, the
10228 // expression is implicitly converted (C++ 4) to the
10229 // cv-unqualified type of the left operand.
10230 QualType RHSType = RHS.get()->getType();
10231 if (Diagnose) {
10232 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10234 } else {
10237 /*SuppressUserConversions=*/false,
10238 AllowedExplicit::None,
10239 /*InOverloadResolution=*/false,
10240 /*CStyle=*/false,
10241 /*AllowObjCWritebackConversion=*/false);
10242 if (ICS.isFailure())
10244 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10246 }
10247 if (RHS.isInvalid())
10250 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10251 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10253
10254 // Check if OBT is being discarded during assignment
10255 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10256 if (RHSType->isOverflowBehaviorType() &&
10257 !LHSType->isOverflowBehaviorType()) {
10259 }
10260
10261 return result;
10262 }
10263
10264 // FIXME: Currently, we fall through and treat C++ classes like C
10265 // structures.
10266 // FIXME: We also fall through for atomics; not sure what should
10267 // happen there, though.
10268 } else if (RHS.get()->getType() == Context.OverloadTy) {
10269 // As a set of extensions to C, we support overloading on functions. These
10270 // functions need to be resolved here.
10271 DeclAccessPair DAP;
10273 RHS.get(), LHSType, /*Complain=*/false, DAP))
10274 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10275 else
10277 }
10278
10279 // For HLSL records, insert derived-to-base conversion if needed.
10280 if (getLangOpts().HLSL && LHSType->isRecordType()) {
10281 QualType RHSType = RHS.get()->getType();
10282 if (!Context.hasSameUnqualifiedType(RHSType, LHSType)) {
10283 CXXBasePaths Paths;
10284 if (IsDerivedFrom(RHS.get()->getBeginLoc(), RHSType, LHSType, Paths)) {
10285 CXXCastPath CastPath;
10286 BuildBasePathArray(Paths, CastPath);
10287 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_DerivedToBase, VK_LValue,
10288 &CastPath);
10289 }
10290 }
10291 }
10292
10293 // This check seems unnatural, however it is necessary to ensure the proper
10294 // conversion of functions/arrays. If the conversion were done for all
10295 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10296 // expressions that suppress this implicit conversion (&, sizeof). This needs
10297 // to happen before we check for null pointer conversions because C does not
10298 // undergo the same implicit conversions as C++ does above (by the calls to
10299 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10300 // lvalue to rvalue cast before checking for null pointer constraints. This
10301 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10302 //
10303 // Suppress this for references: C++ 8.5.3p5.
10304 if (!LHSType->isReferenceType()) {
10305 // FIXME: We potentially allocate here even if ConvertRHS is false.
10307 if (RHS.isInvalid())
10309 }
10310
10311 // The constraints are expressed in terms of the atomic, qualified, or
10312 // unqualified type of the LHS.
10313 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10314
10315 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10316 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10317 if ((LHSTypeAfterConversion->isPointerType() ||
10318 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10319 LHSTypeAfterConversion->isBlockPointerType()) &&
10320 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10324 if (Diagnose || ConvertRHS) {
10325 CastKind Kind;
10326 CXXCastPath Path;
10327 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10328 /*IgnoreBaseAccess=*/false, Diagnose);
10329
10330 // If there is a conversion of some kind, check to see what kind of
10331 // pointer conversion happened so we can diagnose a C++ compatibility
10332 // diagnostic if the conversion is invalid. This only matters if the RHS
10333 // is some kind of void pointer. We have a carve-out when the RHS is from
10334 // a macro expansion because the use of a macro may indicate different
10335 // code between C and C++. Consider: char *s = NULL; where NULL is
10336 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10337 // C++, which is valid in C++.
10338 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10339 !RHS.get()->getBeginLoc().isMacroID()) {
10340 QualType CanRHS =
10342 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10343 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10344 Ret = checkPointerTypesForAssignment(*this, CanLHS, CanRHS,
10345 RHS.get()->getExprLoc());
10346 // Anything that's not considered perfectly compatible would be
10347 // incompatible in C++.
10350 }
10351 }
10352
10353 if (ConvertRHS)
10354 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10355 }
10356 return Ret;
10357 }
10358 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10359 // unqualified bool, and the right operand is a pointer or its type is
10360 // nullptr_t.
10361 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10362 RHS.get()->getType()->isNullPtrType()) {
10363 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10364 // only handles nullptr -> _Bool due to needing an extra conversion
10365 // step.
10366 // We model this by converting from nullptr -> void * and then let the
10367 // conversion from void * -> _Bool happen naturally.
10368 if (Diagnose || ConvertRHS) {
10369 CastKind Kind;
10370 CXXCastPath Path;
10371 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10372 /*IgnoreBaseAccess=*/false, Diagnose);
10373 if (ConvertRHS)
10374 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10375 &Path);
10376 }
10377 }
10378
10379 // OpenCL queue_t type assignment.
10380 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10382 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10384 }
10385
10386 CastKind Kind;
10387 AssignConvertType result =
10388 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10389
10390 // If assigning a void * created by an allocation function call to some other
10391 // type, check that the allocated size is sufficient for that type.
10392 if (result != AssignConvertType::Incompatible &&
10393 RHS.get()->getType()->isVoidPointerType())
10394 CheckSufficientAllocSize(*this, LHSType, RHS.get());
10395
10396 // C99 6.5.16.1p2: The value of the right operand is converted to the
10397 // type of the assignment expression.
10398 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10399 // so that we can use references in built-in functions even in C.
10400 // The getNonReferenceType() call makes sure that the resulting expression
10401 // does not have reference type.
10402 if (result != AssignConvertType::Incompatible &&
10403 RHS.get()->getType() != LHSType) {
10405 Expr *E = RHS.get();
10406
10407 // Check for various Objective-C errors. If we are not reporting
10408 // diagnostics and just checking for errors, e.g., during overload
10409 // resolution, return Incompatible to indicate the failure.
10410 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10411 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
10413 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10414 if (!Diagnose)
10416 }
10417 if (getLangOpts().ObjC &&
10418 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10419 E->getType(), E, Diagnose) ||
10420 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10421 if (!Diagnose)
10423 // Replace the expression with a corrected version and continue so we
10424 // can find further errors.
10425 RHS = E;
10427 }
10428
10429 if (ConvertRHS)
10430 RHS = ImpCastExprToType(E, Ty, Kind);
10431 }
10432
10433 return result;
10434}
10435
10436namespace {
10437/// The original operand to an operator, prior to the application of the usual
10438/// arithmetic conversions and converting the arguments of a builtin operator
10439/// candidate.
10440struct OriginalOperand {
10441 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10442 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10443 Op = MTE->getSubExpr();
10444 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10445 Op = BTE->getSubExpr();
10446 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10447 Orig = ICE->getSubExprAsWritten();
10448 Conversion = ICE->getConversionFunction();
10449 }
10450 }
10451
10452 QualType getType() const { return Orig->getType(); }
10453
10454 Expr *Orig;
10455 NamedDecl *Conversion;
10456};
10457}
10458
10460 ExprResult &RHS) {
10461 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10462
10463 Diag(Loc, diag::err_typecheck_invalid_operands)
10464 << OrigLHS.getType() << OrigRHS.getType()
10465 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10466
10467 // If a user-defined conversion was applied to either of the operands prior
10468 // to applying the built-in operator rules, tell the user about it.
10469 if (OrigLHS.Conversion) {
10470 Diag(OrigLHS.Conversion->getLocation(),
10471 diag::note_typecheck_invalid_operands_converted)
10472 << 0 << LHS.get()->getType();
10473 }
10474 if (OrigRHS.Conversion) {
10475 Diag(OrigRHS.Conversion->getLocation(),
10476 diag::note_typecheck_invalid_operands_converted)
10477 << 1 << RHS.get()->getType();
10478 }
10479
10480 return QualType();
10481}
10482
10484 ExprResult &RHS) {
10485 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10486 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10487
10488 bool LHSNatVec = LHSType->isVectorType();
10489 bool RHSNatVec = RHSType->isVectorType();
10490
10491 if (!(LHSNatVec && RHSNatVec)) {
10492 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10493 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10494 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10495 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10496 << Vector->getSourceRange();
10497 return QualType();
10498 }
10499
10500 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10501 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10502 << RHS.get()->getSourceRange();
10503
10504 return QualType();
10505}
10506
10507/// Try to convert a value of non-vector type to a vector type by converting
10508/// the type to the element type of the vector and then performing a splat.
10509/// If the language is OpenCL, we only use conversions that promote scalar
10510/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10511/// for float->int.
10512///
10513/// OpenCL V2.0 6.2.6.p2:
10514/// An error shall occur if any scalar operand type has greater rank
10515/// than the type of the vector element.
10516///
10517/// \param scalar - if non-null, actually perform the conversions
10518/// \return true if the operation fails (but without diagnosing the failure)
10520 QualType scalarTy,
10521 QualType vectorEltTy,
10522 QualType vectorTy,
10523 unsigned &DiagID) {
10524 // The conversion to apply to the scalar before splatting it,
10525 // if necessary.
10526 CastKind scalarCast = CK_NoOp;
10527
10528 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
10529 scalarCast = CK_IntegralToBoolean;
10530 } else if (vectorEltTy->isIntegralType(S.Context)) {
10531 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10532 (scalarTy->isIntegerType() &&
10533 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10534 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10535 return true;
10536 }
10537 if (!scalarTy->isIntegralType(S.Context))
10538 return true;
10539 scalarCast = CK_IntegralCast;
10540 } else if (vectorEltTy->isRealFloatingType()) {
10541 if (scalarTy->isRealFloatingType()) {
10542 if (S.getLangOpts().OpenCL &&
10543 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10544 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10545 return true;
10546 }
10547 scalarCast = CK_FloatingCast;
10548 }
10549 else if (scalarTy->isIntegralType(S.Context))
10550 scalarCast = CK_IntegralToFloating;
10551 else
10552 return true;
10553 } else {
10554 return true;
10555 }
10556
10557 // Adjust scalar if desired.
10558 if (scalar) {
10559 if (scalarCast != CK_NoOp)
10560 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10561 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10562 }
10563 return false;
10564}
10565
10566/// Convert vector E to a vector with the same number of elements but different
10567/// element type.
10568static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10569 const auto *VecTy = E->getType()->getAs<VectorType>();
10570 assert(VecTy && "Expression E must be a vector");
10571 QualType NewVecTy =
10572 VecTy->isExtVectorType()
10573 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10574 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10575 VecTy->getVectorKind());
10576
10577 // Look through the implicit cast. Return the subexpression if its type is
10578 // NewVecTy.
10579 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10580 if (ICE->getSubExpr()->getType() == NewVecTy)
10581 return ICE->getSubExpr();
10582
10583 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10584 return S.ImpCastExprToType(E, NewVecTy, Cast);
10585}
10586
10587/// Test if a (constant) integer Int can be casted to another integer type
10588/// IntTy without losing precision.
10590 QualType OtherIntTy) {
10591 Expr *E = Int->get();
10593 return false;
10594
10595 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10596
10597 // Reject cases where the value of the Int is unknown as that would
10598 // possibly cause truncation, but accept cases where the scalar can be
10599 // demoted without loss of precision.
10600 Expr::EvalResult EVResult;
10601 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10602 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10603 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10604 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10605
10606 if (CstInt) {
10607 // If the scalar is constant and is of a higher order and has more active
10608 // bits that the vector element type, reject it.
10609 llvm::APSInt Result = EVResult.Val.getInt();
10610 unsigned NumBits = IntSigned
10611 ? (Result.isNegative() ? Result.getSignificantBits()
10612 : Result.getActiveBits())
10613 : Result.getActiveBits();
10614 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10615 return true;
10616
10617 // If the signedness of the scalar type and the vector element type
10618 // differs and the number of bits is greater than that of the vector
10619 // element reject it.
10620 return (IntSigned != OtherIntSigned &&
10621 NumBits > S.Context.getIntWidth(OtherIntTy));
10622 }
10623
10624 // Reject cases where the value of the scalar is not constant and it's
10625 // order is greater than that of the vector element type.
10626 return (Order < 0);
10627}
10628
10629/// Test if a (constant) integer Int can be casted to floating point type
10630/// FloatTy without losing precision.
10632 QualType FloatTy) {
10633 if (Int->get()->containsErrors())
10634 return false;
10635
10636 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10637
10638 // Determine if the integer constant can be expressed as a floating point
10639 // number of the appropriate type.
10640 Expr::EvalResult EVResult;
10641 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10642
10643 uint64_t Bits = 0;
10644 if (CstInt) {
10645 // Reject constants that would be truncated if they were converted to
10646 // the floating point type. Test by simple to/from conversion.
10647 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10648 // could be avoided if there was a convertFromAPInt method
10649 // which could signal back if implicit truncation occurred.
10650 llvm::APSInt Result = EVResult.Val.getInt();
10651 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10652 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10653 llvm::APFloat::rmTowardZero);
10654 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10656 bool Ignored = false;
10657 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10658 &Ignored);
10659 if (Result != ConvertBack)
10660 return true;
10661 } else {
10662 // Reject types that cannot be fully encoded into the mantissa of
10663 // the float.
10664 Bits = S.Context.getTypeSize(IntTy);
10665 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10666 S.Context.getFloatTypeSemantics(FloatTy));
10667 if (Bits > FloatPrec)
10668 return true;
10669 }
10670
10671 return false;
10672}
10673
10674/// Attempt to convert and splat Scalar into a vector whose types matches
10675/// Vector following GCC conversion rules. The rule is that implicit
10676/// conversion can occur when Scalar can be casted to match Vector's element
10677/// type without causing truncation of Scalar.
10679 ExprResult *Vector) {
10680 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10681 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10682 QualType VectorEltTy;
10683
10684 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10685 assert(!isa<ExtVectorType>(VT) &&
10686 "ExtVectorTypes should not be handled here!");
10687 VectorEltTy = VT->getElementType();
10688 } else if (VectorTy->isSveVLSBuiltinType()) {
10689 VectorEltTy =
10690 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10691 } else {
10692 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10693 }
10694
10695 // Reject cases where the vector element type or the scalar element type are
10696 // not integral or floating point types.
10697 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10698 return true;
10699
10700 // The conversion to apply to the scalar before splatting it,
10701 // if necessary.
10702 CastKind ScalarCast = CK_NoOp;
10703
10704 // Accept cases where the vector elements are integers and the scalar is
10705 // an integer.
10706 // FIXME: Notionally if the scalar was a floating point value with a precise
10707 // integral representation, we could cast it to an appropriate integer
10708 // type and then perform the rest of the checks here. GCC will perform
10709 // this conversion in some cases as determined by the input language.
10710 // We should accept it on a language independent basis.
10711 if (VectorEltTy->isIntegralType(S.Context) &&
10712 ScalarTy->isIntegralType(S.Context) &&
10713 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10714
10715 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10716 return true;
10717
10718 ScalarCast = CK_IntegralCast;
10719 } else if (VectorEltTy->isIntegralType(S.Context) &&
10720 ScalarTy->isRealFloatingType()) {
10721 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10722 ScalarCast = CK_FloatingToIntegral;
10723 else
10724 return true;
10725 } else if (VectorEltTy->isRealFloatingType()) {
10726 if (ScalarTy->isRealFloatingType()) {
10727
10728 // Reject cases where the scalar type is not a constant and has a higher
10729 // Order than the vector element type.
10730 llvm::APFloat Result(0.0);
10731
10732 // Determine whether this is a constant scalar. In the event that the
10733 // value is dependent (and thus cannot be evaluated by the constant
10734 // evaluator), skip the evaluation. This will then diagnose once the
10735 // expression is instantiated.
10736 bool CstScalar = Scalar->get()->isValueDependent() ||
10737 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10738 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10739 if (!CstScalar && Order < 0)
10740 return true;
10741
10742 // If the scalar cannot be safely casted to the vector element type,
10743 // reject it.
10744 if (CstScalar) {
10745 bool Truncated = false;
10746 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10747 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10748 if (Truncated)
10749 return true;
10750 }
10751
10752 ScalarCast = CK_FloatingCast;
10753 } else if (ScalarTy->isIntegralType(S.Context)) {
10754 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10755 return true;
10756
10757 ScalarCast = CK_IntegralToFloating;
10758 } else
10759 return true;
10760 } else if (ScalarTy->isEnumeralType())
10761 return true;
10762
10763 // Adjust scalar if desired.
10764 if (ScalarCast != CK_NoOp)
10765 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10766 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10767 return false;
10768}
10769
10771 SourceLocation Loc, bool IsCompAssign,
10772 bool AllowBothBool,
10773 bool AllowBoolConversions,
10774 bool AllowBoolOperation,
10775 bool ReportInvalid) {
10776 if (!IsCompAssign) {
10778 if (LHS.isInvalid())
10779 return QualType();
10780 }
10782 if (RHS.isInvalid())
10783 return QualType();
10784
10785 // For conversion purposes, we ignore any qualifiers.
10786 // For example, "const float" and "float" are equivalent.
10787 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10788 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10789
10790 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10791 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10792 assert(LHSVecType || RHSVecType);
10793
10794 if (getLangOpts().HLSL)
10795 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10796 IsCompAssign);
10797
10798 // Any operation with MFloat8 type is only possible with C intrinsics
10799 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10800 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10801 return InvalidOperands(Loc, LHS, RHS);
10802
10803 // AltiVec-style "vector bool op vector bool" combinations are allowed
10804 // for some operators but not others.
10805 if (!AllowBothBool && LHSVecType &&
10806 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10807 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10808 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10809
10810 // This operation may not be performed on boolean vectors.
10811 if (!AllowBoolOperation &&
10812 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10813 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10814
10815 // If the vector types are identical, return.
10816 if (Context.hasSameType(LHSType, RHSType))
10817 return Context.getCommonSugaredType(LHSType, RHSType);
10818
10819 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10820 if (LHSVecType && RHSVecType &&
10821 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10822 if (isa<ExtVectorType>(LHSVecType)) {
10823 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10824 return LHSType;
10825 }
10826
10827 if (!IsCompAssign)
10828 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10829 return RHSType;
10830 }
10831
10832 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10833 // can be mixed, with the result being the non-bool type. The non-bool
10834 // operand must have integer element type.
10835 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10836 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10837 (Context.getTypeSize(LHSVecType->getElementType()) ==
10838 Context.getTypeSize(RHSVecType->getElementType()))) {
10839 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10840 LHSVecType->getElementType()->isIntegerType() &&
10841 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10842 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10843 return LHSType;
10844 }
10845 if (!IsCompAssign &&
10846 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10847 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10848 RHSVecType->getElementType()->isIntegerType()) {
10849 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10850 return RHSType;
10851 }
10852 }
10853
10854 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10855 // invalid since the ambiguity can affect the ABI.
10856 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10857 unsigned &SVEorRVV) {
10858 const VectorType *VecType = SecondType->getAs<VectorType>();
10859 SVEorRVV = 0;
10860 if (FirstType->isSizelessBuiltinType() && VecType) {
10863 return true;
10869 SVEorRVV = 1;
10870 return true;
10871 }
10872 }
10873
10874 return false;
10875 };
10876
10877 unsigned SVEorRVV;
10878 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10879 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10880 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10881 << SVEorRVV << LHSType << RHSType;
10882 return QualType();
10883 }
10884
10885 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10886 // invalid since the ambiguity can affect the ABI.
10887 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10888 unsigned &SVEorRVV) {
10889 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10890 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10891
10892 SVEorRVV = 0;
10893 if (FirstVecType && SecondVecType) {
10894 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10895 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10896 SecondVecType->getVectorKind() ==
10898 return true;
10899 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10900 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10901 SecondVecType->getVectorKind() ==
10903 SecondVecType->getVectorKind() ==
10905 SecondVecType->getVectorKind() ==
10907 SVEorRVV = 1;
10908 return true;
10909 }
10910 }
10911 return false;
10912 }
10913
10914 if (SecondVecType &&
10915 SecondVecType->getVectorKind() == VectorKind::Generic) {
10916 if (FirstType->isSVESizelessBuiltinType())
10917 return true;
10918 if (FirstType->isRVVSizelessBuiltinType()) {
10919 SVEorRVV = 1;
10920 return true;
10921 }
10922 }
10923
10924 return false;
10925 };
10926
10927 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10928 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10929 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10930 << SVEorRVV << LHSType << RHSType;
10931 return QualType();
10932 }
10933
10934 // If there's a vector type and a scalar, try to convert the scalar to
10935 // the vector element type and splat.
10936 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10937 if (!RHSVecType) {
10938 if (isa<ExtVectorType>(LHSVecType)) {
10939 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10940 LHSVecType->getElementType(), LHSType,
10941 DiagID))
10942 return LHSType;
10943 } else {
10944 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10945 return LHSType;
10946 }
10947 }
10948 if (!LHSVecType) {
10949 if (isa<ExtVectorType>(RHSVecType)) {
10950 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10951 LHSType, RHSVecType->getElementType(),
10952 RHSType, DiagID))
10953 return RHSType;
10954 } else {
10955 if (LHS.get()->isLValue() ||
10956 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10957 return RHSType;
10958 }
10959 }
10960
10961 // FIXME: The code below also handles conversion between vectors and
10962 // non-scalars, we should break this down into fine grained specific checks
10963 // and emit proper diagnostics.
10964 QualType VecType = LHSVecType ? LHSType : RHSType;
10965 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10966 QualType OtherType = LHSVecType ? RHSType : LHSType;
10967 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10968 if (isLaxVectorConversion(OtherType, VecType)) {
10969 if (Context.getTargetInfo().getTriple().isPPC() &&
10970 anyAltivecTypes(RHSType, LHSType) &&
10971 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10972 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10973 // If we're allowing lax vector conversions, only the total (data) size
10974 // needs to be the same. For non compound assignment, if one of the types is
10975 // scalar, the result is always the vector type.
10976 if (!IsCompAssign) {
10977 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10978 return VecType;
10979 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10980 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10981 // type. Note that this is already done by non-compound assignments in
10982 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10983 // <1 x T> -> T. The result is also a vector type.
10984 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10985 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10986 ExprResult *RHSExpr = &RHS;
10987 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10988 return VecType;
10989 }
10990 }
10991
10992 // Okay, the expression is invalid.
10993
10994 // If there's a non-vector, non-real operand, diagnose that.
10995 if ((!RHSVecType && !RHSType->isRealType()) ||
10996 (!LHSVecType && !LHSType->isRealType())) {
10997 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10998 << LHSType << RHSType
10999 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11000 return QualType();
11001 }
11002
11003 // OpenCL V1.1 6.2.6.p1:
11004 // If the operands are of more than one vector type, then an error shall
11005 // occur. Implicit conversions between vector types are not permitted, per
11006 // section 6.2.1.
11007 if (getLangOpts().OpenCL &&
11008 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
11009 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
11010 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
11011 << RHSType;
11012 return QualType();
11013 }
11014
11015
11016 // If there is a vector type that is not a ExtVector and a scalar, we reach
11017 // this point if scalar could not be converted to the vector's element type
11018 // without truncation.
11019 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
11020 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
11021 QualType Scalar = LHSVecType ? RHSType : LHSType;
11022 QualType Vector = LHSVecType ? LHSType : RHSType;
11023 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
11024 Diag(Loc,
11025 diag::err_typecheck_vector_not_convertable_implict_truncation)
11026 << ScalarOrVector << Scalar << Vector;
11027
11028 return QualType();
11029 }
11030
11031 // Otherwise, use the generic diagnostic.
11032 Diag(Loc, DiagID)
11033 << LHSType << RHSType
11034 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11035 return QualType();
11036}
11037
11039 SourceLocation Loc,
11040 bool IsCompAssign,
11041 ArithConvKind OperationKind) {
11042 if (!IsCompAssign) {
11044 if (LHS.isInvalid())
11045 return QualType();
11046 }
11048 if (RHS.isInvalid())
11049 return QualType();
11050
11051 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11052 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11053
11054 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11055 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11056
11057 unsigned DiagID = diag::err_typecheck_invalid_operands;
11058 if ((OperationKind == ArithConvKind::Arithmetic) &&
11059 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11060 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11061 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11062 << RHS.get()->getSourceRange();
11063 return QualType();
11064 }
11065
11066 if (Context.hasSameType(LHSType, RHSType))
11067 return LHSType;
11068
11069 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11070 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11071 return LHSType;
11072 }
11073 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11074 if (LHS.get()->isLValue() ||
11075 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11076 return RHSType;
11077 }
11078
11079 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11080 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11081 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11082 << LHSType << RHSType << LHS.get()->getSourceRange()
11083 << RHS.get()->getSourceRange();
11084 return QualType();
11085 }
11086
11087 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11088 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11089 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
11090 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11091 << LHSType << RHSType << LHS.get()->getSourceRange()
11092 << RHS.get()->getSourceRange();
11093 return QualType();
11094 }
11095
11096 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11097 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11098 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11099 bool ScalarOrVector =
11100 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11101
11102 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
11103 << ScalarOrVector << Scalar << Vector;
11104
11105 return QualType();
11106 }
11107
11108 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11109 << RHS.get()->getSourceRange();
11110 return QualType();
11111}
11112
11113// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11114// expression. These are mainly cases where the null pointer is used as an
11115// integer instead of a pointer.
11117 SourceLocation Loc, bool IsCompare) {
11118 // The canonical way to check for a GNU null is with isNullPointerConstant,
11119 // but we use a bit of a hack here for speed; this is a relatively
11120 // hot path, and isNullPointerConstant is slow.
11121 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
11122 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
11123
11124 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11125
11126 // Avoid analyzing cases where the result will either be invalid (and
11127 // diagnosed as such) or entirely valid and not something to warn about.
11128 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11129 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11130 return;
11131
11132 // Comparison operations would not make sense with a null pointer no matter
11133 // what the other expression is.
11134 if (!IsCompare) {
11135 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
11136 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11137 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11138 return;
11139 }
11140
11141 // The rest of the operations only make sense with a null pointer
11142 // if the other expression is a pointer.
11143 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11144 NonNullType->canDecayToPointerType())
11145 return;
11146
11147 S.Diag(Loc, diag::warn_null_in_comparison_operation)
11148 << LHSNull /* LHS is NULL */ << NonNullType
11149 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11150}
11151
11153 SourceLocation OpLoc) {
11154 // If the divisor is real, then this is real/real or complex/real division.
11155 // Either way there can be no precision loss.
11156 auto *CT = DivisorTy->getAs<ComplexType>();
11157 if (!CT)
11158 return;
11159
11160 QualType ElementType = CT->getElementType().getCanonicalType();
11161 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11163 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11164 return;
11165
11166 ASTContext &Ctx = S.getASTContext();
11167 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11168 const llvm::fltSemantics &ElementTypeSemantics =
11169 Ctx.getFloatTypeSemantics(ElementType);
11170 const llvm::fltSemantics &HigherElementTypeSemantics =
11171 Ctx.getFloatTypeSemantics(HigherElementType);
11172
11173 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11174 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11175 (HigherElementType == Ctx.LongDoubleTy &&
11176 !Ctx.getTargetInfo().hasLongDoubleType())) {
11177 // Retain the location of the first use of higher precision type.
11180 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11181 if (Type == HigherElementType) {
11182 Num++;
11183 return;
11184 }
11185 }
11186 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
11187 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
11188 }
11189}
11190
11192 SourceLocation Loc) {
11193 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
11194 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
11195 if (!LUE || !RUE)
11196 return;
11197 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11198 RUE->getKind() != UETT_SizeOf)
11199 return;
11200
11201 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11202 QualType LHSTy = LHSArg->getType();
11203 QualType RHSTy;
11204
11205 if (RUE->isArgumentType())
11206 RHSTy = RUE->getArgumentType().getNonReferenceType();
11207 else
11208 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11209
11210 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11211 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11212 return;
11213
11214 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11215 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11216 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11217 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11218 << LHSArgDecl;
11219 }
11220 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11221 QualType ArrayElemTy = ArrayTy->getElementType();
11222 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11223 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11224 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11225 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11226 return;
11227 S.Diag(Loc, diag::warn_division_sizeof_array)
11228 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11229 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11230 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11231 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11232 << LHSArgDecl;
11233 }
11234
11235 S.Diag(Loc, diag::note_precedence_silence) << RHS;
11236 }
11237}
11238
11240 ExprResult &RHS,
11241 SourceLocation Loc, bool IsDiv) {
11242 // Check for division/remainder by zero.
11243 Expr::EvalResult RHSValue;
11244 if (!RHS.get()->isValueDependent() &&
11245 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11246 RHSValue.Val.getInt() == 0)
11247 S.DiagRuntimeBehavior(Loc, RHS.get(),
11248 S.PDiag(diag::warn_remainder_division_by_zero)
11249 << IsDiv << RHS.get()->getSourceRange());
11250}
11251
11252static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11253 const ExprResult &LHS, const ExprResult &RHS,
11254 BinaryOperatorKind Opc) {
11255 if (!LHS.isUsable() || !RHS.isUsable())
11256 return;
11257 const Expr *LHSExpr = LHS.get();
11258 const Expr *RHSExpr = RHS.get();
11259 const QualType LHSType = LHSExpr->getType();
11260 const QualType RHSType = RHSExpr->getType();
11261 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11262 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11263 if (!LHSIsScoped && !RHSIsScoped)
11264 return;
11265 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11266 return;
11267 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11268 return;
11269 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11270 return;
11271 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11272 SourceLocation BeginLoc = expr->getBeginLoc();
11273 QualType IntType = type->castAs<EnumType>()
11274 ->getDecl()
11275 ->getDefinitionOrSelf()
11276 ->getIntegerType();
11277 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11278 S.Diag(BeginLoc, diag::note_no_implicit_conversion_for_scoped_enum)
11279 << FixItHint::CreateInsertion(BeginLoc, InsertionString)
11280 << FixItHint::CreateInsertion(expr->getEndLoc(), ")");
11281 };
11282 if (LHSIsScoped) {
11283 DiagnosticHelper(LHSExpr, LHSType);
11284 }
11285 if (RHSIsScoped) {
11286 DiagnosticHelper(RHSExpr, RHSType);
11287 }
11288}
11289
11291 SourceLocation Loc,
11292 BinaryOperatorKind Opc) {
11293 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11294 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11295
11296 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11297
11298 QualType LHSTy = LHS.get()->getType();
11299 QualType RHSTy = RHS.get()->getType();
11300 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11301 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11302 /*AllowBothBool*/ getLangOpts().AltiVec,
11303 /*AllowBoolConversions*/ false,
11304 /*AllowBooleanOperation*/ false,
11305 /*ReportInvalid*/ true);
11306 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11307 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11309 if (!IsDiv &&
11310 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11311 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11312 // For division, only matrix-by-scalar is supported. Other combinations with
11313 // matrix types are invalid.
11314 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11315 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11316
11318 LHS, RHS, Loc,
11320 if (LHS.isInvalid() || RHS.isInvalid())
11321 return QualType();
11322
11323 if (compType.isNull() || !compType->isArithmeticType()) {
11324 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11325 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11326 return ResultTy;
11327 }
11328 if (IsDiv) {
11329 DetectPrecisionLossInComplexDivision(*this, RHS.get()->getType(), Loc);
11330 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11331 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11332 }
11333 return compType;
11334}
11335
11337 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11338 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11339
11340 // Note: This check is here to simplify the double exclusions of
11341 // scalar and vector HLSL checks. No getLangOpts().HLSL
11342 // is needed since all languages exlcude doubles.
11343 if (LHS.get()->getType()->isDoubleType() ||
11344 RHS.get()->getType()->isDoubleType() ||
11345 (LHS.get()->getType()->isVectorType() && LHS.get()
11346 ->getType()
11347 ->getAs<VectorType>()
11348 ->getElementType()
11349 ->isDoubleType()) ||
11350 (RHS.get()->getType()->isVectorType() && RHS.get()
11351 ->getType()
11352 ->getAs<VectorType>()
11353 ->getElementType()
11354 ->isDoubleType()))
11355 return InvalidOperands(Loc, LHS, RHS);
11356
11357 if (LHS.get()->getType()->isVectorType() ||
11358 RHS.get()->getType()->isVectorType()) {
11359 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11360 RHS.get()->getType()->hasIntegerRepresentation()) ||
11361 (getLangOpts().HLSL &&
11362 (LHS.get()->getType()->hasFloatingRepresentation() ||
11364 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11365 /*AllowBothBool*/ getLangOpts().AltiVec,
11366 /*AllowBoolConversions*/ false,
11367 /*AllowBooleanOperation*/ false,
11368 /*ReportInvalid*/ true);
11369 return InvalidOperands(Loc, LHS, RHS);
11370 }
11371
11372 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11373 RHS.get()->getType()->isSveVLSBuiltinType()) {
11374 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11376 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11378
11379 return InvalidOperands(Loc, LHS, RHS);
11380 }
11381
11383 LHS, RHS, Loc,
11385 if (LHS.isInvalid() || RHS.isInvalid())
11386 return QualType();
11387
11388 if (compType.isNull() ||
11389 (!compType->isIntegerType() &&
11390 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11391 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11392 diagnoseScopedEnums(*this, Loc, LHS, RHS,
11393 IsCompAssign ? BO_RemAssign : BO_Rem);
11394 return ResultTy;
11395 }
11396 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11397 return compType;
11398}
11399
11400/// Diagnose invalid arithmetic on two void pointers.
11402 Expr *LHSExpr, Expr *RHSExpr) {
11403 S.Diag(Loc, S.getLangOpts().CPlusPlus
11404 ? diag::err_typecheck_pointer_arith_void_type
11405 : diag::ext_gnu_void_ptr)
11406 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11407 << RHSExpr->getSourceRange();
11408}
11409
11410/// Diagnose invalid arithmetic on a void pointer.
11412 Expr *Pointer) {
11413 S.Diag(Loc, S.getLangOpts().CPlusPlus
11414 ? diag::err_typecheck_pointer_arith_void_type
11415 : diag::ext_gnu_void_ptr)
11416 << 0 /* one pointer */ << Pointer->getSourceRange();
11417}
11418
11419/// Diagnose invalid arithmetic on a null pointer.
11420///
11421/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11422/// idiom, which we recognize as a GNU extension.
11423///
11425 Expr *Pointer, bool IsGNUIdiom) {
11426 if (IsGNUIdiom)
11427 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11428 << Pointer->getSourceRange();
11429 else
11430 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11431 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11432}
11433
11434/// Diagnose invalid subraction on a null pointer.
11435///
11437 Expr *Pointer, bool BothNull) {
11438 // Null - null is valid in C++ [expr.add]p7
11439 if (BothNull && S.getLangOpts().CPlusPlus)
11440 return;
11441
11442 // Is this s a macro from a system header?
11444 return;
11445
11447 S.PDiag(diag::warn_pointer_sub_null_ptr)
11448 << S.getLangOpts().CPlusPlus
11449 << Pointer->getSourceRange());
11450}
11451
11452/// Diagnose invalid arithmetic on two function pointers.
11454 Expr *LHS, Expr *RHS) {
11455 assert(LHS->getType()->isAnyPointerType());
11456 assert(RHS->getType()->isAnyPointerType());
11457 S.Diag(Loc, S.getLangOpts().CPlusPlus
11458 ? diag::err_typecheck_pointer_arith_function_type
11459 : diag::ext_gnu_ptr_func_arith)
11460 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11461 // We only show the second type if it differs from the first.
11463 RHS->getType())
11464 << RHS->getType()->getPointeeType()
11465 << LHS->getSourceRange() << RHS->getSourceRange();
11466}
11467
11468/// Diagnose invalid arithmetic on a function pointer.
11470 Expr *Pointer) {
11471 assert(Pointer->getType()->isAnyPointerType());
11472 S.Diag(Loc, S.getLangOpts().CPlusPlus
11473 ? diag::err_typecheck_pointer_arith_function_type
11474 : diag::ext_gnu_ptr_func_arith)
11475 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11476 << 0 /* one pointer, so only one type */
11477 << Pointer->getSourceRange();
11478}
11479
11480/// Emit error if Operand is incomplete pointer type
11481///
11482/// \returns True if pointer has incomplete type
11484 Expr *Operand) {
11485 QualType ResType = Operand->getType();
11486 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11487 ResType = ResAtomicType->getValueType();
11488
11489 assert(ResType->isAnyPointerType());
11490 QualType PointeeTy = ResType->getPointeeType();
11491 return S.RequireCompleteSizedType(
11492 Loc, PointeeTy,
11493 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11494 Operand->getSourceRange());
11495}
11496
11497/// Check the validity of an arithmetic pointer operand.
11498///
11499/// If the operand has pointer type, this code will check for pointer types
11500/// which are invalid in arithmetic operations. These will be diagnosed
11501/// appropriately, including whether or not the use is supported as an
11502/// extension.
11503///
11504/// \returns True when the operand is valid to use (even if as an extension).
11506 Expr *Operand) {
11507 QualType ResType = Operand->getType();
11508 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11509 ResType = ResAtomicType->getValueType();
11510
11511 if (!ResType->isAnyPointerType()) return true;
11512
11513 QualType PointeeTy = ResType->getPointeeType();
11514 if (PointeeTy->isVoidType()) {
11515 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11516 return !S.getLangOpts().CPlusPlus;
11517 }
11518 if (PointeeTy->isFunctionType()) {
11519 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11520 return !S.getLangOpts().CPlusPlus;
11521 }
11522
11523 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11524
11525 return true;
11526}
11527
11528/// Check the validity of a binary arithmetic operation w.r.t. pointer
11529/// operands.
11530///
11531/// This routine will diagnose any invalid arithmetic on pointer operands much
11532/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11533/// for emitting a single diagnostic even for operations where both LHS and RHS
11534/// are (potentially problematic) pointers.
11535///
11536/// \returns True when the operand is valid to use (even if as an extension).
11538 Expr *LHSExpr, Expr *RHSExpr) {
11539 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11540 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11541 if (!isLHSPointer && !isRHSPointer) return true;
11542
11543 QualType LHSPointeeTy, RHSPointeeTy;
11544 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11545 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11546
11547 // if both are pointers check if operation is valid wrt address spaces
11548 if (isLHSPointer && isRHSPointer) {
11549 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
11550 S.getASTContext())) {
11551 S.Diag(Loc,
11552 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11553 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11554 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11555 return false;
11556 }
11557 }
11558
11559 // Check for arithmetic on pointers to incomplete types.
11560 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11561 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11562 if (isLHSVoidPtr || isRHSVoidPtr) {
11563 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11564 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11565 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11566
11567 return !S.getLangOpts().CPlusPlus;
11568 }
11569
11570 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11571 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11572 if (isLHSFuncPtr || isRHSFuncPtr) {
11573 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11574 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11575 RHSExpr);
11576 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11577
11578 return !S.getLangOpts().CPlusPlus;
11579 }
11580
11581 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11582 return false;
11583 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11584 return false;
11585
11586 return true;
11587}
11588
11589/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11590/// literal.
11592 Expr *LHSExpr, Expr *RHSExpr) {
11593 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11594 Expr* IndexExpr = RHSExpr;
11595 if (!StrExpr) {
11596 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11597 IndexExpr = LHSExpr;
11598 }
11599
11600 bool IsStringPlusInt = StrExpr &&
11602 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11603 return;
11604
11605 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11606 Self.Diag(OpLoc, diag::warn_string_plus_int)
11607 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11608
11609 // Only print a fixit for "str" + int, not for int + "str".
11610 if (IndexExpr == RHSExpr) {
11611 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11612 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11613 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11615 << FixItHint::CreateInsertion(EndLoc, "]");
11616 } else
11617 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11618}
11619
11620/// Emit a warning when adding a char literal to a string.
11622 Expr *LHSExpr, Expr *RHSExpr) {
11623 const Expr *StringRefExpr = LHSExpr;
11624 const CharacterLiteral *CharExpr =
11625 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11626
11627 if (!CharExpr) {
11628 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11629 StringRefExpr = RHSExpr;
11630 }
11631
11632 if (!CharExpr || !StringRefExpr)
11633 return;
11634
11635 const QualType StringType = StringRefExpr->getType();
11636
11637 // Return if not a PointerType.
11638 if (!StringType->isAnyPointerType())
11639 return;
11640
11641 // Return if not a CharacterType.
11642 if (!StringType->getPointeeType()->isAnyCharacterType())
11643 return;
11644
11645 ASTContext &Ctx = Self.getASTContext();
11646 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11647
11648 const QualType CharType = CharExpr->getType();
11649 if (!CharType->isAnyCharacterType() &&
11650 CharType->isIntegerType() &&
11651 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11652 Self.Diag(OpLoc, diag::warn_string_plus_char)
11653 << DiagRange << Ctx.CharTy;
11654 } else {
11655 Self.Diag(OpLoc, diag::warn_string_plus_char)
11656 << DiagRange << CharExpr->getType();
11657 }
11658
11659 // Only print a fixit for str + char, not for char + str.
11660 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11661 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11662 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11663 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11665 << FixItHint::CreateInsertion(EndLoc, "]");
11666 } else {
11667 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11668 }
11669}
11670
11671/// Emit error when two pointers are incompatible.
11673 Expr *LHSExpr, Expr *RHSExpr) {
11674 assert(LHSExpr->getType()->isAnyPointerType());
11675 assert(RHSExpr->getType()->isAnyPointerType());
11676 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11677 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11678 << RHSExpr->getSourceRange();
11679}
11680
11681// C99 6.5.6
11684 QualType* CompLHSTy) {
11685 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11686
11687 if (LHS.get()->getType()->isVectorType() ||
11688 RHS.get()->getType()->isVectorType()) {
11689 QualType compType =
11690 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11691 /*AllowBothBool*/ getLangOpts().AltiVec,
11692 /*AllowBoolConversions*/ getLangOpts().ZVector,
11693 /*AllowBooleanOperation*/ false,
11694 /*ReportInvalid*/ true);
11695 if (CompLHSTy) *CompLHSTy = compType;
11696 return compType;
11697 }
11698
11699 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11700 RHS.get()->getType()->isSveVLSBuiltinType()) {
11701 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11703 if (CompLHSTy)
11704 *CompLHSTy = compType;
11705 return compType;
11706 }
11707
11708 if (LHS.get()->getType()->isConstantMatrixType() ||
11709 RHS.get()->getType()->isConstantMatrixType()) {
11710 QualType compType =
11711 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11712 if (CompLHSTy)
11713 *CompLHSTy = compType;
11714 return compType;
11715 }
11716
11718 LHS, RHS, Loc,
11720 if (LHS.isInvalid() || RHS.isInvalid())
11721 return QualType();
11722
11723 // Diagnose "string literal" '+' int and string '+' "char literal".
11724 if (Opc == BO_Add) {
11725 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11726 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11727 }
11728
11729 // handle the common case first (both operands are arithmetic).
11730 if (!compType.isNull() && compType->isArithmeticType()) {
11731 if (CompLHSTy) *CompLHSTy = compType;
11732 return compType;
11733 }
11734
11735 // Type-checking. Ultimately the pointer's going to be in PExp;
11736 // note that we bias towards the LHS being the pointer.
11737 Expr *PExp = LHS.get(), *IExp = RHS.get();
11738
11739 bool isObjCPointer;
11740 if (PExp->getType()->isPointerType()) {
11741 isObjCPointer = false;
11742 } else if (PExp->getType()->isObjCObjectPointerType()) {
11743 isObjCPointer = true;
11744 } else {
11745 std::swap(PExp, IExp);
11746 if (PExp->getType()->isPointerType()) {
11747 isObjCPointer = false;
11748 } else if (PExp->getType()->isObjCObjectPointerType()) {
11749 isObjCPointer = true;
11750 } else {
11751 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11752 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11753 return ResultTy;
11754 }
11755 }
11756 assert(PExp->getType()->isAnyPointerType());
11757
11758 if (!IExp->getType()->isIntegerType())
11759 return InvalidOperands(Loc, LHS, RHS);
11760
11761 // Adding to a null pointer results in undefined behavior.
11764 // In C++ adding zero to a null pointer is defined.
11765 Expr::EvalResult KnownVal;
11766 if (!getLangOpts().CPlusPlus ||
11767 (!IExp->isValueDependent() &&
11768 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11769 KnownVal.Val.getInt() != 0))) {
11770 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11772 Context, BO_Add, PExp, IExp);
11773 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11774 }
11775 }
11776
11777 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11778 return QualType();
11779
11780 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11781 return QualType();
11782
11783 // Arithmetic on label addresses is normally allowed, except when we add
11784 // a ptrauth signature to the addresses.
11785 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11786 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11787 << /*addition*/ 1;
11788 return QualType();
11789 }
11790
11791 // Check array bounds for pointer arithemtic
11792 CheckArrayAccess(PExp, IExp);
11793
11794 if (CompLHSTy) {
11795 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11796 if (LHSTy.isNull()) {
11797 LHSTy = LHS.get()->getType();
11798 if (Context.isPromotableIntegerType(LHSTy))
11799 LHSTy = Context.getPromotedIntegerType(LHSTy);
11800 }
11801 *CompLHSTy = LHSTy;
11802 }
11803
11804 return PExp->getType();
11805}
11806
11807// C99 6.5.6
11809 SourceLocation Loc,
11811 QualType *CompLHSTy) {
11812 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11813
11814 if (LHS.get()->getType()->isVectorType() ||
11815 RHS.get()->getType()->isVectorType()) {
11816 QualType compType =
11817 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11818 /*AllowBothBool*/ getLangOpts().AltiVec,
11819 /*AllowBoolConversions*/ getLangOpts().ZVector,
11820 /*AllowBooleanOperation*/ false,
11821 /*ReportInvalid*/ true);
11822 if (CompLHSTy) *CompLHSTy = compType;
11823 return compType;
11824 }
11825
11826 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11827 RHS.get()->getType()->isSveVLSBuiltinType()) {
11828 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11830 if (CompLHSTy)
11831 *CompLHSTy = compType;
11832 return compType;
11833 }
11834
11835 if (LHS.get()->getType()->isConstantMatrixType() ||
11836 RHS.get()->getType()->isConstantMatrixType()) {
11837 QualType compType =
11838 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11839 if (CompLHSTy)
11840 *CompLHSTy = compType;
11841 return compType;
11842 }
11843
11845 LHS, RHS, Loc,
11847 if (LHS.isInvalid() || RHS.isInvalid())
11848 return QualType();
11849
11850 // Enforce type constraints: C99 6.5.6p3.
11851
11852 // Handle the common case first (both operands are arithmetic).
11853 if (!compType.isNull() && compType->isArithmeticType()) {
11854 if (CompLHSTy) *CompLHSTy = compType;
11855 return compType;
11856 }
11857
11858 // Either ptr - int or ptr - ptr.
11859 if (LHS.get()->getType()->isAnyPointerType()) {
11860 QualType lpointee = LHS.get()->getType()->getPointeeType();
11861
11862 // Diagnose bad cases where we step over interface counts.
11863 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11864 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11865 return QualType();
11866
11867 // Arithmetic on label addresses is normally allowed, except when we add
11868 // a ptrauth signature to the addresses.
11869 if (isa<AddrLabelExpr>(LHS.get()) &&
11870 getLangOpts().PointerAuthIndirectGotos) {
11871 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11872 << /*subtraction*/ 0;
11873 return QualType();
11874 }
11875
11876 // The result type of a pointer-int computation is the pointer type.
11877 if (RHS.get()->getType()->isIntegerType()) {
11878 // Subtracting from a null pointer should produce a warning.
11879 // The last argument to the diagnose call says this doesn't match the
11880 // GNU int-to-pointer idiom.
11883 // In C++ adding zero to a null pointer is defined.
11884 Expr::EvalResult KnownVal;
11885 if (!getLangOpts().CPlusPlus ||
11886 (!RHS.get()->isValueDependent() &&
11887 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11888 KnownVal.Val.getInt() != 0))) {
11889 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11890 }
11891 }
11892
11893 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11894 return QualType();
11895
11896 // Check array bounds for pointer arithemtic
11897 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11898 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11899
11900 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11901 return LHS.get()->getType();
11902 }
11903
11904 // Handle pointer-pointer subtractions.
11905 if (const PointerType *RHSPTy
11906 = RHS.get()->getType()->getAs<PointerType>()) {
11907 QualType rpointee = RHSPTy->getPointeeType();
11908
11909 if (getLangOpts().CPlusPlus) {
11910 // Pointee types must be the same: C++ [expr.add]
11911 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11912 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11913 }
11914 } else {
11915 // Pointee types must be compatible C99 6.5.6p3
11916 if (!Context.typesAreCompatible(
11917 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11918 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11919 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11920 return QualType();
11921 }
11922 }
11923
11925 LHS.get(), RHS.get()))
11926 return QualType();
11927
11928 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11930 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11932
11933 // Subtracting nullptr or from nullptr is suspect
11934 if (LHSIsNullPtr)
11935 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11936 if (RHSIsNullPtr)
11937 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11938
11939 // The pointee type may have zero size. As an extension, a structure or
11940 // union may have zero size or an array may have zero length. In this
11941 // case subtraction does not make sense.
11942 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11943 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11944 if (ElementSize.isZero()) {
11945 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11946 << rpointee.getUnqualifiedType()
11947 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11948 }
11949 }
11950
11951 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11952 return Context.getPointerDiffType();
11953 }
11954 }
11955
11956 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11957 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11958 return ResultTy;
11959}
11960
11962 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11963 return ET->getDecl()->isScoped();
11964 return false;
11965}
11966
11969 QualType LHSType) {
11970 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11971 // so skip remaining warnings as we don't want to modify values within Sema.
11972 if (S.getLangOpts().OpenCL)
11973 return;
11974
11975 if (Opc == BO_Shr &&
11977 S.Diag(Loc, diag::warn_shift_bool) << LHS.get()->getSourceRange();
11978
11979 // Check right/shifter operand
11980 Expr::EvalResult RHSResult;
11981 if (RHS.get()->isValueDependent() ||
11982 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11983 return;
11984 llvm::APSInt Right = RHSResult.Val.getInt();
11985
11986 if (Right.isNegative()) {
11987 S.DiagRuntimeBehavior(Loc, RHS.get(),
11988 S.PDiag(diag::warn_shift_negative)
11989 << RHS.get()->getSourceRange());
11990 return;
11991 }
11992
11993 QualType LHSExprType = LHS.get()->getType();
11994 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11995 if (LHSExprType->isBitIntType())
11996 LeftSize = S.Context.getIntWidth(LHSExprType);
11997 else if (LHSExprType->isFixedPointType()) {
11998 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11999 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
12000 }
12001 if (Right.uge(LeftSize)) {
12002 S.DiagRuntimeBehavior(Loc, RHS.get(),
12003 S.PDiag(diag::warn_shift_gt_typewidth)
12004 << RHS.get()->getSourceRange());
12005 return;
12006 }
12007
12008 // FIXME: We probably need to handle fixed point types specially here.
12009 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
12010 return;
12011
12012 // When left shifting an ICE which is signed, we can check for overflow which
12013 // according to C++ standards prior to C++2a has undefined behavior
12014 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
12015 // more than the maximum value representable in the result type, so never
12016 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
12017 // expression is still probably a bug.)
12018 Expr::EvalResult LHSResult;
12019 if (LHS.get()->isValueDependent() ||
12021 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
12022 return;
12023 llvm::APSInt Left = LHSResult.Val.getInt();
12024
12025 // Don't warn if signed overflow is defined, then all the rest of the
12026 // diagnostics will not be triggered because the behavior is defined.
12027 // Also don't warn in C++20 mode (and newer), as signed left shifts
12028 // always wrap and never overflow.
12029 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
12030 return;
12031
12032 // If LHS does not have a non-negative value then, the
12033 // behavior is undefined before C++2a. Warn about it.
12034 if (Left.isNegative()) {
12035 S.DiagRuntimeBehavior(Loc, LHS.get(),
12036 S.PDiag(diag::warn_shift_lhs_negative)
12037 << LHS.get()->getSourceRange());
12038 return;
12039 }
12040
12041 llvm::APInt ResultBits =
12042 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
12043 if (ResultBits.ule(LeftSize))
12044 return;
12045 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
12046 Result = Result.shl(Right);
12047
12048 // Print the bit representation of the signed integer as an unsigned
12049 // hexadecimal number.
12050 SmallString<40> HexResult;
12051 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
12052
12053 // If we are only missing a sign bit, this is less likely to result in actual
12054 // bugs -- if the result is cast back to an unsigned type, it will have the
12055 // expected value. Thus we place this behind a different warning that can be
12056 // turned off separately if needed.
12057 if (ResultBits - 1 == LeftSize) {
12058 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
12059 << HexResult << LHSType
12060 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12061 return;
12062 }
12063
12064 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
12065 << HexResult.str() << Result.getSignificantBits() << LHSType
12066 << Left.getBitWidth() << LHS.get()->getSourceRange()
12067 << RHS.get()->getSourceRange();
12068}
12069
12070/// Return the resulting type when a vector is shifted
12071/// by a scalar or vector shift amount.
12073 SourceLocation Loc, bool IsCompAssign) {
12074 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12075 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12076 !LHS.get()->getType()->isVectorType()) {
12077 S.Diag(Loc, diag::err_shift_rhs_only_vector)
12078 << RHS.get()->getType() << LHS.get()->getType()
12079 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12080 return QualType();
12081 }
12082
12083 if (!IsCompAssign) {
12084 LHS = S.UsualUnaryConversions(LHS.get());
12085 if (LHS.isInvalid()) return QualType();
12086 }
12087
12088 RHS = S.UsualUnaryConversions(RHS.get());
12089 if (RHS.isInvalid()) return QualType();
12090
12091 QualType LHSType = LHS.get()->getType();
12092 // Note that LHS might be a scalar because the routine calls not only in
12093 // OpenCL case.
12094 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12095 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12096
12097 // Note that RHS might not be a vector.
12098 QualType RHSType = RHS.get()->getType();
12099 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12100 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12101
12102 // Do not allow shifts for boolean vectors.
12103 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12104 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12105 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12106 << LHS.get()->getType() << RHS.get()->getType()
12107 << LHS.get()->getSourceRange();
12108 return QualType();
12109 }
12110
12111 // The operands need to be integers.
12112 if (!LHSEleType->isIntegerType()) {
12113 S.Diag(Loc, diag::err_typecheck_expect_int)
12114 << LHS.get()->getType() << LHS.get()->getSourceRange();
12115 return QualType();
12116 }
12117
12118 if (!RHSEleType->isIntegerType()) {
12119 S.Diag(Loc, diag::err_typecheck_expect_int)
12120 << RHS.get()->getType() << RHS.get()->getSourceRange();
12121 return QualType();
12122 }
12123
12124 if (!LHSVecTy) {
12125 assert(RHSVecTy);
12126 if (IsCompAssign)
12127 return RHSType;
12128 if (LHSEleType != RHSEleType) {
12129 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
12130 LHSEleType = RHSEleType;
12131 }
12132 QualType VecTy =
12133 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
12134 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
12135 LHSType = VecTy;
12136 } else if (RHSVecTy) {
12137 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12138 // are applied component-wise. So if RHS is a vector, then ensure
12139 // that the number of elements is the same as LHS...
12140 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12141 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12142 << LHS.get()->getType() << RHS.get()->getType()
12143 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12144 return QualType();
12145 }
12146 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12147 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12148 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12149 if (LHSBT != RHSBT &&
12150 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
12151 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
12152 << LHS.get()->getType() << RHS.get()->getType()
12153 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12154 }
12155 }
12156 } else {
12157 // ...else expand RHS to match the number of elements in LHS.
12158 QualType VecTy =
12159 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
12160 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12161 }
12162
12163 return LHSType;
12164}
12165
12167 ExprResult &RHS, SourceLocation Loc,
12168 bool IsCompAssign) {
12169 if (!IsCompAssign) {
12170 LHS = S.UsualUnaryConversions(LHS.get());
12171 if (LHS.isInvalid())
12172 return QualType();
12173 }
12174
12175 RHS = S.UsualUnaryConversions(RHS.get());
12176 if (RHS.isInvalid())
12177 return QualType();
12178
12179 QualType LHSType = LHS.get()->getType();
12180 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12181 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12182 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
12183 : LHSType;
12184
12185 // Note that RHS might not be a vector
12186 QualType RHSType = RHS.get()->getType();
12187 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12188 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12189 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
12190 : RHSType;
12191
12192 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12193 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12194 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12195 << LHSType << RHSType << LHS.get()->getSourceRange();
12196 return QualType();
12197 }
12198
12199 if (!LHSEleType->isIntegerType()) {
12200 S.Diag(Loc, diag::err_typecheck_expect_int)
12201 << LHS.get()->getType() << LHS.get()->getSourceRange();
12202 return QualType();
12203 }
12204
12205 if (!RHSEleType->isIntegerType()) {
12206 S.Diag(Loc, diag::err_typecheck_expect_int)
12207 << RHS.get()->getType() << RHS.get()->getSourceRange();
12208 return QualType();
12209 }
12210
12211 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12212 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
12213 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
12214 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12215 << LHSType << RHSType << LHS.get()->getSourceRange()
12216 << RHS.get()->getSourceRange();
12217 return QualType();
12218 }
12219
12220 if (!LHSType->isSveVLSBuiltinType()) {
12221 assert(RHSType->isSveVLSBuiltinType());
12222 if (IsCompAssign)
12223 return RHSType;
12224 if (LHSEleType != RHSEleType) {
12225 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
12226 LHSEleType = RHSEleType;
12227 }
12228 const llvm::ElementCount VecSize =
12229 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
12230 QualType VecTy =
12231 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
12232 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
12233 LHSType = VecTy;
12234 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12235 if (S.Context.getTypeSize(RHSBuiltinTy) !=
12236 S.Context.getTypeSize(LHSBuiltinTy)) {
12237 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12238 << LHSType << RHSType << LHS.get()->getSourceRange()
12239 << RHS.get()->getSourceRange();
12240 return QualType();
12241 }
12242 } else {
12243 const llvm::ElementCount VecSize =
12244 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
12245 if (LHSEleType != RHSEleType) {
12246 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
12247 RHSEleType = LHSEleType;
12248 }
12249 QualType VecTy =
12250 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
12251 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12252 }
12253
12254 return LHSType;
12255}
12256
12257// C99 6.5.7
12260 bool IsCompAssign) {
12261 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12262
12263 // Vector shifts promote their scalar inputs to vector type.
12264 if (LHS.get()->getType()->isVectorType() ||
12265 RHS.get()->getType()->isVectorType()) {
12266 if (LangOpts.ZVector) {
12267 // The shift operators for the z vector extensions work basically
12268 // like general shifts, except that neither the LHS nor the RHS is
12269 // allowed to be a "vector bool".
12270 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12271 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12272 return InvalidOperands(Loc, LHS, RHS);
12273 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12274 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12275 return InvalidOperands(Loc, LHS, RHS);
12276 }
12277 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12278 }
12279
12280 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12281 RHS.get()->getType()->isSveVLSBuiltinType())
12282 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12283
12284 // Shifts don't perform usual arithmetic conversions, they just do integer
12285 // promotions on each operand. C99 6.5.7p3
12286
12287 // For the LHS, do usual unary conversions, but then reset them away
12288 // if this is a compound assignment.
12289 ExprResult OldLHS = LHS;
12290 LHS = UsualUnaryConversions(LHS.get());
12291 if (LHS.isInvalid())
12292 return QualType();
12293 QualType LHSType = LHS.get()->getType();
12294 if (IsCompAssign) LHS = OldLHS;
12295
12296 // The RHS is simpler.
12297 RHS = UsualUnaryConversions(RHS.get());
12298 if (RHS.isInvalid())
12299 return QualType();
12300 QualType RHSType = RHS.get()->getType();
12301
12302 // C99 6.5.7p2: Each of the operands shall have integer type.
12303 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12304 if ((!LHSType->isFixedPointOrIntegerType() &&
12305 !LHSType->hasIntegerRepresentation()) ||
12306 !RHSType->hasIntegerRepresentation()) {
12307 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12308 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
12309 return ResultTy;
12310 }
12311
12312 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12313
12314 // "The type of the result is that of the promoted left operand."
12315 return LHSType;
12316}
12317
12318/// Diagnose bad pointer comparisons.
12320 ExprResult &LHS, ExprResult &RHS,
12321 bool IsError) {
12322 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12323 : diag::ext_typecheck_comparison_of_distinct_pointers)
12324 << LHS.get()->getType() << RHS.get()->getType()
12325 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12326}
12327
12328/// Returns false if the pointers are converted to a composite type,
12329/// true otherwise.
12331 ExprResult &LHS, ExprResult &RHS) {
12332 // C++ [expr.rel]p2:
12333 // [...] Pointer conversions (4.10) and qualification
12334 // conversions (4.4) are performed on pointer operands (or on
12335 // a pointer operand and a null pointer constant) to bring
12336 // them to their composite pointer type. [...]
12337 //
12338 // C++ [expr.eq]p1 uses the same notion for (in)equality
12339 // comparisons of pointers.
12340
12341 QualType LHSType = LHS.get()->getType();
12342 QualType RHSType = RHS.get()->getType();
12343 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12344 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12345
12346 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12347 if (T.isNull()) {
12348 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12349 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12350 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12351 else
12352 S.InvalidOperands(Loc, LHS, RHS);
12353 return true;
12354 }
12355
12356 return false;
12357}
12358
12360 ExprResult &LHS,
12361 ExprResult &RHS,
12362 bool IsError) {
12363 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12364 : diag::ext_typecheck_comparison_of_fptr_to_void)
12365 << LHS.get()->getType() << RHS.get()->getType()
12366 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12367}
12368
12370 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12371 case Stmt::ObjCArrayLiteralClass:
12372 case Stmt::ObjCDictionaryLiteralClass:
12373 case Stmt::ObjCStringLiteralClass:
12374 case Stmt::ObjCBoxedExprClass:
12375 return true;
12376 default:
12377 // Note that ObjCBoolLiteral is NOT an object literal!
12378 return false;
12379 }
12380}
12381
12382static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12385
12386 // If this is not actually an Objective-C object, bail out.
12387 if (!Type)
12388 return false;
12389
12390 // Get the LHS object's interface type.
12391 QualType InterfaceType = Type->getPointeeType();
12392
12393 // If the RHS isn't an Objective-C object, bail out.
12394 if (!RHS->getType()->isObjCObjectPointerType())
12395 return false;
12396
12397 // Try to find the -isEqual: method.
12398 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12399 ObjCMethodDecl *Method =
12400 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
12401 /*IsInstance=*/true);
12402 if (!Method) {
12403 if (Type->isObjCIdType()) {
12404 // For 'id', just check the global pool.
12405 Method =
12407 /*receiverId=*/true);
12408 } else {
12409 // Check protocols.
12410 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
12411 /*IsInstance=*/true);
12412 }
12413 }
12414
12415 if (!Method)
12416 return false;
12417
12418 QualType T = Method->parameters()[0]->getType();
12419 if (!T->isObjCObjectPointerType())
12420 return false;
12421
12422 QualType R = Method->getReturnType();
12423 if (!R->isScalarType())
12424 return false;
12425
12426 return true;
12427}
12428
12430 ExprResult &LHS, ExprResult &RHS,
12432 Expr *Literal;
12433 Expr *Other;
12434 if (isObjCObjectLiteral(LHS)) {
12435 Literal = LHS.get();
12436 Other = RHS.get();
12437 } else {
12438 Literal = RHS.get();
12439 Other = LHS.get();
12440 }
12441
12442 // Don't warn on comparisons against nil.
12443 Other = Other->IgnoreParenCasts();
12444 if (Other->isNullPointerConstant(S.getASTContext(),
12446 return;
12447
12448 // This should be kept in sync with warn_objc_literal_comparison.
12449 // LK_String should always be after the other literals, since it has its own
12450 // warning flag.
12451 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
12452 assert(LiteralKind != SemaObjC::LK_Block);
12453 if (LiteralKind == SemaObjC::LK_None) {
12454 llvm_unreachable("Unknown Objective-C object literal kind");
12455 }
12456
12457 if (LiteralKind == SemaObjC::LK_String)
12458 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12459 << Literal->getSourceRange();
12460 else
12461 S.Diag(Loc, diag::warn_objc_literal_comparison)
12462 << LiteralKind << Literal->getSourceRange();
12463
12465 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12466 SourceLocation Start = LHS.get()->getBeginLoc();
12468 CharSourceRange OpRange =
12470
12471 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12472 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12473 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12474 << FixItHint::CreateInsertion(End, "]");
12475 }
12476}
12477
12478/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12480 ExprResult &RHS, SourceLocation Loc,
12481 BinaryOperatorKind Opc) {
12482 // Check that left hand side is !something.
12483 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12484 if (!UO || UO->getOpcode() != UO_LNot) return;
12485
12486 // Only check if the right hand side is non-bool arithmetic type.
12487 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12488
12489 // Make sure that the something in !something is not bool.
12490 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12491 if (SubExpr->isKnownToHaveBooleanValue()) return;
12492
12493 // Emit warning.
12494 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12495 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12496 << Loc << IsBitwiseOp;
12497
12498 // First note suggest !(x < y)
12499 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12500 SourceLocation FirstClose = RHS.get()->getEndLoc();
12501 FirstClose = S.getLocForEndOfToken(FirstClose);
12502 if (FirstClose.isInvalid())
12503 FirstOpen = SourceLocation();
12504 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12505 << IsBitwiseOp
12506 << FixItHint::CreateInsertion(FirstOpen, "(")
12507 << FixItHint::CreateInsertion(FirstClose, ")");
12508
12509 // Second note suggests (!x) < y
12510 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12511 SourceLocation SecondClose = LHS.get()->getEndLoc();
12512 SecondClose = S.getLocForEndOfToken(SecondClose);
12513 if (SecondClose.isInvalid())
12514 SecondOpen = SourceLocation();
12515 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12516 << FixItHint::CreateInsertion(SecondOpen, "(")
12517 << FixItHint::CreateInsertion(SecondClose, ")");
12518}
12519
12520// Returns true if E refers to a non-weak array.
12521static bool checkForArray(const Expr *E) {
12522 const ValueDecl *D = nullptr;
12523 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12524 D = DR->getDecl();
12525 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12526 if (Mem->isImplicitAccess())
12527 D = Mem->getMemberDecl();
12528 }
12529 if (!D)
12530 return false;
12531 return D->getType()->isArrayType() && !D->isWeak();
12532}
12533
12534/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12535/// pointer and size is an unsigned integer. Return whether the result is
12536/// always true/false.
12537static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12538 const Expr *RHS,
12539 BinaryOperatorKind Opc) {
12540 if (!LHS->getType()->isPointerType() ||
12541 S.getLangOpts().PointerOverflowDefined)
12542 return std::nullopt;
12543
12544 // Canonicalize to >= or < predicate.
12545 switch (Opc) {
12546 case BO_GE:
12547 case BO_LT:
12548 break;
12549 case BO_GT:
12550 std::swap(LHS, RHS);
12551 Opc = BO_LT;
12552 break;
12553 case BO_LE:
12554 std::swap(LHS, RHS);
12555 Opc = BO_GE;
12556 break;
12557 default:
12558 return std::nullopt;
12559 }
12560
12561 auto *BO = dyn_cast<BinaryOperator>(LHS);
12562 if (!BO || BO->getOpcode() != BO_Add)
12563 return std::nullopt;
12564
12565 Expr *Other;
12566 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
12567 Other = BO->getRHS();
12568 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
12569 Other = BO->getLHS();
12570 else
12571 return std::nullopt;
12572
12573 if (!Other->getType()->isUnsignedIntegerType())
12574 return std::nullopt;
12575
12576 return Opc == BO_GE;
12577}
12578
12579/// Diagnose some forms of syntactically-obvious tautological comparison.
12581 Expr *LHS, Expr *RHS,
12582 BinaryOperatorKind Opc) {
12583 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12584 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12585
12586 QualType LHSType = LHS->getType();
12587 QualType RHSType = RHS->getType();
12588 if (LHSType->hasFloatingRepresentation() ||
12589 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12591 return;
12592
12593 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12594 // Tautological diagnostics.
12595 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12596 return;
12597
12598 // Comparisons between two array types are ill-formed for operator<=>, so
12599 // we shouldn't emit any additional warnings about it.
12600 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12601 return;
12602
12603 // For non-floating point types, check for self-comparisons of the form
12604 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12605 // often indicate logic errors in the program.
12606 //
12607 // NOTE: Don't warn about comparison expressions resulting from macro
12608 // expansion. Also don't warn about comparisons which are only self
12609 // comparisons within a template instantiation. The warnings should catch
12610 // obvious cases in the definition of the template anyways. The idea is to
12611 // warn when the typed comparison operator will always evaluate to the same
12612 // result.
12613
12614 // Used for indexing into %select in warn_comparison_always
12615 enum {
12616 AlwaysConstant,
12617 AlwaysTrue,
12618 AlwaysFalse,
12619 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12620 };
12621
12622 // C++1a [array.comp]:
12623 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12624 // operands of array type.
12625 // C++2a [depr.array.comp]:
12626 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12627 // operands of array type are deprecated.
12628 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12629 RHSStripped->getType()->isArrayType()) {
12630 auto IsDeprArrayComparionIgnored =
12631 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
12632 auto DiagID = S.getLangOpts().CPlusPlus26
12633 ? diag::warn_array_comparison_cxx26
12634 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12635 ? diag::warn_array_comparison
12636 : diag::warn_depr_array_comparison;
12637 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12638 << LHSStripped->getType() << RHSStripped->getType();
12639 // Carry on to produce the tautological comparison warning, if this
12640 // expression is potentially-evaluated, we can resolve the array to a
12641 // non-weak declaration, and so on.
12642 }
12643
12644 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12645 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12646 unsigned Result;
12647 switch (Opc) {
12648 case BO_EQ:
12649 case BO_LE:
12650 case BO_GE:
12651 Result = AlwaysTrue;
12652 break;
12653 case BO_NE:
12654 case BO_LT:
12655 case BO_GT:
12656 Result = AlwaysFalse;
12657 break;
12658 case BO_Cmp:
12659 Result = AlwaysEqual;
12660 break;
12661 default:
12662 Result = AlwaysConstant;
12663 break;
12664 }
12665 S.DiagRuntimeBehavior(Loc, nullptr,
12666 S.PDiag(diag::warn_comparison_always)
12667 << 0 /*self-comparison*/
12668 << Result);
12669 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12670 // What is it always going to evaluate to?
12671 unsigned Result;
12672 switch (Opc) {
12673 case BO_EQ: // e.g. array1 == array2
12674 Result = AlwaysFalse;
12675 break;
12676 case BO_NE: // e.g. array1 != array2
12677 Result = AlwaysTrue;
12678 break;
12679 default: // e.g. array1 <= array2
12680 // The best we can say is 'a constant'
12681 Result = AlwaysConstant;
12682 break;
12683 }
12684 S.DiagRuntimeBehavior(Loc, nullptr,
12685 S.PDiag(diag::warn_comparison_always)
12686 << 1 /*array comparison*/
12687 << Result);
12688 } else if (std::optional<bool> Res =
12689 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12690 S.DiagRuntimeBehavior(Loc, nullptr,
12691 S.PDiag(diag::warn_comparison_always)
12692 << 2 /*pointer comparison*/
12693 << (*Res ? AlwaysTrue : AlwaysFalse));
12694 }
12695 }
12696
12697 if (isa<CastExpr>(LHSStripped))
12698 LHSStripped = LHSStripped->IgnoreParenCasts();
12699 if (isa<CastExpr>(RHSStripped))
12700 RHSStripped = RHSStripped->IgnoreParenCasts();
12701
12702 // Warn about comparisons against a string constant (unless the other
12703 // operand is null); the user probably wants string comparison function.
12704 Expr *LiteralString = nullptr;
12705 Expr *LiteralStringStripped = nullptr;
12706 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12707 !RHSStripped->isNullPointerConstant(S.Context,
12709 LiteralString = LHS;
12710 LiteralStringStripped = LHSStripped;
12711 } else if ((isa<StringLiteral>(RHSStripped) ||
12712 isa<ObjCEncodeExpr>(RHSStripped)) &&
12713 !LHSStripped->isNullPointerConstant(S.Context,
12715 LiteralString = RHS;
12716 LiteralStringStripped = RHSStripped;
12717 }
12718
12719 if (LiteralString) {
12720 S.DiagRuntimeBehavior(Loc, nullptr,
12721 S.PDiag(diag::warn_stringcompare)
12722 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12723 << LiteralString->getSourceRange());
12724 }
12725}
12726
12728 switch (CK) {
12729 default: {
12730#ifndef NDEBUG
12731 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12732 << "\n";
12733#endif
12734 llvm_unreachable("unhandled cast kind");
12735 }
12736 case CK_UserDefinedConversion:
12737 return ICK_Identity;
12738 case CK_LValueToRValue:
12739 return ICK_Lvalue_To_Rvalue;
12740 case CK_ArrayToPointerDecay:
12741 return ICK_Array_To_Pointer;
12742 case CK_FunctionToPointerDecay:
12744 case CK_IntegralCast:
12746 case CK_FloatingCast:
12748 case CK_IntegralToFloating:
12749 case CK_FloatingToIntegral:
12750 return ICK_Floating_Integral;
12751 case CK_IntegralComplexCast:
12752 case CK_FloatingComplexCast:
12753 case CK_FloatingComplexToIntegralComplex:
12754 case CK_IntegralComplexToFloatingComplex:
12756 case CK_FloatingComplexToReal:
12757 case CK_FloatingRealToComplex:
12758 case CK_IntegralComplexToReal:
12759 case CK_IntegralRealToComplex:
12760 return ICK_Complex_Real;
12761 case CK_HLSLArrayRValue:
12762 return ICK_HLSL_Array_RValue;
12763 }
12764}
12765
12767 QualType FromType,
12768 SourceLocation Loc) {
12769 // Check for a narrowing implicit conversion.
12772 SCS.setToType(0, FromType);
12773 SCS.setToType(1, ToType);
12774 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12775 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12776
12777 APValue PreNarrowingValue;
12778 QualType PreNarrowingType;
12779 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12780 PreNarrowingType,
12781 /*IgnoreFloatToIntegralConversion*/ true)) {
12783 // Implicit conversion to a narrower type, but the expression is
12784 // value-dependent so we can't tell whether it's actually narrowing.
12785 case NK_Not_Narrowing:
12786 return false;
12787
12789 // Implicit conversion to a narrower type, and the value is not a constant
12790 // expression.
12791 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12792 << /*Constant*/ 1
12793 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12794 return true;
12795
12797 // Implicit conversion to a narrower type, and the value is not a constant
12798 // expression.
12799 case NK_Type_Narrowing:
12800 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12801 << /*Constant*/ 0 << FromType << ToType;
12802 // TODO: It's not a constant expression, but what if the user intended it
12803 // to be? Can we produce notes to help them figure out why it isn't?
12804 return true;
12805 }
12806 llvm_unreachable("unhandled case in switch");
12807}
12808
12810 ExprResult &LHS,
12811 ExprResult &RHS,
12812 SourceLocation Loc) {
12813 QualType LHSType = LHS.get()->getType();
12814 QualType RHSType = RHS.get()->getType();
12815 // Dig out the original argument type and expression before implicit casts
12816 // were applied. These are the types/expressions we need to check the
12817 // [expr.spaceship] requirements against.
12818 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12819 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12820 QualType LHSStrippedType = LHSStripped.get()->getType();
12821 QualType RHSStrippedType = RHSStripped.get()->getType();
12822
12823 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12824 // other is not, the program is ill-formed.
12825 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12826 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12827 return QualType();
12828 }
12829
12830 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12831 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12832 RHSStrippedType->isEnumeralType();
12833 if (NumEnumArgs == 1) {
12834 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12835 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12836 if (OtherTy->hasFloatingRepresentation()) {
12837 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12838 return QualType();
12839 }
12840 }
12841 if (NumEnumArgs == 2) {
12842 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12843 // type E, the operator yields the result of converting the operands
12844 // to the underlying type of E and applying <=> to the converted operands.
12845 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12846 S.InvalidOperands(Loc, LHS, RHS);
12847 return QualType();
12848 }
12849 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12850 assert(IntType->isArithmeticType());
12851
12852 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12853 // promote the boolean type, and all other promotable integer types, to
12854 // avoid this.
12855 if (S.Context.isPromotableIntegerType(IntType))
12856 IntType = S.Context.getPromotedIntegerType(IntType);
12857
12858 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12859 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12860 LHSType = RHSType = IntType;
12861 }
12862
12863 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12864 // usual arithmetic conversions are applied to the operands.
12865 QualType Type =
12867 if (LHS.isInvalid() || RHS.isInvalid())
12868 return QualType();
12869 if (Type.isNull()) {
12870 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12871 diagnoseScopedEnums(S, Loc, LHS, RHS, BO_Cmp);
12872 return ResultTy;
12873 }
12874
12875 std::optional<ComparisonCategoryType> CCT =
12877 if (!CCT)
12878 return S.InvalidOperands(Loc, LHS, RHS);
12879
12880 bool HasNarrowing = checkThreeWayNarrowingConversion(
12881 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12882 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12883 RHS.get()->getBeginLoc());
12884 if (HasNarrowing)
12885 return QualType();
12886
12887 assert(!Type.isNull() && "composite type for <=> has not been set");
12888
12891}
12892
12894 ExprResult &RHS,
12895 SourceLocation Loc,
12896 BinaryOperatorKind Opc) {
12897 if (Opc == BO_Cmp)
12898 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12899
12900 // C99 6.5.8p3 / C99 6.5.9p4
12901 QualType Type =
12903 if (LHS.isInvalid() || RHS.isInvalid())
12904 return QualType();
12905 if (Type.isNull()) {
12906 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12907 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12908 return ResultTy;
12909 }
12910 assert(Type->isArithmeticType() || Type->isEnumeralType());
12911
12913 return S.InvalidOperands(Loc, LHS, RHS);
12914
12915 // Check for comparisons of floating point operands using != and ==.
12917 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12918
12919 // The result of comparisons is 'bool' in C++, 'int' in C.
12921}
12922
12924 if (!NullE.get()->getType()->isAnyPointerType())
12925 return;
12926 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12927 if (!E.get()->getType()->isAnyPointerType() &&
12931 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12932 if (CL->getValue() == 0)
12933 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12934 << NullValue
12936 NullValue ? "NULL" : "(void *)0");
12937 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12938 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12939 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12940 if (T == Context.CharTy)
12941 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12942 << NullValue
12944 NullValue ? "NULL" : "(void *)0");
12945 }
12946 }
12947}
12948
12949// C99 6.5.8, C++ [expr.rel]
12951 SourceLocation Loc,
12952 BinaryOperatorKind Opc) {
12953 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12954 bool IsThreeWay = Opc == BO_Cmp;
12955 bool IsOrdered = IsRelational || IsThreeWay;
12956 auto IsAnyPointerType = [](ExprResult E) {
12957 QualType Ty = E.get()->getType();
12958 return Ty->isPointerType() || Ty->isMemberPointerType();
12959 };
12960
12961 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12962 // type, array-to-pointer, ..., conversions are performed on both operands to
12963 // bring them to their composite type.
12964 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12965 // any type-related checks.
12966 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12968 if (LHS.isInvalid())
12969 return QualType();
12971 if (RHS.isInvalid())
12972 return QualType();
12973 } else {
12974 LHS = DefaultLvalueConversion(LHS.get());
12975 if (LHS.isInvalid())
12976 return QualType();
12977 RHS = DefaultLvalueConversion(RHS.get());
12978 if (RHS.isInvalid())
12979 return QualType();
12980 }
12981
12982 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12986 }
12987
12988 // Handle vector comparisons separately.
12989 if (LHS.get()->getType()->isVectorType() ||
12990 RHS.get()->getType()->isVectorType())
12991 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12992
12993 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12994 RHS.get()->getType()->isSveVLSBuiltinType())
12995 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12996
12997 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12998 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12999
13000 QualType LHSType = LHS.get()->getType();
13001 QualType RHSType = RHS.get()->getType();
13002 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
13003 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
13004 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
13005
13006 if ((LHSType->isPointerType() &&
13008 (RHSType->isPointerType() &&
13010 return InvalidOperands(Loc, LHS, RHS);
13011
13012 const Expr::NullPointerConstantKind LHSNullKind =
13014 const Expr::NullPointerConstantKind RHSNullKind =
13016 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
13017 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
13018
13019 auto computeResultTy = [&]() {
13020 if (Opc != BO_Cmp)
13021 return QualType(Context.getLogicalOperationType());
13022 assert(getLangOpts().CPlusPlus);
13023 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
13024
13025 QualType CompositeTy = LHS.get()->getType();
13026 assert(!CompositeTy->isReferenceType());
13027
13028 std::optional<ComparisonCategoryType> CCT =
13030 if (!CCT)
13031 return InvalidOperands(Loc, LHS, RHS);
13032
13033 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
13034 // P0946R0: Comparisons between a null pointer constant and an object
13035 // pointer result in std::strong_equality, which is ill-formed under
13036 // P1959R0.
13037 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
13038 << (LHSIsNull ? LHS.get()->getSourceRange()
13039 : RHS.get()->getSourceRange());
13040 return QualType();
13041 }
13042
13045 };
13046
13047 if (!IsOrdered && LHSIsNull != RHSIsNull) {
13048 bool IsEquality = Opc == BO_EQ;
13049 if (RHSIsNull)
13050 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
13051 RHS.get()->getSourceRange());
13052 else
13053 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
13054 LHS.get()->getSourceRange());
13055 }
13056
13057 if (IsOrdered && LHSType->isFunctionPointerType() &&
13058 RHSType->isFunctionPointerType()) {
13059 // Valid unless a relational comparison of function pointers
13060 bool IsError = Opc == BO_Cmp;
13061 auto DiagID =
13062 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13063 : getLangOpts().CPlusPlus
13064 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13065 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13066 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13067 << RHS.get()->getSourceRange();
13068 if (IsError)
13069 return QualType();
13070 }
13071
13072 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13073 (RHSType->isIntegerType() && !RHSIsNull)) {
13074 // Skip normal pointer conversion checks in this case; we have better
13075 // diagnostics for this below.
13076 } else if (getLangOpts().CPlusPlus) {
13077 // Equality comparison of a function pointer to a void pointer is invalid,
13078 // but we allow it as an extension.
13079 // FIXME: If we really want to allow this, should it be part of composite
13080 // pointer type computation so it works in conditionals too?
13081 if (!IsOrdered &&
13082 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13083 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13084 // This is a gcc extension compatibility comparison.
13085 // In a SFINAE context, we treat this as a hard error to maintain
13086 // conformance with the C++ standard.
13087 bool IsError = isSFINAEContext();
13088 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, IsError);
13089
13090 if (IsError)
13091 return QualType();
13092
13093 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13094 return computeResultTy();
13095 }
13096
13097 // C++ [expr.eq]p2:
13098 // If at least one operand is a pointer [...] bring them to their
13099 // composite pointer type.
13100 // C++ [expr.spaceship]p6
13101 // If at least one of the operands is of pointer type, [...] bring them
13102 // to their composite pointer type.
13103 // C++ [expr.rel]p2:
13104 // If both operands are pointers, [...] bring them to their composite
13105 // pointer type.
13106 // For <=>, the only valid non-pointer types are arrays and functions, and
13107 // we already decayed those, so this is really the same as the relational
13108 // comparison rule.
13109 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13110 (IsOrdered ? 2 : 1) &&
13111 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13112 RHSType->isObjCObjectPointerType()))) {
13113 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13114 return QualType();
13115 return computeResultTy();
13116 }
13117 } else if (LHSType->isPointerType() &&
13118 RHSType->isPointerType()) { // C99 6.5.8p2
13119 // All of the following pointer-related warnings are GCC extensions, except
13120 // when handling null pointer constants.
13121 QualType LCanPointeeTy =
13123 QualType RCanPointeeTy =
13125
13126 // C99 6.5.9p2 and C99 6.5.8p2
13127 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
13128 RCanPointeeTy.getUnqualifiedType())) {
13129 if (IsRelational) {
13130 // Pointers both need to point to complete or incomplete types
13131 if ((LCanPointeeTy->isIncompleteType() !=
13132 RCanPointeeTy->isIncompleteType()) &&
13133 !getLangOpts().C11) {
13134 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
13135 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13136 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13137 << RCanPointeeTy->isIncompleteType();
13138 }
13139 }
13140 } else if (!IsRelational &&
13141 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13142 // Valid unless comparison between non-null pointer and function pointer
13143 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13144 && !LHSIsNull && !RHSIsNull)
13145 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
13146 /*isError*/false);
13147 } else {
13148 // Invalid
13149 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
13150 }
13151 if (LCanPointeeTy != RCanPointeeTy) {
13152 // Treat NULL constant as a special case in OpenCL.
13153 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13154 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
13155 getASTContext())) {
13156 Diag(Loc,
13157 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13158 << LHSType << RHSType << 0 /* comparison */
13159 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13160 }
13161 }
13162 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13163 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13164 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13165 : CK_BitCast;
13166
13167 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13168 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13169 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13170 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13171 bool ChangingCFIUncheckedCallee =
13172 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13173
13174 if (LHSIsNull && !RHSIsNull)
13175 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
13176 else if (!ChangingCFIUncheckedCallee)
13177 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
13178 }
13179 return computeResultTy();
13180 }
13181
13182
13183 // C++ [expr.eq]p4:
13184 // Two operands of type std::nullptr_t or one operand of type
13185 // std::nullptr_t and the other a null pointer constant compare
13186 // equal.
13187 // C23 6.5.9p5:
13188 // If both operands have type nullptr_t or one operand has type nullptr_t
13189 // and the other is a null pointer constant, they compare equal if the
13190 // former is a null pointer.
13191 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13192 if (LHSType->isNullPtrType()) {
13193 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13194 return computeResultTy();
13195 }
13196 if (RHSType->isNullPtrType()) {
13197 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13198 return computeResultTy();
13199 }
13200 }
13201
13202 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13203 // C23 6.5.9p6:
13204 // Otherwise, at least one operand is a pointer. If one is a pointer and
13205 // the other is a null pointer constant or has type nullptr_t, they
13206 // compare equal
13207 if (LHSIsNull && RHSType->isPointerType()) {
13208 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13209 return computeResultTy();
13210 }
13211 if (RHSIsNull && LHSType->isPointerType()) {
13212 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13213 return computeResultTy();
13214 }
13215 }
13216
13217 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13218 // These aren't covered by the composite pointer type rules.
13219 if (!IsOrdered && RHSType->isNullPtrType() &&
13220 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13221 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13222 return computeResultTy();
13223 }
13224 if (!IsOrdered && LHSType->isNullPtrType() &&
13225 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13226 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13227 return computeResultTy();
13228 }
13229
13230 if (getLangOpts().CPlusPlus) {
13231 if (IsRelational &&
13232 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13233 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13234 // HACK: Relational comparison of nullptr_t against a pointer type is
13235 // invalid per DR583, but we allow it within std::less<> and friends,
13236 // since otherwise common uses of it break.
13237 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13238 // friends to have std::nullptr_t overload candidates.
13239 DeclContext *DC = CurContext;
13240 if (isa<FunctionDecl>(DC))
13241 DC = DC->getParent();
13242 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
13243 if (CTSD->isInStdNamespace() &&
13244 llvm::StringSwitch<bool>(CTSD->getName())
13245 .Cases({"less", "less_equal", "greater", "greater_equal"}, true)
13246 .Default(false)) {
13247 if (RHSType->isNullPtrType())
13248 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13249 else
13250 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13251 return computeResultTy();
13252 }
13253 }
13254 }
13255
13256 // C++ [expr.eq]p2:
13257 // If at least one operand is a pointer to member, [...] bring them to
13258 // their composite pointer type.
13259 if (!IsOrdered &&
13260 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13261 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13262 return QualType();
13263 else
13264 return computeResultTy();
13265 }
13266 }
13267
13268 // Handle block pointer types.
13269 if (!IsOrdered && LHSType->isBlockPointerType() &&
13270 RHSType->isBlockPointerType()) {
13271 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13272 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13273
13274 if (!LHSIsNull && !RHSIsNull &&
13275 !Context.typesAreCompatible(lpointee, rpointee)) {
13276 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13277 << LHSType << RHSType << LHS.get()->getSourceRange()
13278 << RHS.get()->getSourceRange();
13279 }
13280 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13281 return computeResultTy();
13282 }
13283
13284 // Allow block pointers to be compared with null pointer constants.
13285 if (!IsOrdered
13286 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13287 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13288 if (!LHSIsNull && !RHSIsNull) {
13289 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13291 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13292 ->getPointeeType()->isVoidType())))
13293 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13294 << LHSType << RHSType << LHS.get()->getSourceRange()
13295 << RHS.get()->getSourceRange();
13296 }
13297 if (LHSIsNull && !RHSIsNull)
13298 LHS = ImpCastExprToType(LHS.get(), RHSType,
13299 RHSType->isPointerType() ? CK_BitCast
13300 : CK_AnyPointerToBlockPointerCast);
13301 else
13302 RHS = ImpCastExprToType(RHS.get(), LHSType,
13303 LHSType->isPointerType() ? CK_BitCast
13304 : CK_AnyPointerToBlockPointerCast);
13305 return computeResultTy();
13306 }
13307
13308 if (LHSType->isObjCObjectPointerType() ||
13309 RHSType->isObjCObjectPointerType()) {
13310 const PointerType *LPT = LHSType->getAs<PointerType>();
13311 const PointerType *RPT = RHSType->getAs<PointerType>();
13312 if (LPT || RPT) {
13313 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13314 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13315
13316 if (!LPtrToVoid && !RPtrToVoid &&
13317 !Context.typesAreCompatible(LHSType, RHSType)) {
13318 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13319 /*isError*/false);
13320 }
13321 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13322 // the RHS, but we have test coverage for this behavior.
13323 // FIXME: Consider using convertPointersToCompositeType in C++.
13324 if (LHSIsNull && !RHSIsNull) {
13325 Expr *E = LHS.get();
13326 if (getLangOpts().ObjCAutoRefCount)
13327 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
13329 LHS = ImpCastExprToType(E, RHSType,
13330 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13331 }
13332 else {
13333 Expr *E = RHS.get();
13334 if (getLangOpts().ObjCAutoRefCount)
13335 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
13337 /*Diagnose=*/true,
13338 /*DiagnoseCFAudited=*/false, Opc);
13339 RHS = ImpCastExprToType(E, LHSType,
13340 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13341 }
13342 return computeResultTy();
13343 }
13344 if (LHSType->isObjCObjectPointerType() &&
13345 RHSType->isObjCObjectPointerType()) {
13346 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13347 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13348 /*isError*/false);
13350 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13351
13352 if (LHSIsNull && !RHSIsNull)
13353 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13354 else
13355 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13356 return computeResultTy();
13357 }
13358
13359 if (!IsOrdered && LHSType->isBlockPointerType() &&
13361 LHS = ImpCastExprToType(LHS.get(), RHSType,
13362 CK_BlockPointerToObjCPointerCast);
13363 return computeResultTy();
13364 } else if (!IsOrdered &&
13366 RHSType->isBlockPointerType()) {
13367 RHS = ImpCastExprToType(RHS.get(), LHSType,
13368 CK_BlockPointerToObjCPointerCast);
13369 return computeResultTy();
13370 }
13371 }
13372 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13373 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13374 unsigned DiagID = 0;
13375 bool isError = false;
13376 if (LangOpts.DebuggerSupport) {
13377 // Under a debugger, allow the comparison of pointers to integers,
13378 // since users tend to want to compare addresses.
13379 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13380 (RHSIsNull && RHSType->isIntegerType())) {
13381 if (IsOrdered) {
13382 isError = getLangOpts().CPlusPlus;
13383 DiagID =
13384 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13385 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13386 }
13387 } else if (getLangOpts().CPlusPlus) {
13388 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13389 isError = true;
13390 } else if (IsOrdered)
13391 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13392 else
13393 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13394
13395 if (DiagID) {
13396 Diag(Loc, DiagID)
13397 << LHSType << RHSType << LHS.get()->getSourceRange()
13398 << RHS.get()->getSourceRange();
13399 if (isError)
13400 return QualType();
13401 }
13402
13403 if (LHSType->isIntegerType())
13404 LHS = ImpCastExprToType(LHS.get(), RHSType,
13405 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13406 else
13407 RHS = ImpCastExprToType(RHS.get(), LHSType,
13408 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13409 return computeResultTy();
13410 }
13411
13412 // Handle block pointers.
13413 if (!IsOrdered && RHSIsNull
13414 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13415 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13416 return computeResultTy();
13417 }
13418 if (!IsOrdered && LHSIsNull
13419 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13420 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13421 return computeResultTy();
13422 }
13423
13424 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13425 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13426 return computeResultTy();
13427 }
13428
13429 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13430 return computeResultTy();
13431 }
13432
13433 if (LHSIsNull && RHSType->isQueueT()) {
13434 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13435 return computeResultTy();
13436 }
13437
13438 if (LHSType->isQueueT() && RHSIsNull) {
13439 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13440 return computeResultTy();
13441 }
13442 }
13443
13444 return InvalidOperands(Loc, LHS, RHS);
13445}
13446
13448 const VectorType *VTy = V->castAs<VectorType>();
13449 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13450
13451 if (isa<ExtVectorType>(VTy)) {
13452 if (VTy->isExtVectorBoolType())
13453 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13454 if (TypeSize == Context.getTypeSize(Context.CharTy))
13455 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13456 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13457 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13458 if (TypeSize == Context.getTypeSize(Context.IntTy))
13459 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13460 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13461 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13462 if (TypeSize == Context.getTypeSize(Context.LongTy))
13463 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13464 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13465 "Unhandled vector element size in vector compare");
13466 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13467 }
13468
13469 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13470 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13472 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13473 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13475 if (TypeSize == Context.getTypeSize(Context.LongTy))
13476 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13478 if (TypeSize == Context.getTypeSize(Context.IntTy))
13479 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13481 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13482 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13484 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13485 "Unhandled vector element size in vector compare");
13486 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13488}
13489
13491 const BuiltinType *VTy = V->castAs<BuiltinType>();
13492 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13493
13494 const QualType ETy = V->getSveEltType(Context);
13495 const auto TypeSize = Context.getTypeSize(ETy);
13496
13497 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13498 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13499 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13500}
13501
13503 SourceLocation Loc,
13504 BinaryOperatorKind Opc) {
13505 if (Opc == BO_Cmp) {
13506 Diag(Loc, diag::err_three_way_vector_comparison);
13507 return QualType();
13508 }
13509
13510 // Check to make sure we're operating on vectors of the same type and width,
13511 // Allowing one side to be a scalar of element type.
13512 QualType vType =
13513 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13514 /*AllowBothBool*/ true,
13515 /*AllowBoolConversions*/ getLangOpts().ZVector,
13516 /*AllowBooleanOperation*/ true,
13517 /*ReportInvalid*/ true);
13518 if (vType.isNull())
13519 return vType;
13520
13521 QualType LHSType = LHS.get()->getType();
13522
13523 // Determine the return type of a vector compare. By default clang will return
13524 // a scalar for all vector compares except vector bool and vector pixel.
13525 // With the gcc compiler we will always return a vector type and with the xl
13526 // compiler we will always return a scalar type. This switch allows choosing
13527 // which behavior is prefered.
13528 if (getLangOpts().AltiVec) {
13529 switch (getLangOpts().getAltivecSrcCompat()) {
13531 // If AltiVec, the comparison results in a numeric type, i.e.
13532 // bool for C++, int for C
13533 if (vType->castAs<VectorType>()->getVectorKind() ==
13535 return Context.getLogicalOperationType();
13536 else
13537 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13538 break;
13540 // For GCC we always return the vector type.
13541 break;
13543 return Context.getLogicalOperationType();
13544 break;
13545 }
13546 }
13547
13548 // For non-floating point types, check for self-comparisons of the form
13549 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13550 // often indicate logic errors in the program.
13551 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13552
13553 // Check for comparisons of floating point operands using != and ==.
13554 if (LHSType->hasFloatingRepresentation()) {
13555 assert(RHS.get()->getType()->hasFloatingRepresentation());
13556 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13557 }
13558
13559 // Return a signed type for the vector.
13560 return GetSignedVectorType(vType);
13561}
13562
13564 ExprResult &RHS,
13565 SourceLocation Loc,
13566 BinaryOperatorKind Opc) {
13567 if (Opc == BO_Cmp) {
13568 Diag(Loc, diag::err_three_way_vector_comparison);
13569 return QualType();
13570 }
13571
13572 // Check to make sure we're operating on vectors of the same type and width,
13573 // Allowing one side to be a scalar of element type.
13575 LHS, RHS, Loc, /*isCompAssign*/ false, ArithConvKind::Comparison);
13576
13577 if (vType.isNull())
13578 return vType;
13579
13580 QualType LHSType = LHS.get()->getType();
13581
13582 // For non-floating point types, check for self-comparisons of the form
13583 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13584 // often indicate logic errors in the program.
13585 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13586
13587 // Check for comparisons of floating point operands using != and ==.
13588 if (LHSType->hasFloatingRepresentation()) {
13589 assert(RHS.get()->getType()->hasFloatingRepresentation());
13590 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13591 }
13592
13593 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13594 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13595
13596 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13597 RHSBuiltinTy->isSVEBool())
13598 return LHSType;
13599
13600 // Return a signed type for the vector.
13601 return GetSignedSizelessVectorType(vType);
13602}
13603
13604static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13605 const ExprResult &XorRHS,
13606 const SourceLocation Loc) {
13607 // Do not diagnose macros.
13608 if (Loc.isMacroID())
13609 return;
13610
13611 // Do not diagnose if both LHS and RHS are macros.
13612 if (XorLHS.get()->getExprLoc().isMacroID() &&
13613 XorRHS.get()->getExprLoc().isMacroID())
13614 return;
13615
13616 bool Negative = false;
13617 bool ExplicitPlus = false;
13618 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13619 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13620
13621 if (!LHSInt)
13622 return;
13623 if (!RHSInt) {
13624 // Check negative literals.
13625 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13626 UnaryOperatorKind Opc = UO->getOpcode();
13627 if (Opc != UO_Minus && Opc != UO_Plus)
13628 return;
13629 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13630 if (!RHSInt)
13631 return;
13632 Negative = (Opc == UO_Minus);
13633 ExplicitPlus = !Negative;
13634 } else {
13635 return;
13636 }
13637 }
13638
13639 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13640 llvm::APInt RightSideValue = RHSInt->getValue();
13641 if (LeftSideValue != 2 && LeftSideValue != 10)
13642 return;
13643
13644 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13645 return;
13646
13648 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13649 llvm::StringRef ExprStr =
13651
13652 CharSourceRange XorRange =
13654 llvm::StringRef XorStr =
13656 // Do not diagnose if xor keyword/macro is used.
13657 if (XorStr == "xor")
13658 return;
13659
13660 std::string LHSStr = std::string(Lexer::getSourceText(
13661 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13662 S.getSourceManager(), S.getLangOpts()));
13663 std::string RHSStr = std::string(Lexer::getSourceText(
13664 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13665 S.getSourceManager(), S.getLangOpts()));
13666
13667 if (Negative) {
13668 RightSideValue = -RightSideValue;
13669 RHSStr = "-" + RHSStr;
13670 } else if (ExplicitPlus) {
13671 RHSStr = "+" + RHSStr;
13672 }
13673
13674 StringRef LHSStrRef = LHSStr;
13675 StringRef RHSStrRef = RHSStr;
13676 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13677 // literals.
13678 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13679 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13680 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13681 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13682 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13683 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13684 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13685 return;
13686
13687 bool SuggestXor =
13688 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13689 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13690 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13691 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13692 std::string SuggestedExpr = "1 << " + RHSStr;
13693 bool Overflow = false;
13694 llvm::APInt One = (LeftSideValue - 1);
13695 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13696 if (Overflow) {
13697 if (RightSideIntValue < 64)
13698 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13699 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13700 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13701 else if (RightSideIntValue == 64)
13702 S.Diag(Loc, diag::warn_xor_used_as_pow)
13703 << ExprStr << toString(XorValue, 10, true);
13704 else
13705 return;
13706 } else {
13707 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13708 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13709 << toString(PowValue, 10, true)
13711 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13712 }
13713
13714 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13715 << ("0x2 ^ " + RHSStr) << SuggestXor;
13716 } else if (LeftSideValue == 10) {
13717 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13718 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13719 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13720 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13721 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13722 << ("0xA ^ " + RHSStr) << SuggestXor;
13723 }
13724}
13725
13727 SourceLocation Loc,
13728 BinaryOperatorKind Opc) {
13729 // Ensure that either both operands are of the same vector type, or
13730 // one operand is of a vector type and the other is of its element type.
13731 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13732 /*AllowBothBool*/ true,
13733 /*AllowBoolConversions*/ false,
13734 /*AllowBooleanOperation*/ false,
13735 /*ReportInvalid*/ false);
13736 if (vType.isNull())
13737 return InvalidOperands(Loc, LHS, RHS);
13738 if (getLangOpts().OpenCL &&
13739 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13741 return InvalidOperands(Loc, LHS, RHS);
13742 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13743 // usage of the logical operators && and || with vectors in C. This
13744 // check could be notionally dropped.
13745 if (!getLangOpts().CPlusPlus &&
13746 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13747 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13748 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13749 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13750 // `select` functions.
13751 if (getLangOpts().HLSL &&
13752 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13753 (void)InvalidOperands(Loc, LHS, RHS);
13754 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13755 return QualType();
13756 }
13757
13758 return GetSignedVectorType(LHS.get()->getType());
13759}
13760
13762 SourceLocation Loc,
13763 BinaryOperatorKind Opc) {
13764
13765 if (!getLangOpts().HLSL) {
13766 assert(false && "Logical operands are not supported in C\\C++");
13767 return QualType();
13768 }
13769
13770 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13771 (void)InvalidOperands(Loc, LHS, RHS);
13772 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13773 return QualType();
13774 }
13775 SemaRef.Diag(LHS.get()->getBeginLoc(), diag::err_hlsl_langstd_unimplemented)
13776 << getLangOpts().getHLSLVersion();
13777 return QualType();
13778}
13779
13781 SourceLocation Loc,
13782 bool IsCompAssign) {
13783 if (!IsCompAssign) {
13785 if (LHS.isInvalid())
13786 return QualType();
13787 }
13789 if (RHS.isInvalid())
13790 return QualType();
13791
13792 // For conversion purposes, we ignore any qualifiers.
13793 // For example, "const float" and "float" are equivalent.
13794 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13795 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13796
13797 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13798 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13799 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13800
13801 if (Context.hasSameType(LHSType, RHSType))
13802 return Context.getCommonSugaredType(LHSType, RHSType);
13803
13804 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13805 // case we have to return InvalidOperands.
13806 ExprResult OriginalLHS = LHS;
13807 ExprResult OriginalRHS = RHS;
13808 if (LHSMatType && !RHSMatType) {
13809 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13810 if (!RHS.isInvalid())
13811 return LHSType;
13812
13813 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13814 }
13815
13816 if (!LHSMatType && RHSMatType) {
13817 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13818 if (!LHS.isInvalid())
13819 return RHSType;
13820 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13821 }
13822
13823 return InvalidOperands(Loc, LHS, RHS);
13824}
13825
13827 SourceLocation Loc,
13828 bool IsCompAssign) {
13829 if (!IsCompAssign) {
13831 if (LHS.isInvalid())
13832 return QualType();
13833 }
13835 if (RHS.isInvalid())
13836 return QualType();
13837
13838 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13839 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13840 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13841
13842 if (LHSMatType && RHSMatType) {
13843 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13844 return InvalidOperands(Loc, LHS, RHS);
13845
13846 if (Context.hasSameType(LHSMatType, RHSMatType))
13847 return Context.getCommonSugaredType(
13848 LHS.get()->getType().getUnqualifiedType(),
13849 RHS.get()->getType().getUnqualifiedType());
13850
13851 QualType LHSELTy = LHSMatType->getElementType(),
13852 RHSELTy = RHSMatType->getElementType();
13853 if (!Context.hasSameType(LHSELTy, RHSELTy))
13854 return InvalidOperands(Loc, LHS, RHS);
13855
13856 return Context.getConstantMatrixType(
13857 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13858 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13859 }
13860 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13861}
13862
13864 switch (Opc) {
13865 default:
13866 return false;
13867 case BO_And:
13868 case BO_AndAssign:
13869 case BO_Or:
13870 case BO_OrAssign:
13871 case BO_Xor:
13872 case BO_XorAssign:
13873 return true;
13874 }
13875}
13876
13878 SourceLocation Loc,
13879 BinaryOperatorKind Opc) {
13880 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13881
13882 bool IsCompAssign =
13883 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13884
13885 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13886
13887 if (LHS.get()->getType()->isVectorType() ||
13888 RHS.get()->getType()->isVectorType()) {
13889 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13891 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13892 /*AllowBothBool*/ true,
13893 /*AllowBoolConversions*/ getLangOpts().ZVector,
13894 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13895 /*ReportInvalid*/ true);
13896 return InvalidOperands(Loc, LHS, RHS);
13897 }
13898
13899 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13900 RHS.get()->getType()->isSveVLSBuiltinType()) {
13901 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13903 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13905 return InvalidOperands(Loc, LHS, RHS);
13906 }
13907
13908 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13909 RHS.get()->getType()->isSveVLSBuiltinType()) {
13910 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13912 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13914 return InvalidOperands(Loc, LHS, RHS);
13915 }
13916
13917 if (Opc == BO_And)
13918 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13919
13920 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13922 return InvalidOperands(Loc, LHS, RHS);
13923
13924 ExprResult LHSResult = LHS, RHSResult = RHS;
13926 LHSResult, RHSResult, Loc,
13928 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13929 return QualType();
13930 LHS = LHSResult.get();
13931 RHS = RHSResult.get();
13932
13933 if (Opc == BO_Xor)
13934 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13935
13936 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13937 return compType;
13938 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13939 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13940 return ResultTy;
13941}
13942
13943// C99 6.5.[13,14]
13945 SourceLocation Loc,
13946 BinaryOperatorKind Opc) {
13947 // Check vector operands differently.
13948 if (LHS.get()->getType()->isVectorType() ||
13949 RHS.get()->getType()->isVectorType())
13950 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13951
13952 if (LHS.get()->getType()->isConstantMatrixType() ||
13953 RHS.get()->getType()->isConstantMatrixType())
13954 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
13955
13956 bool EnumConstantInBoolContext = false;
13957 for (const ExprResult &HS : {LHS, RHS}) {
13958 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13959 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13960 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13961 EnumConstantInBoolContext = true;
13962 }
13963 }
13964
13965 if (EnumConstantInBoolContext)
13966 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13967
13968 // WebAssembly tables can't be used with logical operators.
13969 QualType LHSTy = LHS.get()->getType();
13970 QualType RHSTy = RHS.get()->getType();
13971 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13972 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13973 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13974 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13975 return InvalidOperands(Loc, LHS, RHS);
13976 }
13977
13978 // Diagnose cases where the user write a logical and/or but probably meant a
13979 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13980 // is a constant.
13981 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13982 !LHS.get()->getType()->isBooleanType() &&
13983 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13984 // Don't warn in macros or template instantiations.
13985 !Loc.isMacroID() && !inTemplateInstantiation()) {
13986 // If the RHS can be constant folded, and if it constant folds to something
13987 // that isn't 0 or 1 (which indicate a potential logical operation that
13988 // happened to fold to true/false) then warn.
13989 // Parens on the RHS are ignored.
13990 Expr::EvalResult EVResult;
13991 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13992 llvm::APSInt Result = EVResult.Val.getInt();
13993 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13994 !RHS.get()->getExprLoc().isMacroID()) ||
13995 (Result != 0 && Result != 1)) {
13996 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13997 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13998 // Suggest replacing the logical operator with the bitwise version
13999 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
14000 << (Opc == BO_LAnd ? "&" : "|")
14003 Opc == BO_LAnd ? "&" : "|");
14004 if (Opc == BO_LAnd)
14005 // Suggest replacing "Foo() && kNonZero" with "Foo()"
14006 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
14009 RHS.get()->getEndLoc()));
14010 }
14011 }
14012 }
14013
14014 if (!Context.getLangOpts().CPlusPlus) {
14015 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
14016 // not operate on the built-in scalar and vector float types.
14017 if (Context.getLangOpts().OpenCL &&
14018 Context.getLangOpts().OpenCLVersion < 120) {
14019 if (LHS.get()->getType()->isFloatingType() ||
14020 RHS.get()->getType()->isFloatingType())
14021 return InvalidOperands(Loc, LHS, RHS);
14022 }
14023
14024 LHS = UsualUnaryConversions(LHS.get());
14025 if (LHS.isInvalid())
14026 return QualType();
14027
14028 RHS = UsualUnaryConversions(RHS.get());
14029 if (RHS.isInvalid())
14030 return QualType();
14031
14032 if (LHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14034 if (RHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
14036
14037 if (!LHS.get()->getType()->isScalarType() ||
14038 !RHS.get()->getType()->isScalarType())
14039 return InvalidOperands(Loc, LHS, RHS);
14040
14041 return Context.IntTy;
14042 }
14043
14044 // The following is safe because we only use this method for
14045 // non-overloadable operands.
14046
14047 // C++ [expr.log.and]p1
14048 // C++ [expr.log.or]p1
14049 // The operands are both contextually converted to type bool.
14051 if (LHSRes.isInvalid()) {
14052 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14053 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
14054 return ResultTy;
14055 }
14056 LHS = LHSRes;
14057
14059 if (RHSRes.isInvalid()) {
14060 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14061 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
14062 return ResultTy;
14063 }
14064 RHS = RHSRes;
14065
14066 // C++ [expr.log.and]p2
14067 // C++ [expr.log.or]p2
14068 // The result is a bool.
14069 return Context.BoolTy;
14070}
14071
14072static bool IsReadonlyMessage(Expr *E, Sema &S) {
14073 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14074 if (!ME) return false;
14075 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
14076 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14078 if (!Base) return false;
14079 return Base->getMethodDecl() != nullptr;
14080}
14081
14082/// Is the given expression (which must be 'const') a reference to a
14083/// variable which was originally non-const, but which has become
14084/// 'const' due to being captured within a block?
14087 assert(E->isLValue() && E->getType().isConstQualified());
14088 E = E->IgnoreParens();
14089
14090 // Must be a reference to a declaration from an enclosing scope.
14091 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14092 if (!DRE) return NCCK_None;
14094
14095 ValueDecl *Value = DRE->getDecl();
14096
14097 // The declaration must be a value which is not declared 'const'.
14099 return NCCK_None;
14100
14101 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
14102 if (Binding) {
14103 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
14104 assert(!isa<BlockDecl>(Binding->getDeclContext()));
14105 return NCCK_Lambda;
14106 }
14107
14108 VarDecl *Var = dyn_cast<VarDecl>(Value);
14109 if (!Var)
14110 return NCCK_None;
14111 if (Var->getType()->isReferenceType())
14112 return NCCK_None;
14113
14114 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
14115
14116 // Decide whether the first capture was for a block or a lambda.
14117 DeclContext *DC = S.CurContext, *Prev = nullptr;
14118 // Decide whether the first capture was for a block or a lambda.
14119 while (DC) {
14120 // For init-capture, it is possible that the variable belongs to the
14121 // template pattern of the current context.
14122 if (auto *FD = dyn_cast<FunctionDecl>(DC))
14123 if (Var->isInitCapture() &&
14124 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
14125 break;
14126 if (DC == Var->getDeclContext())
14127 break;
14128 Prev = DC;
14129 DC = DC->getParent();
14130 }
14131 // Unless we have an init-capture, we've gone one step too far.
14132 if (!Var->isInitCapture())
14133 DC = Prev;
14134 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
14135}
14136
14137static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14138 Ty = Ty.getNonReferenceType();
14139 if (IsDereference && Ty->isPointerType())
14140 Ty = Ty->getPointeeType();
14141 return !Ty.isConstQualified();
14142}
14143
14144// Update err_typecheck_assign_const and note_typecheck_assign_const
14145// when this enum is changed.
14146enum {
14151 ConstUnknown, // Keep as last element
14152};
14153
14154/// Emit the "read-only variable not assignable" error and print notes to give
14155/// more information about why the variable is not assignable, such as pointing
14156/// to the declaration of a const variable, showing that a method is const, or
14157/// that the function is returning a const reference.
14158static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14159 SourceLocation Loc) {
14160 SourceRange ExprRange = E->getSourceRange();
14161
14162 // Only emit one error on the first const found. All other consts will emit
14163 // a note to the error.
14164 bool DiagnosticEmitted = false;
14165
14166 // Track if the current expression is the result of a dereference, and if the
14167 // next checked expression is the result of a dereference.
14168 bool IsDereference = false;
14169 bool NextIsDereference = false;
14170
14171 // Loop to process MemberExpr chains.
14172 while (true) {
14173 IsDereference = NextIsDereference;
14174
14176 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14177 NextIsDereference = ME->isArrow();
14178 const ValueDecl *VD = ME->getMemberDecl();
14179 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
14180 // Mutable fields can be modified even if the class is const.
14181 if (Field->isMutable()) {
14182 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14183 break;
14184 }
14185
14186 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
14187 if (!DiagnosticEmitted) {
14188 S.Diag(Loc, diag::err_typecheck_assign_const)
14189 << ExprRange << ConstMember << false /*static*/ << Field
14190 << Field->getType();
14191 DiagnosticEmitted = true;
14192 }
14193 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14194 << ConstMember << false /*static*/ << Field << Field->getType()
14195 << Field->getSourceRange();
14196 }
14197 E = ME->getBase();
14198 continue;
14199 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
14200 if (VDecl->getType().isConstQualified()) {
14201 if (!DiagnosticEmitted) {
14202 S.Diag(Loc, diag::err_typecheck_assign_const)
14203 << ExprRange << ConstMember << true /*static*/ << VDecl
14204 << VDecl->getType();
14205 DiagnosticEmitted = true;
14206 }
14207 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14208 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14209 << VDecl->getSourceRange();
14210 }
14211 // Static fields do not inherit constness from parents.
14212 break;
14213 }
14214 break; // End MemberExpr
14215 } else if (const ArraySubscriptExpr *ASE =
14216 dyn_cast<ArraySubscriptExpr>(E)) {
14217 E = ASE->getBase()->IgnoreParenImpCasts();
14218 continue;
14219 } else if (const ExtVectorElementExpr *EVE =
14220 dyn_cast<ExtVectorElementExpr>(E)) {
14221 E = EVE->getBase()->IgnoreParenImpCasts();
14222 continue;
14223 }
14224 break;
14225 }
14226
14227 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
14228 // Function calls
14229 const FunctionDecl *FD = CE->getDirectCallee();
14230 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
14231 if (!DiagnosticEmitted) {
14232 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14233 << ConstFunction << FD;
14234 DiagnosticEmitted = true;
14235 }
14237 diag::note_typecheck_assign_const)
14238 << ConstFunction << FD << FD->getReturnType()
14239 << FD->getReturnTypeSourceRange();
14240 }
14241 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14242 // Point to variable declaration.
14243 if (const ValueDecl *VD = DRE->getDecl()) {
14244 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
14245 if (!DiagnosticEmitted) {
14246 S.Diag(Loc, diag::err_typecheck_assign_const)
14247 << ExprRange << ConstVariable << VD << VD->getType();
14248 DiagnosticEmitted = true;
14249 }
14250 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14251 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14252 }
14253 }
14254 } else if (isa<CXXThisExpr>(E)) {
14255 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14256 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
14257 if (MD->isConst()) {
14258 if (!DiagnosticEmitted) {
14259 S.Diag(Loc, diag::err_typecheck_assign_const_method)
14260 << ExprRange << MD;
14261 DiagnosticEmitted = true;
14262 }
14263 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const_method)
14264 << MD << MD->getSourceRange();
14265 }
14266 }
14267 }
14268 }
14269
14270 if (DiagnosticEmitted)
14271 return;
14272
14273 // Can't determine a more specific message, so display the generic error.
14274 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14275}
14276
14282
14284 const RecordType *Ty,
14285 SourceLocation Loc, SourceRange Range,
14286 OriginalExprKind OEK,
14287 bool &DiagnosticEmitted) {
14288 std::vector<const RecordType *> RecordTypeList;
14289 RecordTypeList.push_back(Ty);
14290 unsigned NextToCheckIndex = 0;
14291 // We walk the record hierarchy breadth-first to ensure that we print
14292 // diagnostics in field nesting order.
14293 while (RecordTypeList.size() > NextToCheckIndex) {
14294 bool IsNested = NextToCheckIndex > 0;
14295 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14296 ->getDecl()
14297 ->getDefinitionOrSelf()
14298 ->fields()) {
14299 // First, check every field for constness.
14300 QualType FieldTy = Field->getType();
14301 if (FieldTy.isConstQualified()) {
14302 if (!DiagnosticEmitted) {
14303 S.Diag(Loc, diag::err_typecheck_assign_const)
14304 << Range << NestedConstMember << OEK << VD
14305 << IsNested << Field;
14306 DiagnosticEmitted = true;
14307 }
14308 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14309 << NestedConstMember << IsNested << Field
14310 << FieldTy << Field->getSourceRange();
14311 }
14312
14313 // Then we append it to the list to check next in order.
14314 FieldTy = FieldTy.getCanonicalType();
14315 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14316 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14317 RecordTypeList.push_back(FieldRecTy);
14318 }
14319 }
14320 ++NextToCheckIndex;
14321 }
14322}
14323
14324/// Emit an error for the case where a record we are trying to assign to has a
14325/// const-qualified field somewhere in its hierarchy.
14326static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14327 SourceLocation Loc) {
14328 QualType Ty = E->getType();
14329 assert(Ty->isRecordType() && "lvalue was not record?");
14330 SourceRange Range = E->getSourceRange();
14331 const auto *RTy = Ty->getAsCanonical<RecordType>();
14332 bool DiagEmitted = false;
14333
14334 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14335 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14336 Range, OEK_Member, DiagEmitted);
14337 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14338 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14339 Range, OEK_Variable, DiagEmitted);
14340 else
14341 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14342 Range, OEK_LValue, DiagEmitted);
14343 if (!DiagEmitted)
14344 DiagnoseConstAssignment(S, E, Loc);
14345}
14346
14347/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14348/// emit an error and return true. If so, return false.
14350 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14351
14353
14354 SourceLocation OrigLoc = Loc;
14356 &Loc);
14357 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14359 if (IsLV == Expr::MLV_Valid)
14360 return false;
14361
14362 unsigned DiagID = 0;
14363 bool NeedType = false;
14364 switch (IsLV) { // C99 6.5.16p2
14366 // Use a specialized diagnostic when we're assigning to an object
14367 // from an enclosing function or block.
14369 if (NCCK == NCCK_Block)
14370 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14371 else
14372 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14373 break;
14374 }
14375
14376 // In ARC, use some specialized diagnostics for occasions where we
14377 // infer 'const'. These are always pseudo-strong variables.
14378 if (S.getLangOpts().ObjCAutoRefCount) {
14379 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14380 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14381 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14382
14383 // Use the normal diagnostic if it's pseudo-__strong but the
14384 // user actually wrote 'const'.
14385 if (var->isARCPseudoStrong() &&
14386 (!var->getTypeSourceInfo() ||
14387 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14388 // There are three pseudo-strong cases:
14389 // - self
14390 ObjCMethodDecl *method = S.getCurMethodDecl();
14391 if (method && var == method->getSelfDecl()) {
14392 DiagID = method->isClassMethod()
14393 ? diag::err_typecheck_arc_assign_self_class_method
14394 : diag::err_typecheck_arc_assign_self;
14395
14396 // - Objective-C externally_retained attribute.
14397 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14398 isa<ParmVarDecl>(var)) {
14399 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14400
14401 // - fast enumeration variables
14402 } else {
14403 DiagID = diag::err_typecheck_arr_assign_enumeration;
14404 }
14405
14406 SourceRange Assign;
14407 if (Loc != OrigLoc)
14408 Assign = SourceRange(OrigLoc, OrigLoc);
14409 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14410 // We need to preserve the AST regardless, so migration tool
14411 // can do its job.
14412 return false;
14413 }
14414 }
14415 }
14416
14417 // If none of the special cases above are triggered, then this is a
14418 // simple const assignment.
14419 if (DiagID == 0) {
14420 DiagnoseConstAssignment(S, E, Loc);
14421 return true;
14422 }
14423
14424 break;
14426 DiagnoseConstAssignment(S, E, Loc);
14427 return true;
14430 return true;
14433 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14434 NeedType = true;
14435 break;
14437 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14438 NeedType = true;
14439 break;
14441 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14442 break;
14443 case Expr::MLV_Valid:
14444 llvm_unreachable("did not take early return for MLV_Valid");
14448 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14449 break;
14452 return S.RequireCompleteType(Loc, E->getType(),
14453 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14455 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14456 break;
14458 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14459 break;
14461 llvm_unreachable("readonly properties should be processed differently");
14463 DiagID = diag::err_readonly_message_assignment;
14464 break;
14466 DiagID = diag::err_no_subobject_property_setting;
14467 break;
14468 }
14469
14470 SourceRange Assign;
14471 if (Loc != OrigLoc)
14472 Assign = SourceRange(OrigLoc, OrigLoc);
14473 if (NeedType)
14474 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14475 else
14476 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14477 return true;
14478}
14479
14480static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14481 SourceLocation Loc,
14482 Sema &Sema) {
14484 return;
14486 return;
14487 if (Loc.isInvalid() || Loc.isMacroID())
14488 return;
14489 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14490 return;
14491
14492 // C / C++ fields
14493 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14494 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14495 if (ML && MR) {
14496 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14497 return;
14498 const ValueDecl *LHSDecl =
14500 const ValueDecl *RHSDecl =
14502 if (LHSDecl != RHSDecl)
14503 return;
14504 if (LHSDecl->getType().isVolatileQualified())
14505 return;
14506 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14507 if (RefTy->getPointeeType().isVolatileQualified())
14508 return;
14509
14510 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14511 }
14512
14513 // Objective-C instance variables
14514 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14515 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14516 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14517 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14518 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14519 if (RL && RR && RL->getDecl() == RR->getDecl())
14520 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14521 }
14522}
14523
14524// C99 6.5.16.1
14526 SourceLocation Loc,
14527 QualType CompoundType,
14528 BinaryOperatorKind Opc) {
14529 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14530
14531 // Verify that LHS is a modifiable lvalue, and emit error if not.
14532 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14533 return QualType();
14534
14535 QualType LHSType = LHSExpr->getType();
14536 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14537 CompoundType;
14538
14539 if (RHS.isUsable()) {
14540 // Even if this check fails don't return early to allow the best
14541 // possible error recovery and to allow any subsequent diagnostics to
14542 // work.
14543 const ValueDecl *Assignee = nullptr;
14544 bool ShowFullyQualifiedAssigneeName = false;
14545 // In simple cases describe what is being assigned to
14546 if (auto *DR = dyn_cast<DeclRefExpr>(LHSExpr->IgnoreParenCasts())) {
14547 Assignee = DR->getDecl();
14548 } else if (auto *ME = dyn_cast<MemberExpr>(LHSExpr->IgnoreParenCasts())) {
14549 Assignee = ME->getMemberDecl();
14550 ShowFullyQualifiedAssigneeName = true;
14551 }
14552
14554 LHSType, RHS.get(), AssignmentAction::Assigning, Loc, Assignee,
14555 ShowFullyQualifiedAssigneeName);
14556 }
14557
14558 // OpenCL v1.2 s6.1.1.1 p2:
14559 // The half data type can only be used to declare a pointer to a buffer that
14560 // contains half values
14561 if (getLangOpts().OpenCL &&
14562 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14563 LHSType->isHalfType()) {
14564 Diag(Loc, diag::err_opencl_half_load_store) << 1
14565 << LHSType.getUnqualifiedType();
14566 return QualType();
14567 }
14568
14569 // WebAssembly tables can't be used on RHS of an assignment expression.
14570 if (RHSType->isWebAssemblyTableType()) {
14571 Diag(Loc, diag::err_wasm_table_art) << 0;
14572 return QualType();
14573 }
14574
14575 AssignConvertType ConvTy;
14576 if (CompoundType.isNull()) {
14577 Expr *RHSCheck = RHS.get();
14578
14579 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14580
14581 QualType LHSTy(LHSType);
14582 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14583 if (RHS.isInvalid())
14584 return QualType();
14585 // Special case of NSObject attributes on c-style pointer types.
14587 ((Context.isObjCNSObjectType(LHSType) &&
14588 RHSType->isObjCObjectPointerType()) ||
14589 (Context.isObjCNSObjectType(RHSType) &&
14590 LHSType->isObjCObjectPointerType())))
14592
14593 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14594 Diag(Loc, diag::err_objc_object_assignment) << LHSType;
14595
14596 // If the RHS is a unary plus or minus, check to see if they = and + are
14597 // right next to each other. If so, the user may have typo'd "x =+ 4"
14598 // instead of "x += 4".
14599 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14600 RHSCheck = ICE->getSubExpr();
14601 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14602 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14603 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14604 // Only if the two operators are exactly adjacent.
14605 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14606 // And there is a space or other character before the subexpr of the
14607 // unary +/-. We don't want to warn on "x=-1".
14608 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14609 UO->getSubExpr()->getBeginLoc().isFileID()) {
14610 Diag(Loc, diag::warn_not_compound_assign)
14611 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14612 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14613 }
14614 }
14615
14616 if (IsAssignConvertCompatible(ConvTy)) {
14617 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14618 // Warn about retain cycles where a block captures the LHS, but
14619 // not if the LHS is a simple variable into which the block is
14620 // being stored...unless that variable can be captured by reference!
14621 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14622 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14623 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14624 ObjC().checkRetainCycles(LHSExpr, RHS.get());
14625 }
14626
14627 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14629 // It is safe to assign a weak reference into a strong variable.
14630 // Although this code can still have problems:
14631 // id x = self.weakProp;
14632 // id y = self.weakProp;
14633 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14634 // paths through the function. This should be revisited if
14635 // -Wrepeated-use-of-weak is made flow-sensitive.
14636 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14637 // variable, which will be valid for the current autorelease scope.
14638 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14639 RHS.get()->getBeginLoc()))
14641
14642 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14643 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14644 }
14645 }
14646 } else {
14647 // Compound assignment "x += y"
14648 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14649 }
14650
14651 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
14653 return QualType();
14654
14655 CheckForNullPointerDereference(*this, LHSExpr);
14656
14657 AssignedEntity AE{LHSExpr};
14658 checkAssignmentLifetime(*this, AE, RHS.get());
14659
14660 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14661 if (CompoundType.isNull()) {
14662 // C++2a [expr.ass]p5:
14663 // A simple-assignment whose left operand is of a volatile-qualified
14664 // type is deprecated unless the assignment is either a discarded-value
14665 // expression or an unevaluated operand
14666 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14667 }
14668 }
14669
14670 // C11 6.5.16p3: The type of an assignment expression is the type of the
14671 // left operand would have after lvalue conversion.
14672 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14673 // qualified type, the value has the unqualified version of the type of the
14674 // lvalue; additionally, if the lvalue has atomic type, the value has the
14675 // non-atomic version of the type of the lvalue.
14676 // C++ 5.17p1: the type of the assignment expression is that of its left
14677 // operand.
14678 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14679}
14680
14681// Scenarios to ignore if expression E is:
14682// 1. an explicit cast expression into void
14683// 2. a function call expression that returns void
14684static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14685 E = E->IgnoreParens();
14686
14687 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14688 if (CE->getCastKind() == CK_ToVoid) {
14689 return true;
14690 }
14691
14692 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14693 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14694 CE->getSubExpr()->getType()->isDependentType()) {
14695 return true;
14696 }
14697 }
14698
14699 if (const auto *CE = dyn_cast<CallExpr>(E))
14700 return CE->getCallReturnType(Context)->isVoidType();
14701 return false;
14702}
14703
14705 // No warnings in macros
14706 if (Loc.isMacroID())
14707 return;
14708
14709 // Don't warn in template instantiations.
14711 return;
14712
14713 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14714 // instead, skip more than needed, then call back into here with the
14715 // CommaVisitor in SemaStmt.cpp.
14716 // The listed locations are the initialization and increment portions
14717 // of a for loop. The additional checks are on the condition of
14718 // if statements, do/while loops, and for loops.
14719 if (getCurScope()->isControlScope())
14720 return;
14721
14722 // If there are multiple comma operators used together, get the RHS of the
14723 // of the comma operator as the LHS.
14724 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14725 if (BO->getOpcode() != BO_Comma)
14726 break;
14727 LHS = BO->getRHS();
14728 }
14729
14730 // Only allow some expressions on LHS to not warn.
14731 if (IgnoreCommaOperand(LHS, Context))
14732 return;
14733
14734 Diag(Loc, diag::warn_comma_operator);
14735 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14736 << LHS->getSourceRange()
14738 LangOpts.CPlusPlus ? "static_cast<void>("
14739 : "(void)(")
14740 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14741 ")");
14742}
14743
14744// C99 6.5.17
14746 SourceLocation Loc) {
14747 LHS = S.CheckPlaceholderExpr(LHS.get());
14748 RHS = S.CheckPlaceholderExpr(RHS.get());
14749 if (LHS.isInvalid() || RHS.isInvalid())
14750 return QualType();
14751
14752 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14753 // operands, but not unary promotions.
14754 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14755
14756 // So we treat the LHS as a ignored value, and in C++ we allow the
14757 // containing site to determine what should be done with the RHS.
14758 LHS = S.IgnoredValueConversions(LHS.get());
14759 if (LHS.isInvalid())
14760 return QualType();
14761
14762 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14763
14764 if (!S.getLangOpts().CPlusPlus) {
14766 if (RHS.isInvalid())
14767 return QualType();
14768 if (!RHS.get()->getType()->isVoidType())
14769 S.RequireCompleteType(Loc, RHS.get()->getType(),
14770 diag::err_incomplete_type);
14771 }
14772
14773 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14774 S.DiagnoseCommaOperator(LHS.get(), Loc);
14775
14776 return RHS.get()->getType();
14777}
14778
14779/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14780/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14783 ExprObjectKind &OK,
14784 SourceLocation OpLoc, bool IsInc,
14785 bool IsPrefix) {
14786 QualType ResType = Op->getType();
14787 // Atomic types can be used for increment / decrement where the non-atomic
14788 // versions can, so ignore the _Atomic() specifier for the purpose of
14789 // checking.
14790 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14791 ResType = ResAtomicType->getValueType();
14792
14793 assert(!ResType.isNull() && "no type for increment/decrement expression");
14794
14795 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14796 // Decrement of bool is not allowed.
14797 if (!IsInc) {
14798 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14799 return QualType();
14800 }
14801 // Increment of bool sets it to true, but is deprecated.
14802 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14803 : diag::warn_increment_bool)
14804 << Op->getSourceRange();
14805 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14806 // Error on enum increments and decrements in C++ mode
14807 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14808 return QualType();
14809 } else if (ResType->isRealType()) {
14810 // OK!
14811 } else if (ResType->isPointerType()) {
14812 // C99 6.5.2.4p2, 6.5.6p2
14813 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14814 return QualType();
14815 } else if (ResType->isOverflowBehaviorType()) {
14816 // OK!
14817 } else if (ResType->isObjCObjectPointerType()) {
14818 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14819 // Otherwise, we just need a complete type.
14820 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14821 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14822 return QualType();
14823 } else if (ResType->isAnyComplexType()) {
14824 // C99 does not support ++/-- on complex types, we allow as an extension.
14825 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14826 : diag::ext_c2y_increment_complex)
14827 << IsInc << Op->getSourceRange();
14828 } else if (ResType->isPlaceholderType()) {
14830 if (PR.isInvalid()) return QualType();
14831 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14832 IsInc, IsPrefix);
14833 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14834 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14835 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14836 (ResType->castAs<VectorType>()->getVectorKind() !=
14838 // The z vector extensions allow ++ and -- for non-bool vectors.
14839 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14840 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14841 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14842 } else {
14843 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14844 << ResType << int(IsInc) << Op->getSourceRange();
14845 return QualType();
14846 }
14847 // At this point, we know we have a real, complex or pointer type.
14848 // Now make sure the operand is a modifiable lvalue.
14849 if (CheckForModifiableLvalue(Op, OpLoc, S))
14850 return QualType();
14851 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14852 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14853 // An operand with volatile-qualified type is deprecated
14854 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14855 << IsInc << ResType;
14856 }
14857 // In C++, a prefix increment is the same type as the operand. Otherwise
14858 // (in C or with postfix), the increment is the unqualified type of the
14859 // operand.
14860 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14861 VK = VK_LValue;
14862 OK = Op->getObjectKind();
14863 return ResType;
14864 } else {
14865 VK = VK_PRValue;
14866 return ResType.getUnqualifiedType();
14867 }
14868}
14869
14870/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14871/// This routine allows us to typecheck complex/recursive expressions
14872/// where the declaration is needed for type checking. We only need to
14873/// handle cases when the expression references a function designator
14874/// or is an lvalue. Here are some examples:
14875/// - &(x) => x
14876/// - &*****f => f for f a function designator.
14877/// - &s.xx => s
14878/// - &s.zz[1].yy -> s, if zz is an array
14879/// - *(x + 1) -> x, if x is an array
14880/// - &"123"[2] -> 0
14881/// - & __real__ x -> x
14882///
14883/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14884/// members.
14886 switch (E->getStmtClass()) {
14887 case Stmt::DeclRefExprClass:
14888 return cast<DeclRefExpr>(E)->getDecl();
14889 case Stmt::MemberExprClass:
14890 // If this is an arrow operator, the address is an offset from
14891 // the base's value, so the object the base refers to is
14892 // irrelevant.
14893 if (cast<MemberExpr>(E)->isArrow())
14894 return nullptr;
14895 // Otherwise, the expression refers to a part of the base
14896 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14897 case Stmt::ArraySubscriptExprClass: {
14898 // FIXME: This code shouldn't be necessary! We should catch the implicit
14899 // promotion of register arrays earlier.
14900 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14901 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14902 if (ICE->getSubExpr()->getType()->isArrayType())
14903 return getPrimaryDecl(ICE->getSubExpr());
14904 }
14905 return nullptr;
14906 }
14907 case Stmt::UnaryOperatorClass: {
14909
14910 switch(UO->getOpcode()) {
14911 case UO_Real:
14912 case UO_Imag:
14913 case UO_Extension:
14914 return getPrimaryDecl(UO->getSubExpr());
14915 default:
14916 return nullptr;
14917 }
14918 }
14919 case Stmt::ParenExprClass:
14920 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14921 case Stmt::ImplicitCastExprClass:
14922 // If the result of an implicit cast is an l-value, we care about
14923 // the sub-expression; otherwise, the result here doesn't matter.
14924 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14925 case Stmt::CXXUuidofExprClass:
14926 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14927 default:
14928 return nullptr;
14929 }
14930}
14931
14932namespace {
14933enum {
14934 AO_Bit_Field = 0,
14935 AO_Vector_Element = 1,
14936 AO_Property_Expansion = 2,
14937 AO_Register_Variable = 3,
14938 AO_Matrix_Element = 4,
14939 AO_No_Error = 5
14940};
14941}
14942/// Diagnose invalid operand for address of operations.
14943///
14944/// \param Type The type of operand which cannot have its address taken.
14946 Expr *E, unsigned Type) {
14947 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14948}
14949
14951 const Expr *Op,
14952 const CXXMethodDecl *MD) {
14953 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14954
14955 if (Op != DRE)
14956 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14957 << Op->getSourceRange();
14958
14959 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14960 if (isa<CXXDestructorDecl>(MD))
14961 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14962 << DRE->getSourceRange();
14963
14964 if (DRE->getQualifier())
14965 return false;
14966
14967 if (MD->getParent()->getName().empty())
14968 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14969 << DRE->getSourceRange();
14970
14971 SmallString<32> Str;
14972 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14973 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14974 << DRE->getSourceRange()
14975 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14976}
14977
14979 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14980 if (PTy->getKind() == BuiltinType::Overload) {
14981 Expr *E = OrigOp.get()->IgnoreParens();
14982 if (!isa<OverloadExpr>(E)) {
14983 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14984 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14985 << OrigOp.get()->getSourceRange();
14986 return QualType();
14987 }
14988
14992 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14993 << OrigOp.get()->getSourceRange();
14994 return QualType();
14995 }
14996
14997 return Context.OverloadTy;
14998 }
14999
15000 if (PTy->getKind() == BuiltinType::UnknownAny)
15001 return Context.UnknownAnyTy;
15002
15003 if (PTy->getKind() == BuiltinType::BoundMember) {
15004 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15005 << OrigOp.get()->getSourceRange();
15006 return QualType();
15007 }
15008
15009 OrigOp = CheckPlaceholderExpr(OrigOp.get());
15010 if (OrigOp.isInvalid()) return QualType();
15011 }
15012
15013 if (OrigOp.get()->isTypeDependent())
15014 return Context.DependentTy;
15015
15016 assert(!OrigOp.get()->hasPlaceholderType());
15017
15018 // Make sure to ignore parentheses in subsequent checks
15019 Expr *op = OrigOp.get()->IgnoreParens();
15020
15021 // In OpenCL captures for blocks called as lambda functions
15022 // are located in the private address space. Blocks used in
15023 // enqueue_kernel can be located in a different address space
15024 // depending on a vendor implementation. Thus preventing
15025 // taking an address of the capture to avoid invalid AS casts.
15026 if (LangOpts.OpenCL) {
15027 auto* VarRef = dyn_cast<DeclRefExpr>(op);
15028 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
15029 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
15030 return QualType();
15031 }
15032 }
15033
15034 if (getLangOpts().C99) {
15035 // Implement C99-only parts of addressof rules.
15036 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
15037 if (uOp->getOpcode() == UO_Deref)
15038 // Per C99 6.5.3.2, the address of a deref always returns a valid result
15039 // (assuming the deref expression is valid).
15040 return uOp->getSubExpr()->getType();
15041 }
15042 // Technically, there should be a check for array subscript
15043 // expressions here, but the result of one is always an lvalue anyway.
15044 }
15045 ValueDecl *dcl = getPrimaryDecl(op);
15046
15047 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
15048 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
15049 op->getBeginLoc()))
15050 return QualType();
15051
15053 unsigned AddressOfError = AO_No_Error;
15054
15055 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15056 bool IsError = isSFINAEContext();
15057 Diag(OpLoc, IsError ? diag::err_typecheck_addrof_temporary
15058 : diag::ext_typecheck_addrof_temporary)
15059 << op->getType() << op->getSourceRange();
15060 if (IsError)
15061 return QualType();
15062 // Materialize the temporary as an lvalue so that we can take its address.
15063 OrigOp = op =
15064 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
15065 } else if (isa<ObjCSelectorExpr>(op)) {
15066 return Context.getPointerType(op->getType());
15067 } else if (lval == Expr::LV_MemberFunction) {
15068 // If it's an instance method, make a member pointer.
15069 // The expression must have exactly the form &A::foo.
15070
15071 // If the underlying expression isn't a decl ref, give up.
15072 if (!isa<DeclRefExpr>(op)) {
15073 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15074 << OrigOp.get()->getSourceRange();
15075 return QualType();
15076 }
15077 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
15079
15080 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15081 QualType MPTy = Context.getMemberPointerType(
15082 op->getType(), DRE->getQualifier(), MD->getParent());
15083
15084 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
15085 !isUnevaluatedContext() && !MPTy->isDependentType()) {
15086 // When pointer authentication is enabled, argument and return types of
15087 // vitual member functions must be complete. This is because vitrual
15088 // member function pointers are implemented using virtual dispatch
15089 // thunks and the thunks cannot be emitted if the argument or return
15090 // types are incomplete.
15091 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15092 SourceLocation DeclRefLoc,
15093 SourceLocation RetArgTypeLoc) {
15094 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
15095 Diag(DeclRefLoc,
15096 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15097 Diag(RetArgTypeLoc,
15098 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15099 << T;
15100 return true;
15101 }
15102 return false;
15103 };
15104 QualType RetTy = MD->getReturnType();
15105 bool IsIncomplete =
15106 !RetTy->isVoidType() &&
15107 ReturnOrParamTypeIsIncomplete(
15108 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15109 for (auto *PVD : MD->parameters())
15110 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15111 PVD->getBeginLoc());
15112 if (IsIncomplete)
15113 return QualType();
15114 }
15115
15116 // Under the MS ABI, lock down the inheritance model now.
15117 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15118 (void)isCompleteType(OpLoc, MPTy);
15119 return MPTy;
15120 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15121 // C99 6.5.3.2p1
15122 // The operand must be either an l-value or a function designator
15123 if (!op->getType()->isFunctionType()) {
15124 // Use a special diagnostic for loads from property references.
15125 if (isa<PseudoObjectExpr>(op)) {
15126 AddressOfError = AO_Property_Expansion;
15127 } else {
15128 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
15129 << op->getType() << op->getSourceRange();
15130 return QualType();
15131 }
15132 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
15133 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
15134 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15135 }
15136
15137 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15138 // The operand cannot be a bit-field
15139 AddressOfError = AO_Bit_Field;
15140 } else if (op->getObjectKind() == OK_VectorComponent) {
15141 // The operand cannot be an element of a vector
15142 AddressOfError = AO_Vector_Element;
15143 } else if (op->getObjectKind() == OK_MatrixComponent) {
15144 // The operand cannot be an element of a matrix.
15145 AddressOfError = AO_Matrix_Element;
15146 } else if (dcl) { // C99 6.5.3.2p1
15147 // We have an lvalue with a decl. Make sure the decl is not declared
15148 // with the register storage-class specifier.
15149 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
15150 // in C++ it is not error to take address of a register
15151 // variable (c++03 7.1.1P3)
15152 if (vd->getStorageClass() == SC_Register &&
15154 AddressOfError = AO_Register_Variable;
15155 }
15156 } else if (isa<MSPropertyDecl>(dcl)) {
15157 AddressOfError = AO_Property_Expansion;
15158 } else if (isa<FunctionTemplateDecl>(dcl)) {
15159 return Context.OverloadTy;
15160 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
15161 // Okay: we can take the address of a field.
15162 // Could be a pointer to member, though, if there is an explicit
15163 // scope qualifier for the class.
15164
15165 // [C++26] [expr.prim.id.general]
15166 // If an id-expression E denotes a non-static non-type member
15167 // of some class C [...] and if E is a qualified-id, E is
15168 // not the un-parenthesized operand of the unary & operator [...]
15169 // the id-expression is transformed into a class member access expression.
15170 if (auto *DRE = dyn_cast<DeclRefExpr>(op);
15171 DRE && DRE->getQualifier() && !isa<ParenExpr>(OrigOp.get())) {
15172 DeclContext *Ctx = dcl->getDeclContext();
15173 if (Ctx && Ctx->isRecord()) {
15174 if (dcl->getType()->isReferenceType()) {
15175 Diag(OpLoc,
15176 diag::err_cannot_form_pointer_to_member_of_reference_type)
15177 << dcl->getDeclName() << dcl->getType();
15178 return QualType();
15179 }
15180
15181 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
15182 Ctx = Ctx->getParent();
15183
15184 QualType MPTy = Context.getMemberPointerType(
15185 op->getType(), DRE->getQualifier(), cast<CXXRecordDecl>(Ctx));
15186 // Under the MS ABI, lock down the inheritance model now.
15187 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15188 (void)isCompleteType(OpLoc, MPTy);
15189 return MPTy;
15190 }
15191 }
15195 llvm_unreachable("Unknown/unexpected decl type");
15196 }
15197
15198 if (AddressOfError != AO_No_Error) {
15199 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
15200 return QualType();
15201 }
15202
15203 if (lval == Expr::LV_IncompleteVoidType) {
15204 // Taking the address of a void variable is technically illegal, but we
15205 // allow it in cases which are otherwise valid.
15206 // Example: "extern void x; void* y = &x;".
15207 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
15208 }
15209
15210 // If the operand has type "type", the result has type "pointer to type".
15211 if (op->getType()->isObjCObjectType())
15212 return Context.getObjCObjectPointerType(op->getType());
15213
15214 // Cannot take the address of WebAssembly references or tables.
15215 if (Context.getTargetInfo().getTriple().isWasm()) {
15216 QualType OpTy = op->getType();
15217 if (OpTy.isWebAssemblyReferenceType()) {
15218 Diag(OpLoc, diag::err_wasm_ca_reference)
15219 << 1 << OrigOp.get()->getSourceRange();
15220 return QualType();
15221 }
15222 if (OpTy->isWebAssemblyTableType()) {
15223 Diag(OpLoc, diag::err_wasm_table_pr)
15224 << 1 << OrigOp.get()->getSourceRange();
15225 return QualType();
15226 }
15227 }
15228
15229 CheckAddressOfPackedMember(op);
15230
15231 return Context.getPointerType(op->getType());
15232}
15233
15234static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15235 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
15236 if (!DRE)
15237 return;
15238 const Decl *D = DRE->getDecl();
15239 if (!D)
15240 return;
15241 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
15242 if (!Param)
15243 return;
15244 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
15245 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15246 return;
15247 if (FunctionScopeInfo *FD = S.getCurFunction())
15248 FD->ModifiedNonNullParams.insert(Param);
15249}
15250
15251/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15253 SourceLocation OpLoc,
15254 bool IsAfterAmp = false) {
15255 ExprResult ConvResult = S.UsualUnaryConversions(Op);
15256 if (ConvResult.isInvalid())
15257 return QualType();
15258 Op = ConvResult.get();
15259 QualType OpTy = Op->getType();
15261
15263 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15264 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
15265 Op->getSourceRange());
15266 }
15267
15268 if (const PointerType *PT = OpTy->getAs<PointerType>())
15269 {
15270 Result = PT->getPointeeType();
15271 }
15272 else if (const ObjCObjectPointerType *OPT =
15274 Result = OPT->getPointeeType();
15275 else {
15277 if (PR.isInvalid()) return QualType();
15278 if (PR.get() != Op)
15279 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
15280 }
15281
15282 if (Result.isNull()) {
15283 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
15284 << OpTy << Op->getSourceRange();
15285 return QualType();
15286 }
15287
15288 if (Result->isVoidType()) {
15289 // C++ [expr.unary.op]p1:
15290 // [...] the expression to which [the unary * operator] is applied shall
15291 // be a pointer to an object type, or a pointer to a function type
15292 LangOptions LO = S.getLangOpts();
15293 if (LO.CPlusPlus)
15294 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
15295 << OpTy << Op->getSourceRange();
15296 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15297 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
15298 << OpTy << Op->getSourceRange();
15299 }
15300
15301 // Dereferences are usually l-values...
15302 VK = VK_LValue;
15303
15304 // ...except that certain expressions are never l-values in C.
15305 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15306 VK = VK_PRValue;
15307
15308 return Result;
15309}
15310
15311BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15313 switch (Kind) {
15314 default: llvm_unreachable("Unknown binop!");
15315 case tok::periodstar: Opc = BO_PtrMemD; break;
15316 case tok::arrowstar: Opc = BO_PtrMemI; break;
15317 case tok::star: Opc = BO_Mul; break;
15318 case tok::slash: Opc = BO_Div; break;
15319 case tok::percent: Opc = BO_Rem; break;
15320 case tok::plus: Opc = BO_Add; break;
15321 case tok::minus: Opc = BO_Sub; break;
15322 case tok::lessless: Opc = BO_Shl; break;
15323 case tok::greatergreater: Opc = BO_Shr; break;
15324 case tok::lessequal: Opc = BO_LE; break;
15325 case tok::less: Opc = BO_LT; break;
15326 case tok::greaterequal: Opc = BO_GE; break;
15327 case tok::greater: Opc = BO_GT; break;
15328 case tok::exclaimequal: Opc = BO_NE; break;
15329 case tok::equalequal: Opc = BO_EQ; break;
15330 case tok::spaceship: Opc = BO_Cmp; break;
15331 case tok::amp: Opc = BO_And; break;
15332 case tok::caret: Opc = BO_Xor; break;
15333 case tok::pipe: Opc = BO_Or; break;
15334 case tok::ampamp: Opc = BO_LAnd; break;
15335 case tok::pipepipe: Opc = BO_LOr; break;
15336 case tok::equal: Opc = BO_Assign; break;
15337 case tok::starequal: Opc = BO_MulAssign; break;
15338 case tok::slashequal: Opc = BO_DivAssign; break;
15339 case tok::percentequal: Opc = BO_RemAssign; break;
15340 case tok::plusequal: Opc = BO_AddAssign; break;
15341 case tok::minusequal: Opc = BO_SubAssign; break;
15342 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15343 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15344 case tok::ampequal: Opc = BO_AndAssign; break;
15345 case tok::caretequal: Opc = BO_XorAssign; break;
15346 case tok::pipeequal: Opc = BO_OrAssign; break;
15347 case tok::comma: Opc = BO_Comma; break;
15348 }
15349 return Opc;
15350}
15351
15353 tok::TokenKind Kind) {
15355 switch (Kind) {
15356 default: llvm_unreachable("Unknown unary op!");
15357 case tok::plusplus: Opc = UO_PreInc; break;
15358 case tok::minusminus: Opc = UO_PreDec; break;
15359 case tok::amp: Opc = UO_AddrOf; break;
15360 case tok::star: Opc = UO_Deref; break;
15361 case tok::plus: Opc = UO_Plus; break;
15362 case tok::minus: Opc = UO_Minus; break;
15363 case tok::tilde: Opc = UO_Not; break;
15364 case tok::exclaim: Opc = UO_LNot; break;
15365 case tok::kw___real: Opc = UO_Real; break;
15366 case tok::kw___imag: Opc = UO_Imag; break;
15367 case tok::kw___extension__: Opc = UO_Extension; break;
15368 }
15369 return Opc;
15370}
15371
15372const FieldDecl *
15374 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15375 // common for setters.
15376 // struct A {
15377 // int X;
15378 // -void setX(int X) { X = X; }
15379 // +void setX(int X) { this->X = X; }
15380 // };
15381
15382 // Only consider parameters for self assignment fixes.
15383 if (!isa<ParmVarDecl>(SelfAssigned))
15384 return nullptr;
15385 const auto *Method =
15386 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15387 if (!Method)
15388 return nullptr;
15389
15390 const CXXRecordDecl *Parent = Method->getParent();
15391 // In theory this is fixable if the lambda explicitly captures this, but
15392 // that's added complexity that's rarely going to be used.
15393 if (Parent->isLambda())
15394 return nullptr;
15395
15396 // FIXME: Use an actual Lookup operation instead of just traversing fields
15397 // in order to get base class fields.
15398 auto Field =
15399 llvm::find_if(Parent->fields(),
15400 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15401 return F->getDeclName() == Name;
15402 });
15403 return (Field != Parent->field_end()) ? *Field : nullptr;
15404}
15405
15406/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15407/// This warning suppressed in the event of macro expansions.
15408static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15409 SourceLocation OpLoc, bool IsBuiltin) {
15411 return;
15412 if (S.isUnevaluatedContext())
15413 return;
15414 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15415 return;
15416 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15417 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15418 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15419 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15420 if (!LHSDeclRef || !RHSDeclRef ||
15421 LHSDeclRef->getLocation().isMacroID() ||
15422 RHSDeclRef->getLocation().isMacroID())
15423 return;
15424 const ValueDecl *LHSDecl =
15425 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15426 const ValueDecl *RHSDecl =
15427 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15428 if (LHSDecl != RHSDecl)
15429 return;
15430 if (LHSDecl->getType().isVolatileQualified())
15431 return;
15432 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15433 if (RefTy->getPointeeType().isVolatileQualified())
15434 return;
15435
15436 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15437 : diag::warn_self_assignment_overloaded)
15438 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15439 << RHSExpr->getSourceRange();
15440 if (const FieldDecl *SelfAssignField =
15442 Diag << 1 << SelfAssignField
15443 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15444 else
15445 Diag << 0;
15446}
15447
15448/// Check if a bitwise-& is performed on an Objective-C pointer. This
15449/// is usually indicative of introspection within the Objective-C pointer.
15451 SourceLocation OpLoc) {
15452 if (!S.getLangOpts().ObjC)
15453 return;
15454
15455 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15456 const Expr *LHS = L.get();
15457 const Expr *RHS = R.get();
15458
15460 ObjCPointerExpr = LHS;
15461 OtherExpr = RHS;
15462 }
15463 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15464 ObjCPointerExpr = RHS;
15465 OtherExpr = LHS;
15466 }
15467
15468 // This warning is deliberately made very specific to reduce false
15469 // positives with logic that uses '&' for hashing. This logic mainly
15470 // looks for code trying to introspect into tagged pointers, which
15471 // code should generally never do.
15472 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15473 unsigned Diag = diag::warn_objc_pointer_masking;
15474 // Determine if we are introspecting the result of performSelectorXXX.
15475 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15476 // Special case messages to -performSelector and friends, which
15477 // can return non-pointer values boxed in a pointer value.
15478 // Some clients may wish to silence warnings in this subcase.
15479 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15480 Selector S = ME->getSelector();
15481 StringRef SelArg0 = S.getNameForSlot(0);
15482 if (SelArg0.starts_with("performSelector"))
15483 Diag = diag::warn_objc_pointer_masking_performSelector;
15484 }
15485
15486 S.Diag(OpLoc, Diag)
15487 << ObjCPointerExpr->getSourceRange();
15488 }
15489}
15490
15491// This helper function promotes a binary operator's operands (which are of a
15492// half vector type) to a vector of floats and then truncates the result to
15493// a vector of either half or short.
15495 BinaryOperatorKind Opc, QualType ResultTy,
15497 bool IsCompAssign, SourceLocation OpLoc,
15498 FPOptionsOverride FPFeatures) {
15499 auto &Context = S.getASTContext();
15500 assert((isVector(ResultTy, Context.HalfTy) ||
15501 isVector(ResultTy, Context.ShortTy)) &&
15502 "Result must be a vector of half or short");
15503 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15504 isVector(RHS.get()->getType(), Context.HalfTy) &&
15505 "both operands expected to be a half vector");
15506
15507 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15508 QualType BinOpResTy = RHS.get()->getType();
15509
15510 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15511 // change BinOpResTy to a vector of ints.
15512 if (isVector(ResultTy, Context.ShortTy))
15513 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15514
15515 if (IsCompAssign)
15516 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15517 ResultTy, VK, OK, OpLoc, FPFeatures,
15518 BinOpResTy, BinOpResTy);
15519
15520 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15521 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15522 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15523 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15524}
15525
15526/// Returns true if conversion between vectors of halfs and vectors of floats
15527/// is needed.
15528static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15529 Expr *E0, Expr *E1 = nullptr) {
15530 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType)
15531 return false;
15532
15533 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15534 QualType Ty = E->IgnoreImplicit()->getType();
15535
15536 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15537 // to vectors of floats. Although the element type of the vectors is __fp16,
15538 // the vectors shouldn't be treated as storage-only types. See the
15539 // discussion here: https://reviews.llvm.org/rG825235c140e7
15540 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15541 if (VT->getVectorKind() == VectorKind::Neon)
15542 return false;
15543 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15544 }
15545 return false;
15546 };
15547
15548 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15549}
15550
15552 BinaryOperatorKind Opc, Expr *LHSExpr,
15553 Expr *RHSExpr, bool ForFoldExpression) {
15554 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15555 // The syntax only allows initializer lists on the RHS of assignment,
15556 // so we don't need to worry about accepting invalid code for
15557 // non-assignment operators.
15558 // C++11 5.17p9:
15559 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15560 // of x = {} is x = T().
15562 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15563 InitializedEntity Entity =
15565 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15566 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15567 if (Init.isInvalid())
15568 return Init;
15569 RHSExpr = Init.get();
15570 }
15571
15572 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15573 QualType ResultTy; // Result type of the binary operator.
15574 // The following two variables are used for compound assignment operators
15575 QualType CompLHSTy; // Type of LHS after promotions for computation
15576 QualType CompResultTy; // Type of computation result
15579 bool ConvertHalfVec = false;
15580
15581 if (!LHS.isUsable() || !RHS.isUsable())
15582 return ExprError();
15583
15584 if (getLangOpts().OpenCL) {
15585 QualType LHSTy = LHSExpr->getType();
15586 QualType RHSTy = RHSExpr->getType();
15587 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15588 // the ATOMIC_VAR_INIT macro.
15589 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15590 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15591 if (BO_Assign == Opc)
15592 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15593 else
15594 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15595 return ExprError();
15596 }
15597
15598 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15599 // only with a builtin functions and therefore should be disallowed here.
15600 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15601 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15602 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15603 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15604 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15605 return ExprError();
15606 }
15607 }
15608
15609 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15610 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15611
15612 switch (Opc) {
15613 case BO_Assign:
15614 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15615 if (getLangOpts().CPlusPlus &&
15616 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15617 VK = LHS.get()->getValueKind();
15618 OK = LHS.get()->getObjectKind();
15619 }
15620 if (!ResultTy.isNull()) {
15621 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15622 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15623
15624 // Avoid copying a block to the heap if the block is assigned to a local
15625 // auto variable that is declared in the same scope as the block. This
15626 // optimization is unsafe if the local variable is declared in an outer
15627 // scope. For example:
15628 //
15629 // BlockTy b;
15630 // {
15631 // b = ^{...};
15632 // }
15633 // // It is unsafe to invoke the block here if it wasn't copied to the
15634 // // heap.
15635 // b();
15636
15637 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15638 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15639 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15640 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15641 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15642
15644 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15646 }
15647 RecordModifiableNonNullParam(*this, LHS.get());
15648 break;
15649 case BO_PtrMemD:
15650 case BO_PtrMemI:
15651 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15652 Opc == BO_PtrMemI);
15653 break;
15654 case BO_Mul:
15655 case BO_Div:
15656 ConvertHalfVec = true;
15657 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15658 break;
15659 case BO_Rem:
15660 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15661 break;
15662 case BO_Add:
15663 ConvertHalfVec = true;
15664 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15665 break;
15666 case BO_Sub:
15667 ConvertHalfVec = true;
15668 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);
15669 break;
15670 case BO_Shl:
15671 case BO_Shr:
15672 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15673 break;
15674 case BO_LE:
15675 case BO_LT:
15676 case BO_GE:
15677 case BO_GT:
15678 ConvertHalfVec = true;
15679 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15680
15681 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
15682 !ForFoldExpression && BI && BI->isComparisonOp())
15683 Diag(OpLoc, diag::warn_consecutive_comparison)
15684 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
15685
15686 break;
15687 case BO_EQ:
15688 case BO_NE:
15689 ConvertHalfVec = true;
15690 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15691 break;
15692 case BO_Cmp:
15693 ConvertHalfVec = true;
15694 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15695 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15696 break;
15697 case BO_And:
15698 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15699 [[fallthrough]];
15700 case BO_Xor:
15701 case BO_Or:
15702 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15703 break;
15704 case BO_LAnd:
15705 case BO_LOr:
15706 ConvertHalfVec = true;
15707 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15708 break;
15709 case BO_MulAssign:
15710 case BO_DivAssign:
15711 ConvertHalfVec = true;
15712 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15713 CompLHSTy = CompResultTy;
15714 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15715 ResultTy =
15716 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15717 break;
15718 case BO_RemAssign:
15719 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, 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_AddAssign:
15726 ConvertHalfVec = true;
15727 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15728 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15729 ResultTy =
15730 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15731 break;
15732 case BO_SubAssign:
15733 ConvertHalfVec = true;
15734 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15735 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15736 ResultTy =
15737 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15738 break;
15739 case BO_ShlAssign:
15740 case BO_ShrAssign:
15741 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15742 CompLHSTy = CompResultTy;
15743 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15744 ResultTy =
15745 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15746 break;
15747 case BO_AndAssign:
15748 case BO_OrAssign: // fallthrough
15749 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15750 [[fallthrough]];
15751 case BO_XorAssign:
15752 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15753 CompLHSTy = CompResultTy;
15754 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15755 ResultTy =
15756 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15757 break;
15758 case BO_Comma:
15759 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15760 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15761 VK = RHS.get()->getValueKind();
15762 OK = RHS.get()->getObjectKind();
15763 }
15764 break;
15765 }
15766 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15767 return ExprError();
15768
15769 // Some of the binary operations require promoting operands of half vector to
15770 // float vectors and truncating the result back to half vector. For now, we do
15771 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15772 // arm64).
15773 assert(
15774 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15775 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15776 "both sides are half vectors or neither sides are");
15777 ConvertHalfVec =
15778 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15779
15780 // Check for array bounds violations for both sides of the BinaryOperator
15781 CheckArrayAccess(LHS.get());
15782 CheckArrayAccess(RHS.get());
15783
15784 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15785 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15786 &Context.Idents.get("object_setClass"),
15788 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15789 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15790 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15792 "object_setClass(")
15793 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15794 ",")
15795 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15796 }
15797 else
15798 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15799 }
15800 else if (const ObjCIvarRefExpr *OIRE =
15801 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15802 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15803
15804 // Opc is not a compound assignment if CompResultTy is null.
15805 if (CompResultTy.isNull()) {
15806 if (ConvertHalfVec)
15807 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15808 OpLoc, CurFPFeatureOverrides());
15809 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15810 VK, OK, OpLoc, CurFPFeatureOverrides());
15811 }
15812
15813 // Handle compound assignments.
15814 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15816 VK = VK_LValue;
15817 OK = LHS.get()->getObjectKind();
15818 }
15819
15820 // The LHS is not converted to the result type for fixed-point compound
15821 // assignment as the common type is computed on demand. Reset the CompLHSTy
15822 // to the LHS type we would have gotten after unary conversions.
15823 if (CompResultTy->isFixedPointType())
15824 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15825
15826 if (ConvertHalfVec)
15827 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15828 OpLoc, CurFPFeatureOverrides());
15829
15831 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15832 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15833}
15834
15835/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15836/// operators are mixed in a way that suggests that the programmer forgot that
15837/// comparison operators have higher precedence. The most typical example of
15838/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15840 SourceLocation OpLoc, Expr *LHSExpr,
15841 Expr *RHSExpr) {
15842 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15843 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15844
15845 // Check that one of the sides is a comparison operator and the other isn't.
15846 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15847 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15848 if (isLeftComp == isRightComp)
15849 return;
15850
15851 // Bitwise operations are sometimes used as eager logical ops.
15852 // Don't diagnose this.
15853 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15854 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15855 if (isLeftBitwise || isRightBitwise)
15856 return;
15857
15858 SourceRange DiagRange = isLeftComp
15859 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15860 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15861 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15862 SourceRange ParensRange =
15863 isLeftComp
15864 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15865 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15866
15867 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15868 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15869 SuggestParentheses(Self, OpLoc,
15870 Self.PDiag(diag::note_precedence_silence) << OpStr,
15871 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15872 SuggestParentheses(Self, OpLoc,
15873 Self.PDiag(diag::note_precedence_bitwise_first)
15875 ParensRange);
15876}
15877
15878/// It accepts a '&&' expr that is inside a '||' one.
15879/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15880/// in parentheses.
15881static void
15883 BinaryOperator *Bop) {
15884 assert(Bop->getOpcode() == BO_LAnd);
15885 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15886 << Bop->getSourceRange() << OpLoc;
15888 Self.PDiag(diag::note_precedence_silence)
15889 << Bop->getOpcodeStr(),
15890 Bop->getSourceRange());
15891}
15892
15893/// Look for '&&' in the left hand of a '||' expr.
15895 Expr *LHSExpr, Expr *RHSExpr) {
15896 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15897 if (Bop->getOpcode() == BO_LAnd) {
15898 // If it's "string_literal && a || b" don't warn since the precedence
15899 // doesn't matter.
15900 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15901 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15902 } else if (Bop->getOpcode() == BO_LOr) {
15903 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15904 // If it's "a || b && string_literal || c" we didn't warn earlier for
15905 // "a || b && string_literal", but warn now.
15906 if (RBop->getOpcode() == BO_LAnd &&
15907 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15908 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15909 }
15910 }
15911 }
15912}
15913
15914/// Look for '&&' in the right hand of a '||' expr.
15916 Expr *LHSExpr, Expr *RHSExpr) {
15917 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15918 if (Bop->getOpcode() == BO_LAnd) {
15919 // If it's "a || b && string_literal" don't warn since the precedence
15920 // doesn't matter.
15921 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15922 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15923 }
15924 }
15925}
15926
15927/// Look for bitwise op in the left or right hand of a bitwise op with
15928/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15929/// the '&' expression in parentheses.
15931 SourceLocation OpLoc, Expr *SubExpr) {
15932 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15933 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15934 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15935 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15936 << Bop->getSourceRange() << OpLoc;
15937 SuggestParentheses(S, Bop->getOperatorLoc(),
15938 S.PDiag(diag::note_precedence_silence)
15939 << Bop->getOpcodeStr(),
15940 Bop->getSourceRange());
15941 }
15942 }
15943}
15944
15946 Expr *SubExpr, StringRef Shift) {
15947 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15948 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15949 StringRef Op = Bop->getOpcodeStr();
15950 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15951 << Bop->getSourceRange() << OpLoc << Shift << Op;
15952 SuggestParentheses(S, Bop->getOperatorLoc(),
15953 S.PDiag(diag::note_precedence_silence) << Op,
15954 Bop->getSourceRange());
15955 }
15956 }
15957}
15958
15960 Expr *LHSExpr, Expr *RHSExpr) {
15961 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15962 if (!OCE)
15963 return;
15964
15965 FunctionDecl *FD = OCE->getDirectCallee();
15966 if (!FD || !FD->isOverloadedOperator())
15967 return;
15968
15970 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15971 return;
15972
15973 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15974 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15975 << (Kind == OO_LessLess);
15977 S.PDiag(diag::note_precedence_silence)
15978 << (Kind == OO_LessLess ? "<<" : ">>"),
15979 OCE->getSourceRange());
15981 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15982 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15983}
15984
15985/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15986/// precedence.
15988 SourceLocation OpLoc, Expr *LHSExpr,
15989 Expr *RHSExpr){
15990 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15992 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15993
15994 // Diagnose "arg1 & arg2 | arg3"
15995 if ((Opc == BO_Or || Opc == BO_Xor) &&
15996 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15997 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15998 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15999 }
16000
16001 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
16002 // We don't warn for 'assert(a || b && "bad")' since this is safe.
16003 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
16004 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
16005 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
16006 }
16007
16008 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
16009 || Opc == BO_Shr) {
16010 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
16011 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
16012 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
16013 }
16014
16015 // Warn on overloaded shift operators and comparisons, such as:
16016 // cout << 5 == 4;
16018 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
16019}
16020
16022 tok::TokenKind Kind,
16023 Expr *LHSExpr, Expr *RHSExpr) {
16024 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
16025 assert(LHSExpr && "ActOnBinOp(): missing left expression");
16026 assert(RHSExpr && "ActOnBinOp(): missing right expression");
16027
16028 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16029 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
16030
16034
16035 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
16036 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
16037
16038 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
16039}
16040
16042 UnresolvedSetImpl &Functions) {
16044 if (OverOp != OO_None && OverOp != OO_Equal)
16045 LookupOverloadedOperatorName(OverOp, S, Functions);
16046
16047 // In C++20 onwards, we may have a second operator to look up.
16048 if (getLangOpts().CPlusPlus20) {
16050 LookupOverloadedOperatorName(ExtraOp, S, Functions);
16051 }
16052}
16053
16054/// Build an overloaded binary operator expression in the given scope.
16057 Expr *LHS, Expr *RHS) {
16058 switch (Opc) {
16059 case BO_Assign:
16060 // In the non-overloaded case, we warn about self-assignment (x = x) for
16061 // both simple assignment and certain compound assignments where algebra
16062 // tells us the operation yields a constant result. When the operator is
16063 // overloaded, we can't do the latter because we don't want to assume that
16064 // those algebraic identities still apply; for example, a path-building
16065 // library might use operator/= to append paths. But it's still reasonable
16066 // to assume that simple assignment is just moving/copying values around
16067 // and so self-assignment is likely a bug.
16068 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
16069 [[fallthrough]];
16070 case BO_DivAssign:
16071 case BO_RemAssign:
16072 case BO_SubAssign:
16073 case BO_AndAssign:
16074 case BO_OrAssign:
16075 case BO_XorAssign:
16076 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
16077 break;
16078 default:
16079 break;
16080 }
16081
16082 // Find all of the overloaded operators visible from this point.
16083 UnresolvedSet<16> Functions;
16084 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
16085
16086 // Build the (potentially-overloaded, potentially-dependent)
16087 // binary operation.
16088 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
16089}
16090
16092 BinaryOperatorKind Opc, Expr *LHSExpr,
16093 Expr *RHSExpr, bool ForFoldExpression) {
16094 if (!LHSExpr || !RHSExpr)
16095 return ExprError();
16096
16097 // We want to end up calling one of SemaPseudoObject::checkAssignment
16098 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16099 // both expressions are overloadable or either is type-dependent),
16100 // or CreateBuiltinBinOp (in any other case). We also want to get
16101 // any placeholder types out of the way.
16102
16103 // Handle pseudo-objects in the LHS.
16104 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16105 // Assignments with a pseudo-object l-value need special analysis.
16106 if (pty->getKind() == BuiltinType::PseudoObject &&
16108 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
16109
16110 // Don't resolve overloads if the other type is overloadable.
16111 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16112 // We can't actually test that if we still have a placeholder,
16113 // though. Fortunately, none of the exceptions we see in that
16114 // code below are valid when the LHS is an overload set. Note
16115 // that an overload set can be dependently-typed, but it never
16116 // instantiates to having an overloadable type.
16117 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16118 if (resolvedRHS.isInvalid()) return ExprError();
16119 RHSExpr = resolvedRHS.get();
16120
16121 if (RHSExpr->isTypeDependent() ||
16122 RHSExpr->getType()->isOverloadableType())
16123 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16124 }
16125
16126 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16127 // template, diagnose the missing 'template' keyword instead of diagnosing
16128 // an invalid use of a bound member function.
16129 //
16130 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16131 // to C++1z [over.over]/1.4, but we already checked for that case above.
16132 if (Opc == BO_LT && inTemplateInstantiation() &&
16133 (pty->getKind() == BuiltinType::BoundMember ||
16134 pty->getKind() == BuiltinType::Overload)) {
16135 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
16136 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16137 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
16138 return isa<FunctionTemplateDecl>(ND);
16139 })) {
16140 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16141 : OE->getNameLoc(),
16142 diag::err_template_kw_missing)
16143 << OE->getName().getAsIdentifierInfo();
16144 return ExprError();
16145 }
16146 }
16147
16148 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
16149 if (LHS.isInvalid()) return ExprError();
16150 LHSExpr = LHS.get();
16151 }
16152
16153 // Handle pseudo-objects in the RHS.
16154 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16155 // An overload in the RHS can potentially be resolved by the type
16156 // being assigned to.
16157 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16158 if (getLangOpts().CPlusPlus &&
16159 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16160 LHSExpr->getType()->isOverloadableType()))
16161 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16162
16163 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16164 ForFoldExpression);
16165 }
16166
16167 // Don't resolve overloads if the other type is overloadable.
16168 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16169 LHSExpr->getType()->isOverloadableType())
16170 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16171
16172 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16173 if (!resolvedRHS.isUsable()) return ExprError();
16174 RHSExpr = resolvedRHS.get();
16175 }
16176
16177 if (getLangOpts().HLSL) {
16178 if (LHSExpr->getType()->isHLSLResourceRecord() ||
16179 LHSExpr->getType()->isHLSLResourceRecordArray()) {
16180 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, OpLoc))
16181 return ExprError();
16182 } else if (RHSExpr->getType()->isHLSLResourceRecord()) {
16183 std::optional<ExprResult> ConvRHS =
16185 if (ConvRHS && Context.hasSameUnqualifiedType(
16186 LHSExpr->getType(), ConvRHS->get()->getType())) {
16187 assert(!ConvRHS->isInvalid());
16188 RHSExpr = ConvRHS->get();
16189 }
16190 }
16191 }
16192
16193 if (getLangOpts().CPlusPlus) {
16194 bool CanOverloadBinOp =
16195 !getLangOpts().HLSL ||
16196 HLSL().canHaveOverloadedBinOp(LHSExpr->getType(), Opc) ||
16197 HLSL().canHaveOverloadedBinOp(RHSExpr->getType(), Opc);
16198 bool TypeDependent =
16199 LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent();
16200 bool Overloadable = LHSExpr->getType()->isOverloadableType() ||
16201 RHSExpr->getType()->isOverloadableType();
16202 if (CanOverloadBinOp && (TypeDependent || Overloadable))
16203 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16204 }
16205
16206 if (getLangOpts().RecoveryAST &&
16207 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16208 assert(!getLangOpts().CPlusPlus);
16209 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16210 "Should only occur in error-recovery path.");
16212 // C [6.15.16] p3:
16213 // An assignment expression has the value of the left operand after the
16214 // assignment, but is not an lvalue.
16216 Context, LHSExpr, RHSExpr, Opc,
16218 OpLoc, CurFPFeatureOverrides());
16219 QualType ResultType;
16220 switch (Opc) {
16221 case BO_Assign:
16222 ResultType = LHSExpr->getType().getUnqualifiedType();
16223 break;
16224 case BO_LT:
16225 case BO_GT:
16226 case BO_LE:
16227 case BO_GE:
16228 case BO_EQ:
16229 case BO_NE:
16230 case BO_LAnd:
16231 case BO_LOr:
16232 // These operators have a fixed result type regardless of operands.
16233 ResultType = Context.IntTy;
16234 break;
16235 case BO_Comma:
16236 ResultType = RHSExpr->getType();
16237 break;
16238 default:
16239 ResultType = Context.DependentTy;
16240 break;
16241 }
16242 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
16243 VK_PRValue, OK_Ordinary, OpLoc,
16245 }
16246
16247 // Build a built-in binary operation.
16248 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16249}
16250
16252 if (T.isNull() || T->isDependentType())
16253 return false;
16254
16255 if (!Ctx.isPromotableIntegerType(T))
16256 return true;
16257
16258 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
16259}
16260
16262 UnaryOperatorKind Opc, Expr *InputExpr,
16263 bool IsAfterAmp) {
16264 ExprResult Input = InputExpr;
16267 QualType resultType;
16268 bool CanOverflow = false;
16269
16270 bool ConvertHalfVec = false;
16271 if (getLangOpts().OpenCL) {
16272 QualType Ty = InputExpr->getType();
16273 // The only legal unary operation for atomics is '&'.
16274 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16275 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16276 // only with a builtin functions and therefore should be disallowed here.
16277 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16278 || Ty->isBlockPointerType())) {
16279 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16280 << InputExpr->getType()
16281 << Input.get()->getSourceRange());
16282 }
16283 }
16284
16285 if (getLangOpts().HLSL && OpLoc.isValid()) {
16286 if (Opc == UO_AddrOf)
16287 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
16288 if (Opc == UO_Deref)
16289 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
16290 }
16291
16292 if (InputExpr->isTypeDependent() &&
16293 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
16294 resultType = Context.DependentTy;
16295 } else {
16296 switch (Opc) {
16297 case UO_PreInc:
16298 case UO_PreDec:
16299 case UO_PostInc:
16300 case UO_PostDec:
16301 resultType =
16302 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
16303 Opc == UO_PreInc || Opc == UO_PostInc,
16304 Opc == UO_PreInc || Opc == UO_PreDec);
16305 CanOverflow = isOverflowingIntegerType(Context, resultType);
16306 break;
16307 case UO_AddrOf:
16308 resultType = CheckAddressOfOperand(Input, OpLoc);
16309 CheckAddressOfNoDeref(InputExpr);
16310 RecordModifiableNonNullParam(*this, InputExpr);
16311 break;
16312 case UO_Deref: {
16314 if (Input.isInvalid())
16315 return ExprError();
16316 resultType =
16317 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
16318 break;
16319 }
16320 case UO_Plus:
16321 case UO_Minus:
16322 CanOverflow = Opc == UO_Minus &&
16324 Input = UsualUnaryConversions(Input.get());
16325 if (Input.isInvalid())
16326 return ExprError();
16327 // Unary plus and minus require promoting an operand of half vector to a
16328 // float vector and truncating the result back to a half vector. For now,
16329 // we do this only when HalfArgsAndReturns is set (that is, when the
16330 // target is arm or arm64).
16331 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
16332
16333 // If the operand is a half vector, promote it to a float vector.
16334 if (ConvertHalfVec)
16335 Input = convertVector(Input.get(), Context.FloatTy, *this);
16336 resultType = Input.get()->getType();
16337 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16338 break;
16339 else if (resultType->isVectorType() &&
16340 // The z vector extensions don't allow + or - with bool vectors.
16341 (!Context.getLangOpts().ZVector ||
16342 resultType->castAs<VectorType>()->getVectorKind() !=
16344 break;
16345 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16346 break;
16347 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16348 Opc == UO_Plus && resultType->isPointerType())
16349 break;
16350
16351 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16352 << resultType << Input.get()->getSourceRange());
16353
16354 case UO_Not: // bitwise complement
16355 Input = UsualUnaryConversions(Input.get());
16356 if (Input.isInvalid())
16357 return ExprError();
16358 resultType = Input.get()->getType();
16359 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16360 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16361 // C99 does not support '~' for complex conjugation.
16362 Diag(OpLoc, diag::ext_integer_complement_complex)
16363 << resultType << Input.get()->getSourceRange();
16364 else if (resultType->hasIntegerRepresentation())
16365 break;
16366 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16367 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16368 // on vector float types.
16369 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16370 if (!T->isIntegerType())
16371 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16372 << resultType << Input.get()->getSourceRange());
16373 } else {
16374 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16375 << resultType << Input.get()->getSourceRange());
16376 }
16377 break;
16378
16379 case UO_LNot: // logical negation
16380 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16382 if (Input.isInvalid())
16383 return ExprError();
16384 resultType = Input.get()->getType();
16385
16386 // Though we still have to promote half FP to float...
16387 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16388 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
16389 .get();
16390 resultType = Context.FloatTy;
16391 }
16392
16393 // WebAsembly tables can't be used in unary expressions.
16394 if (resultType->isPointerType() &&
16396 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16397 << resultType << Input.get()->getSourceRange());
16398 }
16399
16400 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16401 // C99 6.5.3.3p1: ok, fallthrough;
16402 if (Context.getLangOpts().CPlusPlus) {
16403 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16404 // operand contextually converted to bool.
16405 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16406 ScalarTypeToBooleanCastKind(resultType));
16407 } else if (Context.getLangOpts().OpenCL &&
16408 Context.getLangOpts().OpenCLVersion < 120) {
16409 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16410 // operate on scalar float types.
16411 if (!resultType->isIntegerType() && !resultType->isPointerType())
16412 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16413 << resultType << Input.get()->getSourceRange());
16414 }
16415 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16416 !resultType->hasBooleanRepresentation()) {
16417 // HLSL unary logical 'not' behaves like C++, which states that the
16418 // operand is converted to bool and the result is bool, however HLSL
16419 // extends this property to vectors.
16420 const VectorType *VTy = resultType->castAs<VectorType>();
16421 resultType =
16422 Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
16423
16424 Input = ImpCastExprToType(
16425 Input.get(), resultType,
16427 .get();
16428 break;
16429 } else if (resultType->isExtVectorType()) {
16430 if (Context.getLangOpts().OpenCL &&
16431 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16432 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16433 // operate on vector float types.
16434 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16435 if (!T->isIntegerType())
16436 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16437 << resultType << Input.get()->getSourceRange());
16438 }
16439 // Vector logical not returns the signed variant of the operand type.
16440 resultType = GetSignedVectorType(resultType);
16441 break;
16442 } else if (Context.getLangOpts().CPlusPlus &&
16443 resultType->isVectorType()) {
16444 const VectorType *VTy = resultType->castAs<VectorType>();
16445 if (VTy->getVectorKind() != VectorKind::Generic)
16446 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16447 << resultType << Input.get()->getSourceRange());
16448
16449 // Vector logical not returns the signed variant of the operand type.
16450 resultType = GetSignedVectorType(resultType);
16451 break;
16452 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16453 resultType = Context.getLogicalOperationType();
16454 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(InputExpr);
16455 break;
16456 } else {
16457 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16458 << resultType << Input.get()->getSourceRange());
16459 }
16460
16461 // LNot always has type int. C99 6.5.3.3p5.
16462 // In C++, it's bool. C++ 5.3.1p8
16463 resultType = Context.getLogicalOperationType();
16464 break;
16465 case UO_Real:
16466 case UO_Imag:
16467 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16468 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16469 // ordinary complex l-values to ordinary l-values and all other values to
16470 // r-values.
16471 if (Input.isInvalid())
16472 return ExprError();
16473 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16474 if (Input.get()->isGLValue() &&
16475 Input.get()->getObjectKind() == OK_Ordinary)
16476 VK = Input.get()->getValueKind();
16477 } else if (!getLangOpts().CPlusPlus) {
16478 // In C, a volatile scalar is read by __imag. In C++, it is not.
16479 Input = DefaultLvalueConversion(Input.get());
16480 }
16481 break;
16482 case UO_Extension:
16483 resultType = Input.get()->getType();
16484 VK = Input.get()->getValueKind();
16485 OK = Input.get()->getObjectKind();
16486 break;
16487 case UO_Coawait:
16488 // It's unnecessary to represent the pass-through operator co_await in the
16489 // AST; just return the input expression instead.
16490 assert(!Input.get()->getType()->isDependentType() &&
16491 "the co_await expression must be non-dependant before "
16492 "building operator co_await");
16493 return Input;
16494 }
16495 }
16496 if (resultType.isNull() || Input.isInvalid())
16497 return ExprError();
16498
16499 // Check for array bounds violations in the operand of the UnaryOperator,
16500 // except for the '*' and '&' operators that have to be handled specially
16501 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16502 // that are explicitly defined as valid by the standard).
16503 if (Opc != UO_AddrOf && Opc != UO_Deref)
16504 CheckArrayAccess(Input.get());
16505
16506 auto *UO =
16507 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16508 OpLoc, CanOverflow, CurFPFeatureOverrides());
16509
16510 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16511 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16513 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16514
16515 // Convert the result back to a half vector.
16516 if (ConvertHalfVec)
16517 return convertVector(UO, Context.HalfTy, *this);
16518 return UO;
16519}
16520
16522 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16523 if (!DRE->getQualifier())
16524 return false;
16525
16526 ValueDecl *VD = DRE->getDecl();
16527 if (!VD->isCXXClassMember())
16528 return false;
16529
16531 return true;
16532 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16533 return Method->isImplicitObjectMemberFunction();
16534
16535 return false;
16536 }
16537
16538 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16539 if (!ULE->getQualifier())
16540 return false;
16541
16542 for (NamedDecl *D : ULE->decls()) {
16543 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16544 if (Method->isImplicitObjectMemberFunction())
16545 return true;
16546 } else {
16547 // Overload set does not contain methods.
16548 break;
16549 }
16550 }
16551
16552 return false;
16553 }
16554
16555 return false;
16556}
16557
16559 UnaryOperatorKind Opc, Expr *Input,
16560 bool IsAfterAmp) {
16561 // First things first: handle placeholders so that the
16562 // overloaded-operator check considers the right type.
16563 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16564 // Increment and decrement of pseudo-object references.
16565 if (pty->getKind() == BuiltinType::PseudoObject &&
16567 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
16568
16569 // extension is always a builtin operator.
16570 if (Opc == UO_Extension)
16571 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16572
16573 // & gets special logic for several kinds of placeholder.
16574 // The builtin code knows what to do.
16575 if (Opc == UO_AddrOf &&
16576 (pty->getKind() == BuiltinType::Overload ||
16577 pty->getKind() == BuiltinType::UnknownAny ||
16578 pty->getKind() == BuiltinType::BoundMember))
16579 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16580
16581 // Anything else needs to be handled now.
16583 if (Result.isInvalid()) return ExprError();
16584 Input = Result.get();
16585 }
16586
16587 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16589 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16590 // Find all of the overloaded operators visible from this point.
16591 UnresolvedSet<16> Functions;
16593 if (S && OverOp != OO_None)
16594 LookupOverloadedOperatorName(OverOp, S, Functions);
16595
16596 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16597 }
16598
16599 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16600}
16601
16603 Expr *Input, bool IsAfterAmp) {
16604 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16605 IsAfterAmp);
16606}
16607
16609 LabelDecl *TheDecl) {
16610 TheDecl->markUsed(Context);
16611 // Create the AST node. The address of a label always has type 'void*'.
16612 auto *Res = new (Context) AddrLabelExpr(
16613 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16614
16615 if (getCurFunction())
16616 getCurFunction()->AddrLabels.push_back(Res);
16617
16618 return Res;
16619}
16620
16623 // Make sure we diagnose jumping into a statement expression.
16625}
16626
16628 // Note that function is also called by TreeTransform when leaving a
16629 // StmtExpr scope without rebuilding anything.
16630
16633}
16634
16636 SourceLocation RPLoc) {
16637 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16638}
16639
16641 SourceLocation RPLoc, unsigned TemplateDepth) {
16642 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16643 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16644
16647 assert(!Cleanup.exprNeedsCleanups() &&
16648 "cleanups within StmtExpr not correctly bound!");
16650
16651 // FIXME: there are a variety of strange constraints to enforce here, for
16652 // example, it is not possible to goto into a stmt expression apparently.
16653 // More semantic analysis is needed.
16654
16655 // If there are sub-stmts in the compound stmt, take the type of the last one
16656 // as the type of the stmtexpr.
16657 QualType Ty = Context.VoidTy;
16658 bool StmtExprMayBindToTemp = false;
16659 if (!Compound->body_empty()) {
16660 if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
16661 if (const Expr *Value = LastStmt->getExprStmt()) {
16662 StmtExprMayBindToTemp = true;
16663 Ty = Value->getType();
16664 }
16665 }
16666 }
16667
16668 // FIXME: Check that expression type is complete/non-abstract; statement
16669 // expressions are not lvalues.
16670 Expr *ResStmtExpr =
16671 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16672 if (StmtExprMayBindToTemp)
16673 return MaybeBindToTemporary(ResStmtExpr);
16674 return ResStmtExpr;
16675}
16676
16678 if (ER.isInvalid())
16679 return ExprError();
16680
16681 // Do function/array conversion on the last expression, but not
16682 // lvalue-to-rvalue. However, initialize an unqualified type.
16684 if (ER.isInvalid())
16685 return ExprError();
16686 Expr *E = ER.get();
16687
16688 if (E->isTypeDependent())
16689 return E;
16690
16691 // In ARC, if the final expression ends in a consume, splice
16692 // the consume out and bind it later. In the alternate case
16693 // (when dealing with a retainable type), the result
16694 // initialization will create a produce. In both cases the
16695 // result will be +1, and we'll need to balance that out with
16696 // a bind.
16697 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16698 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16699 return Cast->getSubExpr();
16700
16701 // FIXME: Provide a better location for the initialization.
16705 SourceLocation(), E);
16706}
16707
16709 TypeSourceInfo *TInfo,
16710 const Designation &Desig,
16711 SourceLocation RParenLoc) {
16712 QualType ArgTy = TInfo->getType();
16713 bool Dependent = ArgTy->isDependentType();
16714 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16715
16716 // We must have at least one component that refers to the type, and the first
16717 // one is known to be a field designator. Verify that the ArgTy represents
16718 // a struct/union/class.
16719 if (!Dependent && !ArgTy->isRecordType())
16720 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16721 << ArgTy << TypeRange);
16722
16723 // Type must be complete per C99 7.17p3 because a declaring a variable
16724 // with an incomplete type would be ill-formed.
16725 if (!Dependent
16726 && RequireCompleteType(BuiltinLoc, ArgTy,
16727 diag::err_offsetof_incomplete_type, TypeRange))
16728 return ExprError();
16729
16730 bool DidWarnAboutNonPOD = false;
16731 QualType CurrentType = ArgTy;
16734 for (unsigned I = 0, N = Desig.getNumDesignators(); I != N; ++I) {
16735 const Designator &D = Desig.getDesignator(I);
16736 assert(!D.isArrayRangeDesignator());
16737 if (D.isArrayDesignator()) {
16738 // Offset of an array sub-field. TODO: Should we allow vector elements?
16739 if (!CurrentType->isDependentType()) {
16740 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16741 if(!AT)
16742 return ExprError(Diag(D.getEndLoc(), diag::err_offsetof_array_type)
16743 << CurrentType);
16744 CurrentType = AT->getElementType();
16745 } else
16746 CurrentType = Context.DependentTy;
16747
16749 if (IdxRval.isInvalid())
16750 return ExprError();
16751 Expr *Idx = IdxRval.get();
16752
16753 // The expression must be an integral expression.
16754 // FIXME: An integral constant expression?
16755 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16756 !Idx->getType()->isIntegerType())
16757 return ExprError(
16758 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16759 << Idx->getSourceRange());
16760
16761 // Record this array index.
16762 Comps.push_back(
16763 OffsetOfNode(D.getBeginLoc(), Exprs.size(), D.getEndLoc()));
16764 Exprs.push_back(Idx);
16765 continue;
16766 }
16767
16768 assert(D.isFieldDesignator());
16769 const IdentifierInfo *Name = D.getFieldDecl();
16770
16771 // Offset of a field.
16772 if (CurrentType->isDependentType()) {
16773 // We have the offset of a field, but we can't look into the dependent
16774 // type. Just record the identifier of the field.
16775 Comps.push_back(OffsetOfNode(D.getBeginLoc(), Name, D.getEndLoc()));
16776 CurrentType = Context.DependentTy;
16777 continue;
16778 }
16779
16780 // We need to have a complete type to look into.
16781 if (RequireCompleteType(D.getBeginLoc(), CurrentType,
16782 diag::err_offsetof_incomplete_type))
16783 return ExprError();
16784
16785 // Look for the designated field.
16786 auto *RD = CurrentType->getAsRecordDecl();
16787 if (!RD)
16788 return ExprError(Diag(D.getEndLoc(), diag::err_offsetof_record_type)
16789 << CurrentType);
16790
16791 // C++ [lib.support.types]p5:
16792 // The macro offsetof accepts a restricted set of type arguments in this
16793 // International Standard. type shall be a POD structure or a POD union
16794 // (clause 9).
16795 // C++11 [support.types]p4:
16796 // If type is not a standard-layout class (Clause 9), the results are
16797 // undefined.
16798 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16799 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16800 unsigned DiagID =
16801 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16802 : diag::ext_offsetof_non_pod_type;
16803
16804 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16805 Diag(BuiltinLoc, DiagID)
16807 << CurrentType;
16808 DidWarnAboutNonPOD = true;
16809 }
16810 }
16811
16812 // Look for the field.
16813 LookupResult R(*this, Name, D.getBeginLoc(), LookupMemberName);
16814 LookupQualifiedName(R, RD);
16815 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16816 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16817 if (!MemberDecl) {
16818 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16819 MemberDecl = IndirectMemberDecl->getAnonField();
16820 }
16821
16822 if (!MemberDecl) {
16823 // Lookup could be ambiguous when looking up a placeholder variable
16824 // __builtin_offsetof(S, _).
16825 // In that case we would already have emitted a diagnostic
16826 if (!R.isAmbiguous())
16827 Diag(BuiltinLoc, diag::err_no_member)
16828 << Name << RD << SourceRange(D.getBeginLoc(), D.getEndLoc());
16829 return ExprError();
16830 }
16831
16832 // C99 7.17p3:
16833 // (If the specified member is a bit-field, the behavior is undefined.)
16834 //
16835 // We diagnose this as an error.
16836 if (MemberDecl->isBitField()) {
16837 Diag(D.getEndLoc(), diag::err_offsetof_bitfield)
16838 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
16839 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16840 return ExprError();
16841 }
16842
16843 RecordDecl *Parent = MemberDecl->getParent();
16844 if (IndirectMemberDecl)
16845 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16846
16847 // If the member was found in a base class, introduce OffsetOfNodes for
16848 // the base class indirections.
16849 CXXBasePaths Paths;
16850 if (IsDerivedFrom(D.getBeginLoc(), CurrentType,
16851 Context.getCanonicalTagType(Parent), Paths)) {
16852 if (Paths.getDetectedVirtual()) {
16853 Diag(D.getEndLoc(), diag::err_offsetof_field_of_virtual_base)
16854 << MemberDecl->getDeclName() << SourceRange(BuiltinLoc, RParenLoc);
16855 return ExprError();
16856 }
16857
16858 CXXBasePath &Path = Paths.front();
16859 for (const CXXBasePathElement &B : Path)
16860 Comps.push_back(OffsetOfNode(B.Base));
16861 }
16862
16863 if (IndirectMemberDecl) {
16864 for (auto *FI : IndirectMemberDecl->chain()) {
16865 assert(isa<FieldDecl>(FI));
16866 Comps.push_back(
16868 }
16869 } else
16870 Comps.push_back(OffsetOfNode(D.getBeginLoc(), MemberDecl, D.getEndLoc()));
16871
16872 CurrentType = MemberDecl->getType().getNonReferenceType();
16873 }
16874
16875 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16876 Comps, Exprs, RParenLoc);
16877}
16878
16881 ParsedType ParsedArgTy,
16882 const Designation &Desig,
16883 SourceLocation RParenLoc) {
16884
16885 TypeSourceInfo *ArgTInfo;
16886 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16887 if (ArgTy.isNull())
16888 return ExprError();
16889
16890 if (!ArgTInfo)
16891 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16892
16893 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Desig, RParenLoc);
16894}
16895
16897 Expr *CondExpr,
16898 Expr *LHSExpr, Expr *RHSExpr,
16899 SourceLocation RPLoc) {
16900 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16901
16904 QualType resType;
16905 bool CondIsTrue = false;
16906 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16907 resType = Context.DependentTy;
16908 } else {
16909 // The conditional expression is required to be a constant expression.
16910 llvm::APSInt condEval(32);
16912 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16913 if (CondICE.isInvalid())
16914 return ExprError();
16915 CondExpr = CondICE.get();
16916 CondIsTrue = condEval.getZExtValue();
16917
16918 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16919 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16920
16921 resType = ActiveExpr->getType();
16922 VK = ActiveExpr->getValueKind();
16923 OK = ActiveExpr->getObjectKind();
16924 }
16925
16926 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16927 resType, VK, OK, RPLoc, CondIsTrue);
16928}
16929
16930//===----------------------------------------------------------------------===//
16931// Clang Extensions.
16932//===----------------------------------------------------------------------===//
16933
16934void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16936
16937 if (LangOpts.CPlusPlus) {
16939 Decl *ManglingContextDecl;
16940 std::tie(MCtx, ManglingContextDecl) =
16941 getCurrentMangleNumberContext(Block->getDeclContext());
16942 if (MCtx) {
16943 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16944 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16945 }
16946 }
16947
16948 PushBlockScope(CurScope, Block);
16949 CurContext->addDecl(Block);
16950 if (CurScope)
16951 PushDeclContext(CurScope, Block);
16952 else
16953 CurContext = Block;
16954
16956
16957 // Enter a new evaluation context to insulate the block from any
16958 // cleanups from the enclosing full-expression.
16961}
16962
16964 Scope *CurScope) {
16965 assert(ParamInfo.getIdentifier() == nullptr &&
16966 "block-id should have no identifier!");
16967 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16968 BlockScopeInfo *CurBlock = getCurBlock();
16969
16970 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16971 QualType T = Sig->getType();
16973
16974 // GetTypeForDeclarator always produces a function type for a block
16975 // literal signature. Furthermore, it is always a FunctionProtoType
16976 // unless the function was written with a typedef.
16977 assert(T->isFunctionType() &&
16978 "GetTypeForDeclarator made a non-function block signature");
16979
16980 // Look for an explicit signature in that function type.
16981 FunctionProtoTypeLoc ExplicitSignature;
16982
16983 if ((ExplicitSignature = Sig->getTypeLoc()
16985
16986 // Check whether that explicit signature was synthesized by
16987 // GetTypeForDeclarator. If so, don't save that as part of the
16988 // written signature.
16989 if (ExplicitSignature.getLocalRangeBegin() ==
16990 ExplicitSignature.getLocalRangeEnd()) {
16991 // This would be much cheaper if we stored TypeLocs instead of
16992 // TypeSourceInfos.
16993 TypeLoc Result = ExplicitSignature.getReturnLoc();
16994 unsigned Size = Result.getFullDataSize();
16995 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16996 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16997
16998 ExplicitSignature = FunctionProtoTypeLoc();
16999 }
17000 }
17001
17002 CurBlock->TheDecl->setSignatureAsWritten(Sig);
17003 CurBlock->FunctionType = T;
17004
17005 const auto *Fn = T->castAs<FunctionType>();
17006 QualType RetTy = Fn->getReturnType();
17007 bool isVariadic =
17008 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
17009
17010 CurBlock->TheDecl->setIsVariadic(isVariadic);
17011
17012 // Context.DependentTy is used as a placeholder for a missing block
17013 // return type. TODO: what should we do with declarators like:
17014 // ^ * { ... }
17015 // If the answer is "apply template argument deduction"....
17016 if (RetTy != Context.DependentTy) {
17017 CurBlock->ReturnType = RetTy;
17018 CurBlock->TheDecl->setBlockMissingReturnType(false);
17019 CurBlock->HasImplicitReturnType = false;
17020 }
17021
17022 // Push block parameters from the declarator if we had them.
17024 if (ExplicitSignature) {
17025 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
17026 ParmVarDecl *Param = ExplicitSignature.getParam(I);
17027 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
17028 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
17029 // Diagnose this as an extension in C17 and earlier.
17030 if (!getLangOpts().C23)
17031 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
17032 }
17033 Params.push_back(Param);
17034 }
17035
17036 // Fake up parameter variables if we have a typedef, like
17037 // ^ fntype { ... }
17038 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
17039 for (const auto &I : Fn->param_types()) {
17041 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
17042 Params.push_back(Param);
17043 }
17044 }
17045
17046 // Set the parameters on the block decl.
17047 if (!Params.empty()) {
17048 CurBlock->TheDecl->setParams(Params);
17050 /*CheckParameterNames=*/false);
17051 }
17052
17053 // Finally we can process decl attributes.
17054 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
17055
17056 // Put the parameter variables in scope.
17057 for (auto *AI : CurBlock->TheDecl->parameters()) {
17058 AI->setOwningFunction(CurBlock->TheDecl);
17059
17060 // If this has an identifier, add it to the scope stack.
17061 if (AI->getIdentifier()) {
17062 CheckShadow(CurBlock->TheScope, AI);
17063
17064 PushOnScopeChains(AI, CurBlock->TheScope);
17065 }
17066
17067 if (AI->isInvalidDecl())
17068 CurBlock->TheDecl->setInvalidDecl();
17069 }
17070}
17071
17072void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17073 // Leave the expression-evaluation context.
17076
17077 // Pop off CurBlock, handle nested blocks.
17080}
17081
17083 Stmt *Body, Scope *CurScope) {
17084 // If blocks are disabled, emit an error.
17085 if (!LangOpts.Blocks)
17086 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
17087
17088 // Leave the expression-evaluation context.
17091 assert(!Cleanup.exprNeedsCleanups() &&
17092 "cleanups within block not correctly bound!");
17094
17096 BlockDecl *BD = BSI->TheDecl;
17097
17099
17100 if (BSI->HasImplicitReturnType)
17102
17103 QualType RetTy = Context.VoidTy;
17104 if (!BSI->ReturnType.isNull())
17105 RetTy = BSI->ReturnType;
17106
17107 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17108 QualType BlockTy;
17109
17110 // If the user wrote a function type in some form, try to use that.
17111 if (!BSI->FunctionType.isNull()) {
17112 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17113
17114 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17115 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
17116
17117 // Turn protoless block types into nullary block types.
17118 if (isa<FunctionNoProtoType>(FTy)) {
17120 EPI.ExtInfo = Ext;
17121 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17122
17123 // Otherwise, if we don't need to change anything about the function type,
17124 // preserve its sugar structure.
17125 } else if (FTy->getReturnType() == RetTy &&
17126 (!NoReturn || FTy->getNoReturnAttr())) {
17127 BlockTy = BSI->FunctionType;
17128
17129 // Otherwise, make the minimal modifications to the function type.
17130 } else {
17133 EPI.TypeQuals = Qualifiers();
17134 EPI.ExtInfo = Ext;
17135 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
17136 }
17137
17138 // If we don't have a function type, just build one from nothing.
17139 } else {
17141 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
17142 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17143 }
17144
17146 BlockTy = Context.getBlockPointerType(BlockTy);
17147
17148 // If needed, diagnose invalid gotos and switches in the block.
17149 if (getCurFunction()->NeedsScopeChecking() &&
17150 !PP.isCodeCompletionEnabled())
17152
17153 BD->setBody(cast<CompoundStmt>(Body));
17154
17155 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17157
17158 // Try to apply the named return value optimization. We have to check again
17159 // if we can do this, though, because blocks keep return statements around
17160 // to deduce an implicit return type.
17161 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17162 !BD->isDependentContext())
17163 computeNRVO(Body, BSI);
17164
17170
17172
17173 // Set the captured variables on the block.
17175 for (Capture &Cap : BSI->Captures) {
17176 if (Cap.isInvalid() || Cap.isThisCapture())
17177 continue;
17178 // Cap.getVariable() is always a VarDecl because
17179 // blocks cannot capture structured bindings or other ValueDecl kinds.
17180 auto *Var = cast<VarDecl>(Cap.getVariable());
17181 Expr *CopyExpr = nullptr;
17182 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17183 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17184 // The capture logic needs the destructor, so make sure we mark it.
17185 // Usually this is unnecessary because most local variables have
17186 // their destructors marked at declaration time, but parameters are
17187 // an exception because it's technically only the call site that
17188 // actually requires the destructor.
17189 if (isa<ParmVarDecl>(Var))
17191
17192 // Enter a separate potentially-evaluated context while building block
17193 // initializers to isolate their cleanups from those of the block
17194 // itself.
17195 // FIXME: Is this appropriate even when the block itself occurs in an
17196 // unevaluated operand?
17199
17200 SourceLocation Loc = Cap.getLocation();
17201
17203 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
17204
17205 // According to the blocks spec, the capture of a variable from
17206 // the stack requires a const copy constructor. This is not true
17207 // of the copy/move done to move a __block variable to the heap.
17208 if (!Result.isInvalid() &&
17209 !Result.get()->getType().isConstQualified()) {
17211 Result.get()->getType().withConst(),
17212 CK_NoOp, VK_LValue);
17213 }
17214
17215 if (!Result.isInvalid()) {
17217 InitializedEntity::InitializeBlock(Var->getLocation(),
17218 Cap.getCaptureType()),
17219 Loc, Result.get());
17220 }
17221
17222 // Build a full-expression copy expression if initialization
17223 // succeeded and used a non-trivial constructor. Recover from
17224 // errors by pretending that the copy isn't necessary.
17225 if (!Result.isInvalid() &&
17226 !cast<CXXConstructExpr>(Result.get())->getConstructor()
17227 ->isTrivial()) {
17229 CopyExpr = Result.get();
17230 }
17231 }
17232 }
17233
17234 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17235 CopyExpr);
17236 Captures.push_back(NewCap);
17237 }
17238 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
17239
17240 // Pop the block scope now but keep it alive to the end of this function.
17242 AnalysisWarnings.getPolicyInEffectAt(Body->getEndLoc());
17243 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
17244
17245 BlockExpr *Result = new (Context)
17246 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17247
17248 // If the block isn't obviously global, i.e. it captures anything at
17249 // all, then we need to do a few things in the surrounding context:
17250 if (Result->getBlockDecl()->hasCaptures()) {
17251 // First, this expression has a new cleanup object.
17252 ExprCleanupObjects.push_back(Result->getBlockDecl());
17253 Cleanup.setExprNeedsCleanups(true);
17254
17255 // It also gets a branch-protected scope if any of the captured
17256 // variables needs destruction.
17257 for (const auto &CI : Result->getBlockDecl()->captures()) {
17258 const VarDecl *var = CI.getVariable();
17259 if (var->getType().isDestructedType() != QualType::DK_none) {
17261 break;
17262 }
17263 }
17264 }
17265
17266 if (getCurFunction())
17267 getCurFunction()->addBlock(BD);
17268
17269 // This can happen if the block's return type is deduced, but
17270 // the return expression is invalid.
17271 if (BD->isInvalidDecl())
17272 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
17273 {Result}, Result->getType());
17274 return Result;
17275}
17276
17278 SourceLocation RPLoc) {
17279 TypeSourceInfo *TInfo;
17280 GetTypeFromParser(Ty, &TInfo);
17281 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17282}
17283
17285 Expr *E, TypeSourceInfo *TInfo,
17286 SourceLocation RPLoc) {
17287 Expr *OrigExpr = E;
17288 bool IsMS = false;
17289
17290 // CUDA device global function does not support varargs.
17291 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17292 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
17295 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
17296 }
17297 }
17298
17299 // NVPTX does not support va_arg expression.
17300 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17301 Context.getTargetInfo().getTriple().isNVPTX())
17302 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
17303
17304 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17305 // as Microsoft ABI on an actual Microsoft platform, where
17306 // __builtin_ms_va_list and __builtin_va_list are the same.)
17307 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17308 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17309 QualType MSVaListType = Context.getBuiltinMSVaListType();
17310 if (Context.hasSameType(MSVaListType, E->getType())) {
17311 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
17312 return ExprError();
17313 IsMS = true;
17314 }
17315 }
17316
17317 // Get the va_list type
17318 QualType VaListType = Context.getBuiltinVaListType();
17319 if (!IsMS) {
17320 if (VaListType->isArrayType()) {
17321 // Deal with implicit array decay; for example, on x86-64,
17322 // va_list is an array, but it's supposed to decay to
17323 // a pointer for va_arg.
17324 VaListType = Context.getArrayDecayedType(VaListType);
17325 // Make sure the input expression also decays appropriately.
17327 if (Result.isInvalid())
17328 return ExprError();
17329 E = Result.get();
17330 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17331 // If va_list is a record type and we are compiling in C++ mode,
17332 // check the argument using reference binding.
17334 Context, Context.getLValueReferenceType(VaListType), false);
17336 if (Init.isInvalid())
17337 return ExprError();
17338 E = Init.getAs<Expr>();
17339 } else {
17340 // Otherwise, the va_list argument must be an l-value because
17341 // it is modified by va_arg.
17342 if (!E->isTypeDependent() &&
17343 CheckForModifiableLvalue(E, BuiltinLoc, *this))
17344 return ExprError();
17345 }
17346 }
17347
17348 if (!IsMS && !E->isTypeDependent() &&
17349 !Context.hasSameType(VaListType, E->getType()))
17350 return ExprError(
17351 Diag(E->getBeginLoc(),
17352 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17353 << OrigExpr->getType() << E->getSourceRange());
17354
17355 if (!TInfo->getType()->isDependentType()) {
17356 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17357 diag::err_second_parameter_to_va_arg_incomplete,
17358 TInfo->getTypeLoc()))
17359 return ExprError();
17360
17362 TInfo->getType(),
17363 diag::err_second_parameter_to_va_arg_abstract,
17364 TInfo->getTypeLoc()))
17365 return ExprError();
17366
17367 if (!TInfo->getType().isPODType(Context)) {
17368 Diag(TInfo->getTypeLoc().getBeginLoc(),
17369 TInfo->getType()->isObjCLifetimeType()
17370 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17371 : diag::warn_second_parameter_to_va_arg_not_pod)
17372 << TInfo->getType()
17373 << TInfo->getTypeLoc().getSourceRange();
17374 }
17375
17376 if (TInfo->getType()->isArrayType()) {
17378 PDiag(diag::warn_second_parameter_to_va_arg_array)
17379 << TInfo->getType()
17380 << TInfo->getTypeLoc().getSourceRange());
17381 }
17382
17383 // Check for va_arg where arguments of the given type will be promoted
17384 // (i.e. this va_arg is guaranteed to have undefined behavior).
17385 QualType PromoteType;
17386 if (Context.isPromotableIntegerType(TInfo->getType())) {
17387 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17388 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17389 // and C23 7.16.1.1p2 says, in part:
17390 // If type is not compatible with the type of the actual next argument
17391 // (as promoted according to the default argument promotions), the
17392 // behavior is undefined, except for the following cases:
17393 // - both types are pointers to qualified or unqualified versions of
17394 // compatible types;
17395 // - one type is compatible with a signed integer type, the other
17396 // type is compatible with the corresponding unsigned integer type,
17397 // and the value is representable in both types;
17398 // - one type is pointer to qualified or unqualified void and the
17399 // other is a pointer to a qualified or unqualified character type;
17400 // - or, the type of the next argument is nullptr_t and type is a
17401 // pointer type that has the same representation and alignment
17402 // requirements as a pointer to a character type.
17403 // Given that type compatibility is the primary requirement (ignoring
17404 // qualifications), you would think we could call typesAreCompatible()
17405 // directly to test this. However, in C++, that checks for *same type*,
17406 // which causes false positives when passing an enumeration type to
17407 // va_arg. Instead, get the underlying type of the enumeration and pass
17408 // that.
17409 QualType UnderlyingType = TInfo->getType();
17410 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17411 UnderlyingType = ED->getIntegerType();
17412 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17413 /*CompareUnqualified*/ true))
17414 PromoteType = QualType();
17415
17416 // If the types are still not compatible, we need to test whether the
17417 // promoted type and the underlying type are the same except for
17418 // signedness. Ask the AST for the correctly corresponding type and see
17419 // if that's compatible.
17420 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17421 PromoteType->isUnsignedIntegerType() !=
17422 UnderlyingType->isUnsignedIntegerType()) {
17423 UnderlyingType =
17424 UnderlyingType->isUnsignedIntegerType()
17425 ? Context.getCorrespondingSignedType(UnderlyingType)
17426 : Context.getCorrespondingUnsignedType(UnderlyingType);
17427 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17428 /*CompareUnqualified*/ true))
17429 PromoteType = QualType();
17430 }
17431 }
17432 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17433 PromoteType = Context.DoubleTy;
17434 if (!PromoteType.isNull())
17436 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17437 << TInfo->getType()
17438 << PromoteType
17439 << TInfo->getTypeLoc().getSourceRange());
17440 }
17441
17443 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17444}
17445
17447 // The type of __null will be int or long, depending on the size of
17448 // pointers on the target.
17449 QualType Ty;
17450 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17451 if (pw == Context.getTargetInfo().getIntWidth())
17452 Ty = Context.IntTy;
17453 else if (pw == Context.getTargetInfo().getLongWidth())
17454 Ty = Context.LongTy;
17455 else if (pw == Context.getTargetInfo().getLongLongWidth())
17456 Ty = Context.LongLongTy;
17457 else {
17458 llvm_unreachable("I don't know size of pointer!");
17459 }
17460
17461 return new (Context) GNUNullExpr(Ty, TokenLoc);
17462}
17463
17465 CXXRecordDecl *ImplDecl = nullptr;
17466
17467 // Fetch the std::source_location::__impl decl.
17468 if (NamespaceDecl *Std = S.getStdNamespace()) {
17469 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17471 if (S.LookupQualifiedName(ResultSL, Std)) {
17472 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17473 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17475 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17476 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17477 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17478 }
17479 }
17480 }
17481 }
17482
17483 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17484 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17485 return nullptr;
17486 }
17487
17488 // Verify that __impl is a trivial struct type, with no base classes, and with
17489 // only the four expected fields.
17490 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17491 ImplDecl->getNumBases() != 0) {
17492 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17493 return nullptr;
17494 }
17495
17496 unsigned Count = 0;
17497 for (FieldDecl *F : ImplDecl->fields()) {
17498 StringRef Name = F->getName();
17499
17500 if (Name == "_M_file_name") {
17501 if (F->getType() !=
17503 break;
17504 Count++;
17505 } else if (Name == "_M_function_name") {
17506 if (F->getType() !=
17508 break;
17509 Count++;
17510 } else if (Name == "_M_line") {
17511 if (!F->getType()->isIntegerType())
17512 break;
17513 Count++;
17514 } else if (Name == "_M_column") {
17515 if (!F->getType()->isIntegerType())
17516 break;
17517 Count++;
17518 } else {
17519 Count = 100; // invalid
17520 break;
17521 }
17522 }
17523 if (Count != 4) {
17524 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17525 return nullptr;
17526 }
17527
17528 return ImplDecl;
17529}
17530
17532 SourceLocation BuiltinLoc,
17533 SourceLocation RPLoc) {
17534 QualType ResultTy;
17535 switch (Kind) {
17540 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17541 ResultTy =
17542 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17543 break;
17544 }
17547 ResultTy = Context.UnsignedIntTy;
17548 break;
17552 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17554 return ExprError();
17555 }
17556 ResultTy = Context.getPointerType(
17557 Context.getCanonicalTagType(StdSourceLocationImplDecl).withConst());
17558 break;
17559 }
17560
17561 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17562}
17563
17565 SourceLocation BuiltinLoc,
17566 SourceLocation RPLoc,
17567 DeclContext *ParentContext) {
17568 return new (Context)
17569 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17570}
17571
17573 StringLiteral *BinaryData, StringRef FileName) {
17575 Data->BinaryData = BinaryData;
17576 Data->FileName = FileName;
17577 return new (Context)
17578 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17579 Data->getDataElementCount());
17580}
17581
17583 const Expr *SrcExpr) {
17584 if (!DstType->isFunctionPointerType() ||
17585 !SrcExpr->getType()->isFunctionType())
17586 return false;
17587
17588 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17589 if (!DRE)
17590 return false;
17591
17592 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17593 if (!FD)
17594 return false;
17595
17597 /*Complain=*/true,
17598 SrcExpr->getBeginLoc());
17599}
17600
17602 SourceLocation Loc,
17603 QualType DstType, QualType SrcType,
17604 Expr *SrcExpr, AssignmentAction Action,
17605 bool *Complained) {
17606 if (Complained)
17607 *Complained = false;
17608
17609 // Decode the result (notice that AST's are still created for extensions).
17610 bool CheckInferredResultType = false;
17611 bool isInvalid = false;
17612 unsigned DiagKind = 0;
17613 ConversionFixItGenerator ConvHints;
17614 bool MayHaveConvFixit = false;
17615 bool MayHaveFunctionDiff = false;
17616 const ObjCInterfaceDecl *IFace = nullptr;
17617 const ObjCProtocolDecl *PDecl = nullptr;
17618
17619 switch (ConvTy) {
17621 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17622 return false;
17624 // Still a valid conversion, but we may want to diagnose for C++
17625 // compatibility reasons.
17626 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17627 break;
17629 if (getLangOpts().CPlusPlus) {
17630 DiagKind = diag::err_typecheck_convert_pointer_int;
17631 isInvalid = true;
17632 } else {
17633 DiagKind = diag::ext_typecheck_convert_pointer_int;
17634 }
17635 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17636 MayHaveConvFixit = true;
17637 break;
17639 if (getLangOpts().CPlusPlus) {
17640 DiagKind = diag::err_typecheck_convert_int_pointer;
17641 isInvalid = true;
17642 } else {
17643 DiagKind = diag::ext_typecheck_convert_int_pointer;
17644 }
17645 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17646 MayHaveConvFixit = true;
17647 break;
17649 DiagKind =
17650 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17651 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17652 MayHaveConvFixit = true;
17653 break;
17655 if (getLangOpts().CPlusPlus) {
17656 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17657 isInvalid = true;
17658 } else {
17659 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17660 }
17661 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17662 MayHaveConvFixit = true;
17663 break;
17666 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17667 } else if (getLangOpts().CPlusPlus) {
17668 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17669 isInvalid = true;
17670 } else {
17671 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17672 }
17673 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17674 SrcType->isObjCObjectPointerType();
17675 if (CheckInferredResultType) {
17676 SrcType = SrcType.getUnqualifiedType();
17677 DstType = DstType.getUnqualifiedType();
17678 } else {
17679 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17680 }
17681 MayHaveConvFixit = true;
17682 break;
17684 if (getLangOpts().CPlusPlus) {
17685 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17686 isInvalid = true;
17687 } else {
17688 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17689 }
17690 break;
17692 if (getLangOpts().CPlusPlus) {
17693 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17694 isInvalid = true;
17695 } else {
17696 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17697 }
17698 break;
17700 // Perform decay if necessary.
17701 if (SrcType->canDecayToPointerType())
17702 SrcType = Context.getDecayedType(SrcType);
17703
17704 isInvalid = true;
17705
17706 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17707 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17708 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17709 DiagKind = diag::err_typecheck_incompatible_address_space;
17710 break;
17711 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17712 DiagKind = diag::err_typecheck_incompatible_ownership;
17713 break;
17714 } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {
17715 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17716 break;
17717 }
17718
17719 llvm_unreachable("unknown error case for discarding qualifiers!");
17720 // fallthrough
17721 }
17723 if (SrcType->isArrayType())
17724 SrcType = Context.getArrayDecayedType(SrcType);
17725
17726 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17727 break;
17729 // If the qualifiers lost were because we were applying the
17730 // (deprecated) C++ conversion from a string literal to a char*
17731 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17732 // Ideally, this check would be performed in
17733 // checkPointerTypesForAssignment. However, that would require a
17734 // bit of refactoring (so that the second argument is an
17735 // expression, rather than a type), which should be done as part
17736 // of a larger effort to fix checkPointerTypesForAssignment for
17737 // C++ semantics.
17738 if (getLangOpts().CPlusPlus &&
17740 return false;
17741 if (getLangOpts().CPlusPlus) {
17742 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17743 isInvalid = true;
17744 } else {
17745 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17746 }
17747
17748 break;
17750 if (getLangOpts().CPlusPlus) {
17751 isInvalid = true;
17752 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17753 } else {
17754 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17755 }
17756 break;
17758 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17759 isInvalid = true;
17760 break;
17762 DiagKind = diag::err_int_to_block_pointer;
17763 isInvalid = true;
17764 break;
17766 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17767 isInvalid = true;
17768 break;
17770 if (SrcType->isObjCQualifiedIdType()) {
17771 const ObjCObjectPointerType *srcOPT =
17772 SrcType->castAs<ObjCObjectPointerType>();
17773 for (auto *srcProto : srcOPT->quals()) {
17774 PDecl = srcProto;
17775 break;
17776 }
17777 if (const ObjCInterfaceType *IFaceT =
17779 IFace = IFaceT->getDecl();
17780 }
17781 else if (DstType->isObjCQualifiedIdType()) {
17782 const ObjCObjectPointerType *dstOPT =
17783 DstType->castAs<ObjCObjectPointerType>();
17784 for (auto *dstProto : dstOPT->quals()) {
17785 PDecl = dstProto;
17786 break;
17787 }
17788 if (const ObjCInterfaceType *IFaceT =
17790 IFace = IFaceT->getDecl();
17791 }
17792 if (getLangOpts().CPlusPlus) {
17793 DiagKind = diag::err_incompatible_qualified_id;
17794 isInvalid = true;
17795 } else {
17796 DiagKind = diag::warn_incompatible_qualified_id;
17797 }
17798 break;
17799 }
17801 if (getLangOpts().CPlusPlus) {
17802 DiagKind = diag::err_incompatible_vectors;
17803 isInvalid = true;
17804 } else {
17805 DiagKind = diag::warn_incompatible_vectors;
17806 }
17807 break;
17809 DiagKind = diag::err_arc_weak_unavailable_assign;
17810 isInvalid = true;
17811 break;
17813 return false;
17815 assert(!SrcType->isFunctionType() &&
17816 "Unexpected function type found in IncompatibleOBTKinds assignment");
17817 if (SrcType->canDecayToPointerType())
17818 SrcType = Context.getDecayedType(SrcType);
17819
17820 auto getOBTKindName = [](QualType Ty) -> StringRef {
17821 if (Ty->isPointerType())
17822 Ty = Ty->getPointeeType();
17823 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
17824 return OBT->getBehaviorKind() ==
17825 OverflowBehaviorType::OverflowBehaviorKind::Trap
17826 ? "__ob_trap"
17827 : "__ob_wrap";
17828 }
17829 llvm_unreachable("OBT kind unhandled");
17830 };
17831
17832 Diag(Loc, diag::err_incompatible_obt_kinds_assignment)
17833 << DstType << SrcType << getOBTKindName(DstType)
17834 << getOBTKindName(SrcType);
17835 isInvalid = true;
17836 return true;
17837 }
17839 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17840 if (Complained)
17841 *Complained = true;
17842 return true;
17843 }
17844
17845 DiagKind = diag::err_typecheck_convert_incompatible;
17846 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17847 MayHaveConvFixit = true;
17848 isInvalid = true;
17849 MayHaveFunctionDiff = true;
17850 break;
17851 }
17852
17853 QualType FirstType, SecondType;
17854 switch (Action) {
17857 // The destination type comes first.
17858 FirstType = DstType;
17859 SecondType = SrcType;
17860 break;
17861
17868 // The source type comes first.
17869 FirstType = SrcType;
17870 SecondType = DstType;
17871 break;
17872 }
17873
17874 PartialDiagnostic FDiag = PDiag(DiagKind);
17875 AssignmentAction ActionForDiag = Action;
17877 ActionForDiag = AssignmentAction::Passing;
17878
17879 FDiag << FirstType << SecondType << ActionForDiag
17880 << SrcExpr->getSourceRange();
17881
17882 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17883 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17884 auto isPlainChar = [](const clang::Type *Type) {
17885 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17886 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17887 };
17888 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17889 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17890 }
17891
17892 // If we can fix the conversion, suggest the FixIts.
17893 if (!ConvHints.isNull()) {
17894 for (FixItHint &H : ConvHints.Hints)
17895 FDiag << H;
17896 }
17897
17898 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17899
17900 if (MayHaveFunctionDiff)
17901 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17902
17903 Diag(Loc, FDiag);
17904 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17905 DiagKind == diag::err_incompatible_qualified_id) &&
17906 PDecl && IFace && !IFace->hasDefinition())
17907 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17908 << IFace << PDecl;
17909
17910 if (SecondType == Context.OverloadTy)
17912 FirstType, /*TakingAddress=*/true);
17913
17914 if (CheckInferredResultType)
17916
17917 if (Action == AssignmentAction::Returning &&
17920
17921 if (Complained)
17922 *Complained = true;
17923 return isInvalid;
17924}
17925
17927 llvm::APSInt *Result,
17928 AllowFoldKind CanFold) {
17929 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17930 public:
17931 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17932 QualType T) override {
17933 return S.Diag(Loc, diag::err_ice_not_integral)
17934 << T << S.LangOpts.CPlusPlus;
17935 }
17936 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17937 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17938 }
17939 } Diagnoser;
17940
17941 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17942}
17943
17945 llvm::APSInt *Result,
17946 unsigned DiagID,
17947 AllowFoldKind CanFold) {
17948 class IDDiagnoser : public VerifyICEDiagnoser {
17949 unsigned DiagID;
17950
17951 public:
17952 IDDiagnoser(unsigned DiagID)
17953 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17954
17955 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17956 return S.Diag(Loc, DiagID);
17957 }
17958 } Diagnoser(DiagID);
17959
17960 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17961}
17962
17968
17971 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17972}
17973
17976 VerifyICEDiagnoser &Diagnoser,
17977 AllowFoldKind CanFold) {
17978 SourceLocation DiagLoc = E->getBeginLoc();
17979
17980 if (getLangOpts().CPlusPlus11) {
17981 // C++11 [expr.const]p5:
17982 // If an expression of literal class type is used in a context where an
17983 // integral constant expression is required, then that class type shall
17984 // have a single non-explicit conversion function to an integral or
17985 // unscoped enumeration type
17986 ExprResult Converted;
17987 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17988 VerifyICEDiagnoser &BaseDiagnoser;
17989 public:
17990 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17991 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17992 BaseDiagnoser.Suppress, true),
17993 BaseDiagnoser(BaseDiagnoser) {}
17994
17995 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17996 QualType T) override {
17997 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17998 }
17999
18000 SemaDiagnosticBuilder diagnoseIncomplete(
18001 Sema &S, SourceLocation Loc, QualType T) override {
18002 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
18003 }
18004
18005 SemaDiagnosticBuilder diagnoseExplicitConv(
18006 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18007 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
18008 }
18009
18010 SemaDiagnosticBuilder noteExplicitConv(
18011 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18012 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18013 << ConvTy->isEnumeralType() << ConvTy;
18014 }
18015
18016 SemaDiagnosticBuilder diagnoseAmbiguous(
18017 Sema &S, SourceLocation Loc, QualType T) override {
18018 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
18019 }
18020
18021 SemaDiagnosticBuilder noteAmbiguous(
18022 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
18023 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
18024 << ConvTy->isEnumeralType() << ConvTy;
18025 }
18026
18027 SemaDiagnosticBuilder diagnoseConversion(
18028 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
18029 llvm_unreachable("conversion functions are permitted");
18030 }
18031 } ConvertDiagnoser(Diagnoser);
18032
18033 Converted = PerformContextualImplicitConversion(DiagLoc, E,
18034 ConvertDiagnoser);
18035 if (Converted.isInvalid())
18036 return Converted;
18037 E = Converted.get();
18038 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
18039 // don't try to evaluate it later. We also don't want to return the
18040 // RecoveryExpr here, as it results in this call succeeding, thus callers of
18041 // this function will attempt to use 'Value'.
18042 if (isa<RecoveryExpr>(E))
18043 return ExprError();
18045 return ExprError();
18046 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
18047 // An ICE must be of integral or unscoped enumeration type.
18048 if (!Diagnoser.Suppress)
18049 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
18050 << E->getSourceRange();
18051 return ExprError();
18052 }
18053
18054 ExprResult RValueExpr = DefaultLvalueConversion(E);
18055 if (RValueExpr.isInvalid())
18056 return ExprError();
18057
18058 E = RValueExpr.get();
18059
18060 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18061 // in the non-ICE case.
18064 if (Result)
18066 if (!isa<ConstantExpr>(E))
18069
18070 if (Notes.empty())
18071 return E;
18072
18073 // If our only note is the usual "invalid subexpression" note, just point
18074 // the caret at its location rather than producing an essentially
18075 // redundant note.
18076 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18077 diag::note_invalid_subexpr_in_const_expr) {
18078 DiagLoc = Notes[0].first;
18079 Notes.clear();
18080 }
18081
18082 if (getLangOpts().CPlusPlus) {
18083 if (!Diagnoser.Suppress) {
18084 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18085 for (const PartialDiagnosticAt &Note : Notes)
18086 Diag(Note.first, Note.second);
18087 }
18088 return ExprError();
18089 }
18090
18091 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18092 for (const PartialDiagnosticAt &Note : Notes)
18093 Diag(Note.first, Note.second);
18094
18095 return E;
18096 }
18097
18098 Expr::EvalResult EvalResult;
18100 EvalResult.Diag = &Notes;
18101
18102 // Try to evaluate the expression, and produce diagnostics explaining why it's
18103 // not a constant expression as a side-effect.
18104 bool Folded =
18105 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
18106 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
18107 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
18108
18109 if (!isa<ConstantExpr>(E))
18110 E = ConstantExpr::Create(Context, E, EvalResult.Val);
18111
18112 // In C++11, we can rely on diagnostics being produced for any expression
18113 // which is not a constant expression. If no diagnostics were produced, then
18114 // this is a constant expression.
18115 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18116 if (Result)
18117 *Result = EvalResult.Val.getInt();
18118 return E;
18119 }
18120
18121 // If our only note is the usual "invalid subexpression" note, just point
18122 // the caret at its location rather than producing an essentially
18123 // redundant note.
18124 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18125 diag::note_invalid_subexpr_in_const_expr) {
18126 DiagLoc = Notes[0].first;
18127 Notes.clear();
18128 }
18129
18130 if (!Folded || CanFold == AllowFoldKind::No) {
18131 if (!Diagnoser.Suppress) {
18132 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18133 for (const PartialDiagnosticAt &Note : Notes)
18134 Diag(Note.first, Note.second);
18135 }
18136
18137 return ExprError();
18138 }
18139
18140 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18141 for (const PartialDiagnosticAt &Note : Notes)
18142 Diag(Note.first, Note.second);
18143
18144 if (Result)
18145 *Result = EvalResult.Val.getInt();
18146 return E;
18147}
18148
18149namespace {
18150 // Handle the case where we conclude a expression which we speculatively
18151 // considered to be unevaluated is actually evaluated.
18152 class TransformToPE : public TreeTransform<TransformToPE> {
18153 typedef TreeTransform<TransformToPE> BaseTransform;
18154
18155 public:
18156 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18157
18158 // Make sure we redo semantic analysis
18159 bool AlwaysRebuild() { return true; }
18160 bool ReplacingOriginal() { return true; }
18161
18162 // We need to special-case DeclRefExprs referring to FieldDecls which
18163 // are not part of a member pointer formation; normal TreeTransforming
18164 // doesn't catch this case because of the way we represent them in the AST.
18165 // FIXME: This is a bit ugly; is it really the best way to handle this
18166 // case?
18167 //
18168 // Error on DeclRefExprs referring to FieldDecls.
18169 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18170 if (isa<FieldDecl>(E->getDecl()) &&
18171 !SemaRef.isUnevaluatedContext())
18172 return SemaRef.Diag(E->getLocation(),
18173 diag::err_invalid_non_static_member_use)
18174 << E->getDecl() << E->getSourceRange();
18175
18176 return BaseTransform::TransformDeclRefExpr(E);
18177 }
18178
18179 // Exception: filter out member pointer formation
18180 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18181 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18182 return E;
18183
18184 return BaseTransform::TransformUnaryOperator(E);
18185 }
18186
18187 // The body of a lambda-expression is in a separate expression evaluation
18188 // context so never needs to be transformed.
18189 // FIXME: Ideally we wouldn't transform the closure type either, and would
18190 // just recreate the capture expressions and lambda expression.
18191 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18192 return SkipLambdaBody(E, Body);
18193 }
18194 };
18195}
18196
18198 assert(isUnevaluatedContext() &&
18199 "Should only transform unevaluated expressions");
18200 ExprEvalContexts.back().Context =
18201 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18203 return E;
18204 return TransformToPE(*this).TransformExpr(E);
18205}
18206
18208 assert(isUnevaluatedContext() &&
18209 "Should only transform unevaluated expressions");
18212 return TInfo;
18213 return TransformToPE(*this).TransformType(TInfo);
18214}
18215
18216void
18218 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18220 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
18221 LambdaContextDecl, ExprContext);
18222
18223 // Discarded statements and immediate contexts nested in other
18224 // discarded statements or immediate context are themselves
18225 // a discarded statement or an immediate context, respectively.
18226 ExprEvalContexts.back().InDiscardedStatement =
18228
18229 // C++23 [expr.const]/p15
18230 // An expression or conversion is in an immediate function context if [...]
18231 // it is a subexpression of a manifestly constant-evaluated expression or
18232 // conversion.
18233 const auto &Prev = parentEvaluationContext();
18234 ExprEvalContexts.back().InImmediateFunctionContext =
18235 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18236
18237 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18238 Prev.InImmediateEscalatingFunctionContext;
18239
18240 Cleanup.reset();
18241 if (!MaybeODRUseExprs.empty())
18242 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
18243}
18244
18245void
18249 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18250 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
18251}
18252
18254 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18255 // [expr.const]/p14.1
18256 // An expression or conversion is in an immediate function context if it is
18257 // potentially evaluated and either: its innermost enclosing non-block scope
18258 // is a function parameter scope of an immediate function.
18260 FD && FD->isConsteval()
18262 : NewContext);
18266
18267 Current.InDiscardedStatement = false;
18268
18269 if (FD) {
18270
18271 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18272 // context is nested in an immediate function context, so smaller contexts
18273 // that appear inside immediate functions (like variable initializers) are
18274 // considered to be inside an immediate function context even though by
18275 // themselves they are not immediate function contexts. But when a new
18276 // function is entered, we need to reset this tracking, since the entered
18277 // function might be not an immediate function.
18278
18280 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18281
18282 if (isLambdaMethod(FD))
18284 FD->isConsteval() ||
18285 (isLambdaMethod(FD) && (Parent.isConstantEvaluated() ||
18286 Parent.isImmediateFunctionContext()));
18287 else
18289 }
18290}
18291
18293 TypeSourceInfo *TSI) {
18294 return BuildCXXReflectExpr(CaretCaretLoc, TSI);
18295}
18296
18298 TypeSourceInfo *TSI) {
18299 return CXXReflectExpr::Create(Context, CaretCaretLoc, TSI);
18300}
18301
18302namespace {
18303
18304const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18305 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18306 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
18307 if (E->getOpcode() == UO_Deref)
18308 return CheckPossibleDeref(S, E->getSubExpr());
18309 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
18310 return CheckPossibleDeref(S, E->getBase());
18311 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
18312 return CheckPossibleDeref(S, E->getBase());
18313 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
18314 QualType Inner;
18315 QualType Ty = E->getType();
18316 if (const auto *Ptr = Ty->getAs<PointerType>())
18317 Inner = Ptr->getPointeeType();
18318 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
18319 Inner = Arr->getElementType();
18320 else
18321 return nullptr;
18322
18323 if (Inner->hasAttr(attr::NoDeref))
18324 return E;
18325 }
18326 return nullptr;
18327}
18328
18329} // namespace
18330
18332 for (const Expr *E : Rec.PossibleDerefs) {
18333 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
18334 if (DeclRef) {
18335 const ValueDecl *Decl = DeclRef->getDecl();
18336 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
18337 << Decl->getName() << E->getSourceRange();
18338 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
18339 } else {
18340 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
18341 << E->getSourceRange();
18342 }
18343 }
18344 Rec.PossibleDerefs.clear();
18345}
18346
18349 return;
18350
18351 // Note: ignoring parens here is not justified by the standard rules, but
18352 // ignoring parentheses seems like a more reasonable approach, and this only
18353 // drives a deprecation warning so doesn't affect conformance.
18354 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
18355 if (BO->getOpcode() == BO_Assign) {
18356 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18357 llvm::erase(LHSs, BO->getLHS());
18358 }
18359 }
18360}
18361
18363 assert(getLangOpts().CPlusPlus20 &&
18364 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18365 "Cannot mark an immediate escalating expression outside of an "
18366 "immediate escalating context");
18367 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
18368 Call && Call->getCallee()) {
18369 if (auto *DeclRef =
18370 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18371 DeclRef->setIsImmediateEscalating(true);
18372 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
18373 Ctr->setIsImmediateEscalating(true);
18374 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
18375 DeclRef->setIsImmediateEscalating(true);
18376 } else {
18377 assert(false && "expected an immediately escalating expression");
18378 }
18380 FI->FoundImmediateEscalatingExpression = true;
18381}
18382
18384 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18385 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18388 return E;
18389
18390 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18391 /// It's OK if this fails; we'll also remove this in
18392 /// HandleImmediateInvocations, but catching it here allows us to avoid
18393 /// walking the AST looking for it in simple cases.
18394 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18395 if (auto *DeclRef =
18396 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18397 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18398
18399 // C++23 [expr.const]/p16
18400 // An expression or conversion is immediate-escalating if it is not initially
18401 // in an immediate function context and it is [...] an immediate invocation
18402 // that is not a constant expression and is not a subexpression of an
18403 // immediate invocation.
18404 APValue Cached;
18405 auto CheckConstantExpressionAndKeepResult = [&]() {
18406 Expr::EvalResult Eval;
18407 bool Res = E.get()->EvaluateAsConstantExpr(
18408 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
18409 if (Res && !Eval.DiagEmitted) {
18410 Cached = std::move(Eval.Val);
18411 return true;
18412 }
18413 return false;
18414 };
18415
18416 if (!E.get()->isValueDependent() &&
18417 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18418 !CheckConstantExpressionAndKeepResult()) {
18420 return E;
18421 }
18422
18423 if (Cleanup.exprNeedsCleanups()) {
18424 // Since an immediate invocation is a full expression itself - it requires
18425 // an additional ExprWithCleanups node, but it can participate to a bigger
18426 // full expression which actually requires cleanups to be run after so
18427 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18428 // may discard cleanups for outer expression too early.
18429
18430 // Note that ExprWithCleanups created here must always have empty cleanup
18431 // objects:
18432 // - compound literals do not create cleanup objects in C++ and immediate
18433 // invocations are C++-only.
18434 // - blocks are not allowed inside constant expressions and compiler will
18435 // issue an error if they appear there.
18436 //
18437 // Hence, in correct code any cleanup objects created inside current
18438 // evaluation context must be outside the immediate invocation.
18440 Cleanup.cleanupsHaveSideEffects(), {});
18441 }
18442
18444 getASTContext(), E.get(),
18445 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18446 getASTContext()),
18447 /*IsImmediateInvocation*/ true);
18448 if (Cached.hasValue())
18449 Res->MoveIntoResult(Cached, getASTContext());
18450 /// Value-dependent constant expressions should not be immediately
18451 /// evaluated until they are instantiated.
18452 if (!Res->isValueDependent())
18453 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18454 return Res;
18455}
18456
18460 Expr::EvalResult Eval;
18461 Eval.Diag = &Notes;
18462 ConstantExpr *CE = Candidate.getPointer();
18463 bool Result = CE->EvaluateAsConstantExpr(
18464 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18465 if (!Result || !Notes.empty()) {
18467 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18468 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18469 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18470 FunctionDecl *FD = nullptr;
18471 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18472 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18473 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18474 FD = Call->getConstructor();
18475 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18476 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18477
18478 assert(FD && FD->isImmediateFunction() &&
18479 "could not find an immediate function in this expression");
18480 if (FD->isInvalidDecl())
18481 return;
18482 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18483 << FD << FD->isConsteval();
18484 if (auto Context =
18486 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18487 << Context->Decl;
18488 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18489 }
18490 if (!FD->isConsteval())
18492 for (auto &Note : Notes)
18493 SemaRef.Diag(Note.first, Note.second);
18494 return;
18495 }
18497}
18498
18502 struct ComplexRemove : TreeTransform<ComplexRemove> {
18504 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18507 CurrentII;
18508 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18511 4>::reverse_iterator Current)
18512 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18513 void RemoveImmediateInvocation(ConstantExpr* E) {
18514 auto It = std::find_if(CurrentII, IISet.rend(),
18516 return Elem.getPointer() == E;
18517 });
18518 // It is possible that some subexpression of the current immediate
18519 // invocation was handled from another expression evaluation context. Do
18520 // not handle the current immediate invocation if some of its
18521 // subexpressions failed before.
18522 if (It == IISet.rend()) {
18523 if (SemaRef.FailedImmediateInvocations.contains(E))
18524 CurrentII->setInt(1);
18525 } else {
18526 It->setInt(1); // Mark as deleted
18527 }
18528 }
18529 ExprResult TransformConstantExpr(ConstantExpr *E) {
18530 if (!E->isImmediateInvocation())
18531 return Base::TransformConstantExpr(E);
18532 RemoveImmediateInvocation(E);
18533 return Base::TransformExpr(E->getSubExpr());
18534 }
18535 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18536 /// we need to remove its DeclRefExpr from the DRSet.
18537 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18538 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18539 return Base::TransformCXXOperatorCallExpr(E);
18540 }
18541 /// Base::TransformUserDefinedLiteral doesn't preserve the
18542 /// UserDefinedLiteral node.
18543 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18544 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18545 /// here.
18546 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18547 if (!Init)
18548 return Init;
18549
18550 // We cannot use IgnoreImpCasts because we need to preserve
18551 // full expressions.
18552 while (true) {
18553 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
18554 Init = ICE->getSubExpr();
18555 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
18556 Init = ICE->getSubExpr();
18557 else
18558 break;
18559 }
18560 /// ConstantExprs are the first layer of implicit node to be removed so if
18561 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18562 if (auto *CE = dyn_cast<ConstantExpr>(Init);
18563 CE && CE->isImmediateInvocation())
18564 RemoveImmediateInvocation(CE);
18565 return Base::TransformInitializer(Init, NotCopyInit);
18566 }
18567 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18568 DRSet.erase(E);
18569 return E;
18570 }
18571 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18572 // Do not rebuild lambdas to avoid creating a new type.
18573 // Lambdas have already been processed inside their eval contexts.
18574 return E;
18575 }
18576
18577 // We do not have enough information to transform opaque expressions and
18578 // assume they do not contain immediate subexpressions.
18579 ExprResult TransformOpaqueValueExpr(OpaqueValueExpr *E) { return E; }
18580
18581 bool AlwaysRebuild() { return false; }
18582 bool ReplacingOriginal() { return true; }
18583 bool AllowSkippingCXXConstructExpr() {
18584 bool Res = AllowSkippingFirstCXXConstructExpr;
18585 AllowSkippingFirstCXXConstructExpr = true;
18586 return Res;
18587 }
18588 bool AllowSkippingFirstCXXConstructExpr = true;
18589 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18591
18592 /// CXXConstructExpr with a single argument are getting skipped by
18593 /// TreeTransform in some situtation because they could be implicit. This
18594 /// can only occur for the top-level CXXConstructExpr because it is used
18595 /// nowhere in the expression being transformed therefore will not be rebuilt.
18596 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18597 /// skipping the first CXXConstructExpr.
18598 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18599 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18600
18601 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18602 // The result may not be usable in case of previous compilation errors.
18603 // In this case evaluation of the expression may result in crash so just
18604 // don't do anything further with the result.
18605 if (Res.isUsable()) {
18607 It->getPointer()->setSubExpr(Res.get());
18608 }
18609}
18610
18611static void
18614 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18615 Rec.ReferenceToConsteval.size() == 0) ||
18617 return;
18618
18619 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18620 // [...]
18621 // - the initializer of a variable that is usable in constant expressions or
18622 // has constant initialization.
18623 if (SemaRef.getLangOpts().CPlusPlus23 &&
18624 Rec.ExprContext ==
18626 auto *VD = dyn_cast<VarDecl>(Rec.ManglingContextDecl);
18627 if (VD && (VD->isUsableInConstantExpressions(SemaRef.Context) ||
18628 VD->hasConstantInitialization())) {
18629 // An expression or conversion is in an 'immediate function context' if it
18630 // is potentially evaluated and either:
18631 // [...]
18632 // - it is a subexpression of a manifestly constant-evaluated expression
18633 // or conversion.
18634 return;
18635 }
18636 }
18637
18638 /// When we have more than 1 ImmediateInvocationCandidates or previously
18639 /// failed immediate invocations, we need to check for nested
18640 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18641 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18642 /// invocation.
18643 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18645
18646 /// Prevent sema calls during the tree transform from adding pointers that
18647 /// are already in the sets.
18648 llvm::SaveAndRestore DisableIITracking(
18650
18651 /// Prevent diagnostic during tree transfrom as they are duplicates
18653
18654 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18655 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18656 if (!It->getInt())
18658 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18659 Rec.ReferenceToConsteval.size()) {
18660 struct SimpleRemove : DynamicRecursiveASTVisitor {
18661 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18662 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18663 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18664 DRSet.erase(E);
18665 return DRSet.size();
18666 }
18667 } Visitor(Rec.ReferenceToConsteval);
18668 Visitor.TraverseStmt(
18669 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18670 }
18671 for (auto CE : Rec.ImmediateInvocationCandidates)
18672 if (!CE.getInt())
18674 for (auto *DR : Rec.ReferenceToConsteval) {
18675 // If the expression is immediate escalating, it is not an error;
18676 // The outer context itself becomes immediate and further errors,
18677 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18678 if (DR->isImmediateEscalating())
18679 continue;
18680 auto *FD = cast<FunctionDecl>(DR->getDecl());
18681 const NamedDecl *ND = FD;
18682 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18683 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18684 ND = MD->getParent();
18685
18686 // C++23 [expr.const]/p16
18687 // An expression or conversion is immediate-escalating if it is not
18688 // initially in an immediate function context and it is [...] a
18689 // potentially-evaluated id-expression that denotes an immediate function
18690 // that is not a subexpression of an immediate invocation.
18691 bool ImmediateEscalating = false;
18692 bool IsPotentiallyEvaluated =
18693 Rec.Context ==
18695 Rec.Context ==
18697 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18698 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18699
18701 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18702 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18703 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18704 if (!FD->getBuiltinID())
18705 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18706 if (auto Context =
18708 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18709 << Context->Decl;
18710 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18711 }
18712 if (FD->isImmediateEscalating() && !FD->isConsteval())
18714
18715 } else {
18717 }
18718 }
18719}
18720
18723 if (!Rec.Lambdas.empty()) {
18725 if (!getLangOpts().CPlusPlus20 &&
18726 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18727 Rec.isUnevaluated() ||
18729 unsigned D;
18730 if (Rec.isUnevaluated()) {
18731 // C++11 [expr.prim.lambda]p2:
18732 // A lambda-expression shall not appear in an unevaluated operand
18733 // (Clause 5).
18734 D = diag::err_lambda_unevaluated_operand;
18735 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18736 // C++1y [expr.const]p2:
18737 // A conditional-expression e is a core constant expression unless the
18738 // evaluation of e, following the rules of the abstract machine, would
18739 // evaluate [...] a lambda-expression.
18740 D = diag::err_lambda_in_constant_expression;
18741 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18742 // C++17 [expr.prim.lamda]p2:
18743 // A lambda-expression shall not appear [...] in a template-argument.
18744 D = diag::err_lambda_in_invalid_context;
18745 } else
18746 llvm_unreachable("Couldn't infer lambda error message.");
18747
18748 for (const auto *L : Rec.Lambdas)
18749 Diag(L->getBeginLoc(), D);
18750 }
18751 }
18752
18753 // Append the collected materialized temporaries into previous context before
18754 // exit if the previous also is a lifetime extending context.
18756 parentEvaluationContext().InLifetimeExtendingContext &&
18757 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18760 }
18761
18763 HandleImmediateInvocations(*this, Rec);
18764
18765 // Warn on any volatile-qualified simple-assignments that are not discarded-
18766 // value expressions nor unevaluated operands (those cases get removed from
18767 // this list by CheckUnusedVolatileAssignment).
18768 for (auto *BO : Rec.VolatileAssignmentLHSs)
18769 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18770 << BO->getType();
18771
18772 // When are coming out of an unevaluated context, clear out any
18773 // temporaries that we may have created as part of the evaluation of
18774 // the expression in that context: they aren't relevant because they
18775 // will never be constructed.
18776 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18778 ExprCleanupObjects.end());
18779 Cleanup = Rec.ParentCleanup;
18782 // Otherwise, merge the contexts together.
18783 } else {
18784 Cleanup.mergeFrom(Rec.ParentCleanup);
18785 MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
18786 }
18787
18789
18790 // Pop the current expression evaluation context off the stack.
18791 ExprEvalContexts.pop_back();
18792}
18793
18795 ExprCleanupObjects.erase(
18796 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18797 ExprCleanupObjects.end());
18798 Cleanup.reset();
18799 MaybeODRUseExprs.clear();
18800}
18801
18804 if (Result.isInvalid())
18805 return ExprError();
18806 E = Result.get();
18807 if (!E->getType()->isVariablyModifiedType())
18808 return E;
18810}
18811
18812/// Are we in a context that is potentially constant evaluated per C++20
18813/// [expr.const]p12?
18815 /// C++2a [expr.const]p12:
18816 // An expression or conversion is potentially constant evaluated if it is
18817 switch (SemaRef.ExprEvalContexts.back().Context) {
18820
18821 // -- a manifestly constant-evaluated expression,
18825 // -- a potentially-evaluated expression,
18827 // -- an immediate subexpression of a braced-init-list,
18828
18829 // -- [FIXME] an expression of the form & cast-expression that occurs
18830 // within a templated entity
18831 // -- a subexpression of one of the above that is not a subexpression of
18832 // a nested unevaluated operand.
18833 return true;
18834
18837 // Expressions in this context are never evaluated.
18838 return false;
18839 }
18840 llvm_unreachable("Invalid context");
18841}
18842
18843/// Return true if this function has a calling convention that requires mangling
18844/// in the size of the parameter pack.
18846 // These manglings are only applicable for targets whcih use Microsoft
18847 // mangling scheme for C.
18849 return false;
18850
18851 // If this is C++ and this isn't an extern "C" function, parameters do not
18852 // need to be complete. In this case, C++ mangling will apply, which doesn't
18853 // use the size of the parameters.
18854 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18855 return false;
18856
18857 // Stdcall, fastcall, and vectorcall need this special treatment.
18858 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18859 switch (CC) {
18860 case CC_X86StdCall:
18861 case CC_X86FastCall:
18862 case CC_X86VectorCall:
18863 return true;
18864 default:
18865 break;
18866 }
18867 return false;
18868}
18869
18870/// Require that all of the parameter types of function be complete. Normally,
18871/// parameter types are only required to be complete when a function is called
18872/// or defined, but to mangle functions with certain calling conventions, the
18873/// mangler needs to know the size of the parameter list. In this situation,
18874/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18875/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18876/// result in a linker error. Clang doesn't implement this behavior, and instead
18877/// attempts to error at compile time.
18879 SourceLocation Loc) {
18880 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18881 FunctionDecl *FD;
18882 ParmVarDecl *Param;
18883
18884 public:
18885 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18886 : FD(FD), Param(Param) {}
18887
18888 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18889 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18890 StringRef CCName;
18891 switch (CC) {
18892 case CC_X86StdCall:
18893 CCName = "stdcall";
18894 break;
18895 case CC_X86FastCall:
18896 CCName = "fastcall";
18897 break;
18898 case CC_X86VectorCall:
18899 CCName = "vectorcall";
18900 break;
18901 default:
18902 llvm_unreachable("CC does not need mangling");
18903 }
18904
18905 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18906 << Param->getDeclName() << FD->getDeclName() << CCName;
18907 }
18908 };
18909
18910 for (ParmVarDecl *Param : FD->parameters()) {
18911 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18912 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18913 }
18914}
18915
18916namespace {
18917enum class OdrUseContext {
18918 /// Declarations in this context are not odr-used.
18919 None,
18920 /// Declarations in this context are formally odr-used, but this is a
18921 /// dependent context.
18922 Dependent,
18923 /// Declarations in this context are odr-used but not actually used (yet).
18924 FormallyOdrUsed,
18925 /// Declarations in this context are used.
18926 Used
18927};
18928}
18929
18930/// Are we within a context in which references to resolved functions or to
18931/// variables result in odr-use?
18932static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18935
18936 if (Context.isUnevaluated())
18937 return OdrUseContext::None;
18938
18940 return OdrUseContext::Dependent;
18941
18942 if (Context.isDiscardedStatementContext())
18943 return OdrUseContext::FormallyOdrUsed;
18944
18945 else if (Context.Context ==
18947 return OdrUseContext::FormallyOdrUsed;
18948
18949 return OdrUseContext::Used;
18950}
18951
18953 if (!Func->isConstexpr())
18954 return false;
18955
18956 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18957 return true;
18958
18959 // Lambda conversion operators are never user provided.
18960 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))
18961 return isLambdaConversionOperator(Conv);
18962
18963 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18964 return CCD && CCD->getInheritedConstructor();
18965}
18966
18968 bool MightBeOdrUse) {
18969 assert(Func && "No function?");
18970
18971 Func->setReferenced();
18972
18973 // Recursive functions aren't really used until they're used from some other
18974 // context.
18975 bool IsRecursiveCall = CurContext == Func;
18976
18977 // C++11 [basic.def.odr]p3:
18978 // A function whose name appears as a potentially-evaluated expression is
18979 // odr-used if it is the unique lookup result or the selected member of a
18980 // set of overloaded functions [...].
18981 //
18982 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18983 // can just check that here.
18984 OdrUseContext OdrUse =
18985 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18986 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18987 OdrUse = OdrUseContext::FormallyOdrUsed;
18988
18989 // Trivial default constructors and destructors are never actually used.
18990 // FIXME: What about other special members?
18991 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18992 OdrUse == OdrUseContext::Used) {
18993 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18994 if (Constructor->isDefaultConstructor())
18995 OdrUse = OdrUseContext::FormallyOdrUsed;
18997 OdrUse = OdrUseContext::FormallyOdrUsed;
18998 }
18999
19000 // C++20 [expr.const]p12:
19001 // A function [...] is needed for constant evaluation if it is [...] a
19002 // constexpr function that is named by an expression that is potentially
19003 // constant evaluated
19004 bool NeededForConstantEvaluation =
19007
19008 // Determine whether we require a function definition to exist, per
19009 // C++11 [temp.inst]p3:
19010 // Unless a function template specialization has been explicitly
19011 // instantiated or explicitly specialized, the function template
19012 // specialization is implicitly instantiated when the specialization is
19013 // referenced in a context that requires a function definition to exist.
19014 // C++20 [temp.inst]p7:
19015 // The existence of a definition of a [...] function is considered to
19016 // affect the semantics of the program if the [...] function is needed for
19017 // constant evaluation by an expression
19018 // C++20 [basic.def.odr]p10:
19019 // Every program shall contain exactly one definition of every non-inline
19020 // function or variable that is odr-used in that program outside of a
19021 // discarded statement
19022 // C++20 [special]p1:
19023 // The implementation will implicitly define [defaulted special members]
19024 // if they are odr-used or needed for constant evaluation.
19025 //
19026 // Note that we skip the implicit instantiation of templates that are only
19027 // used in unused default arguments or by recursive calls to themselves.
19028 // This is formally non-conforming, but seems reasonable in practice.
19029 bool NeedDefinition =
19030 !IsRecursiveCall &&
19031 (OdrUse == OdrUseContext::Used ||
19032 (NeededForConstantEvaluation && !Func->isPureVirtual()));
19033
19034 // C++14 [temp.expl.spec]p6:
19035 // If a template [...] is explicitly specialized then that specialization
19036 // shall be declared before the first use of that specialization that would
19037 // cause an implicit instantiation to take place, in every translation unit
19038 // in which such a use occurs
19039 if (NeedDefinition &&
19040 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
19041 Func->getMemberSpecializationInfo()))
19043
19044 if (getLangOpts().CUDA)
19045 CUDA().CheckCall(Loc, Func);
19046
19047 // If we need a definition, try to create one.
19048 if (NeedDefinition && !Func->getBody()) {
19051 dyn_cast<CXXConstructorDecl>(Func)) {
19053 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
19054 if (Constructor->isDefaultConstructor()) {
19055 if (Constructor->isTrivial() &&
19056 !Constructor->hasAttr<DLLExportAttr>())
19057 return;
19059 } else if (Constructor->isCopyConstructor()) {
19061 } else if (Constructor->isMoveConstructor()) {
19063 }
19064 } else if (Constructor->getInheritedConstructor()) {
19066 }
19067 } else if (CXXDestructorDecl *Destructor =
19068 dyn_cast<CXXDestructorDecl>(Func)) {
19070 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
19071 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
19072 return;
19074 }
19075 if (Destructor->isVirtual() && getLangOpts().AppleKext)
19076 MarkVTableUsed(Loc, Destructor->getParent());
19077 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
19078 if (MethodDecl->isOverloadedOperator() &&
19079 MethodDecl->getOverloadedOperator() == OO_Equal) {
19080 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
19081 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
19082 if (MethodDecl->isCopyAssignmentOperator())
19083 DefineImplicitCopyAssignment(Loc, MethodDecl);
19084 else if (MethodDecl->isMoveAssignmentOperator())
19085 DefineImplicitMoveAssignment(Loc, MethodDecl);
19086 }
19087 } else if (isa<CXXConversionDecl>(MethodDecl) &&
19088 MethodDecl->getParent()->isLambda()) {
19089 CXXConversionDecl *Conversion =
19090 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
19091 if (Conversion->isLambdaToBlockPointerConversion())
19093 else
19095 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19096 MarkVTableUsed(Loc, MethodDecl->getParent());
19097 }
19098
19099 if (Func->isDefaulted() && !Func->isDeleted()) {
19103 }
19104
19105 // Implicit instantiation of function templates and member functions of
19106 // class templates.
19107 if (Func->isImplicitlyInstantiable()) {
19109 Func->getTemplateSpecializationKindForInstantiation();
19110 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19111 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19112 if (FirstInstantiation) {
19113 PointOfInstantiation = Loc;
19114 if (auto *MSI = Func->getMemberSpecializationInfo())
19115 MSI->setPointOfInstantiation(Loc);
19116 // FIXME: Notify listener.
19117 else
19118 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19119 } else if (TSK != TSK_ImplicitInstantiation) {
19120 // Use the point of use as the point of instantiation, instead of the
19121 // point of explicit instantiation (which we track as the actual point
19122 // of instantiation). This gives better backtraces in diagnostics.
19123 PointOfInstantiation = Loc;
19124 }
19125
19126 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19127 Func->isConstexpr()) {
19128 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
19129 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
19130 CodeSynthesisContexts.size())
19132 std::make_pair(Func, PointOfInstantiation));
19133 else if (Func->isConstexpr())
19134 // Do not defer instantiations of constexpr functions, to avoid the
19135 // expression evaluator needing to call back into Sema if it sees a
19136 // call to such a function.
19137 InstantiateFunctionDefinition(PointOfInstantiation, Func);
19138 else {
19139 Func->setInstantiationIsPending(true);
19140 PendingInstantiations.push_back(
19141 std::make_pair(Func, PointOfInstantiation));
19142 if (llvm::isTimeTraceVerbose()) {
19143 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
19144 std::string Name;
19145 llvm::raw_string_ostream OS(Name);
19146 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
19147 /*Qualified=*/true);
19148 return Name;
19149 });
19150 }
19151 // Notify the consumer that a function was implicitly instantiated.
19152 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
19153 }
19154 }
19155 } else {
19156 // Walk redefinitions, as some of them may be instantiable.
19157 for (auto *i : Func->redecls()) {
19158 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
19159 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
19160 }
19161 }
19162 });
19163 }
19164
19165 // If a constructor was defined in the context of a default parameter
19166 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19167 // context), its initializers may not be referenced yet.
19168 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
19170 *this,
19171 Constructor->isImmediateFunction()
19174 Constructor);
19175 for (CXXCtorInitializer *Init : Constructor->inits()) {
19176 if (Init->isInClassMemberInitializer())
19177 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
19178 MarkDeclarationsReferencedInExpr(Init->getInit());
19179 });
19180 }
19181 }
19182
19183 // C++14 [except.spec]p17:
19184 // An exception-specification is considered to be needed when:
19185 // - the function is odr-used or, if it appears in an unevaluated operand,
19186 // would be odr-used if the expression were potentially-evaluated;
19187 //
19188 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19189 // function is a pure virtual function we're calling, and in that case the
19190 // function was selected by overload resolution and we need to resolve its
19191 // exception specification for a different reason.
19192 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19194 ResolveExceptionSpec(Loc, FPT);
19195
19196 // A callee could be called by a host function then by a device function.
19197 // If we only try recording once, we will miss recording the use on device
19198 // side. Therefore keep trying until it is recorded.
19199 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19200 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
19202
19203 // If this is the first "real" use, act on that.
19204 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19205 // Keep track of used but undefined functions.
19206 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19207 if (mightHaveNonExternalLinkage(Func))
19208 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19209 else if (Func->getMostRecentDecl()->isInlined() &&
19210 !LangOpts.GNUInline &&
19211 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19212 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19214 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19215 }
19216
19217 // Some x86 Windows calling conventions mangle the size of the parameter
19218 // pack into the name. Computing the size of the parameters requires the
19219 // parameter types to be complete. Check that now.
19222
19223 // In the MS C++ ABI, the compiler emits destructor variants where they are
19224 // used. If the destructor is used here but defined elsewhere, mark the
19225 // virtual base destructors referenced. If those virtual base destructors
19226 // are inline, this will ensure they are defined when emitting the complete
19227 // destructor variant. This checking may be redundant if the destructor is
19228 // provided later in this TU.
19229 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19230 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
19231 CXXRecordDecl *Parent = Dtor->getParent();
19232 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19234 }
19235 }
19236
19237 Func->markUsed(Context);
19238 }
19239}
19240
19241/// Directly mark a variable odr-used. Given a choice, prefer to use
19242/// MarkVariableReferenced since it does additional checks and then
19243/// calls MarkVarDeclODRUsed.
19244/// If the variable must be captured:
19245/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19246/// - else capture it in the DeclContext that maps to the
19247/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19248static void
19250 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19251 // Keep track of used but undefined variables.
19252 // FIXME: We shouldn't suppress this warning for static data members.
19253 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19254 assert(Var && "expected a capturable variable");
19255
19257 (!Var->isExternallyVisible() || Var->isInline() ||
19259 !(Var->isStaticDataMember() && Var->hasInit())) {
19261 if (old.isInvalid())
19262 old = Loc;
19263 }
19264 QualType CaptureType, DeclRefType;
19265 if (SemaRef.LangOpts.OpenMP)
19268 /*EllipsisLoc*/ SourceLocation(),
19269 /*BuildAndDiagnose*/ true, CaptureType,
19270 DeclRefType, FunctionScopeIndexToStopAt);
19271
19272 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19273 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
19274 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
19275 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
19276 if (VarTarget == SemaCUDA::CVT_Host &&
19277 (UserTarget == CUDAFunctionTarget::Device ||
19278 UserTarget == CUDAFunctionTarget::HostDevice ||
19279 UserTarget == CUDAFunctionTarget::Global)) {
19280 // Diagnose ODR-use of host global variables in device functions.
19281 // Reference of device global variables in host functions is allowed
19282 // through shadow variables therefore it is not diagnosed.
19283 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19284 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
19285 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19287 Var->getType().isConstQualified()
19288 ? diag::note_cuda_const_var_unpromoted
19289 : diag::note_cuda_host_var);
19290 }
19291 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19292 // Also capture __device__ const variables, which are classified
19293 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19294 // an explicit CUDADeviceAttr to distinguish them from plain
19295 // const variables (no __device__), which also get CVT_Both but
19296 // only have an implicit CUDADeviceAttr.
19297 (VarTarget == SemaCUDA::CVT_Both &&
19298 Var->hasAttr<CUDADeviceAttr>() &&
19299 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19300 !Var->hasAttr<CUDASharedAttr>() &&
19301 (UserTarget == CUDAFunctionTarget::Host ||
19302 UserTarget == CUDAFunctionTarget::HostDevice)) {
19303 // Record a CUDA/HIP device side variable if it is ODR-used
19304 // by host code. This is done conservatively, when the variable is
19305 // referenced in any of the following contexts:
19306 // - a non-function context
19307 // - a host function
19308 // - a host device function
19309 // This makes the ODR-use of the device side variable by host code to
19310 // be visible in the device compilation for the compiler to be able to
19311 // emit template variables instantiated by host code only and to
19312 // externalize the static device side variable ODR-used by host code.
19313 if (!Var->hasExternalStorage())
19315 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19316 (!FD || (!FD->getDescribedFunctionTemplate() &&
19320 }
19321 }
19322
19323 V->markUsed(SemaRef.Context);
19324}
19325
19327 SourceLocation Loc,
19328 unsigned CapturingScopeIndex) {
19329 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
19330}
19331
19333 SourceLocation loc,
19334 ValueDecl *var) {
19335 DeclContext *VarDC = var->getDeclContext();
19336
19337 // If the parameter still belongs to the translation unit, then
19338 // we're actually just using one parameter in the declaration of
19339 // the next.
19340 if (isa<ParmVarDecl>(var) &&
19342 return;
19343
19344 // For C code, don't diagnose about capture if we're not actually in code
19345 // right now; it's impossible to write a non-constant expression outside of
19346 // function context, so we'll get other (more useful) diagnostics later.
19347 //
19348 // For C++, things get a bit more nasty... it would be nice to suppress this
19349 // diagnostic for certain cases like using a local variable in an array bound
19350 // for a member of a local class, but the correct predicate is not obvious.
19351 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19352 return;
19353
19354 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
19355 unsigned ContextKind = 3; // unknown
19356 if (isa<CXXMethodDecl>(VarDC) &&
19357 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
19358 ContextKind = 2;
19359 } else if (isa<FunctionDecl>(VarDC)) {
19360 ContextKind = 0;
19361 } else if (isa<BlockDecl>(VarDC)) {
19362 ContextKind = 1;
19363 }
19364
19365 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
19366 << var << ValueKind << ContextKind << VarDC;
19367 S.Diag(var->getLocation(), diag::note_entity_declared_at)
19368 << var;
19369
19370 // FIXME: Add additional diagnostic info about class etc. which prevents
19371 // capture.
19372}
19373
19375 ValueDecl *Var,
19376 bool &SubCapturesAreNested,
19377 QualType &CaptureType,
19378 QualType &DeclRefType) {
19379 // Check whether we've already captured it.
19380 if (CSI->CaptureMap.count(Var)) {
19381 // If we found a capture, any subcaptures are nested.
19382 SubCapturesAreNested = true;
19383
19384 // Retrieve the capture type for this variable.
19385 CaptureType = CSI->getCapture(Var).getCaptureType();
19386
19387 // Compute the type of an expression that refers to this variable.
19388 DeclRefType = CaptureType.getNonReferenceType();
19389
19390 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19391 // are mutable in the sense that user can change their value - they are
19392 // private instances of the captured declarations.
19393 const Capture &Cap = CSI->getCapture(Var);
19394 // C++ [expr.prim.lambda]p10:
19395 // The type of such a data member is [...] an lvalue reference to the
19396 // referenced function type if the entity is a reference to a function.
19397 // [...]
19398 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19399 !(isa<LambdaScopeInfo>(CSI) &&
19400 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
19402 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19403 DeclRefType.addConst();
19404 return true;
19405 }
19406 return false;
19407}
19408
19409// Only block literals, captured statements, and lambda expressions can
19410// capture; other scopes don't work.
19412 ValueDecl *Var,
19413 SourceLocation Loc,
19414 const bool Diagnose,
19415 Sema &S) {
19418
19419 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19420 if (Underlying) {
19421 if (Underlying->hasLocalStorage() && Diagnose)
19423 }
19424 return nullptr;
19425}
19426
19427// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19428// certain types of variables (unnamed, variably modified types etc.)
19429// so check for eligibility.
19431 SourceLocation Loc, const bool Diagnose,
19432 Sema &S) {
19433
19434 assert((isa<VarDecl, BindingDecl>(Var)) &&
19435 "Only variables and structured bindings can be captured");
19436
19437 bool IsBlock = isa<BlockScopeInfo>(CSI);
19438 bool IsLambda = isa<LambdaScopeInfo>(CSI);
19439
19440 // Lambdas are not allowed to capture unnamed variables
19441 // (e.g. anonymous unions).
19442 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19443 // assuming that's the intent.
19444 if (IsLambda && !Var->getDeclName()) {
19445 if (Diagnose) {
19446 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19447 S.Diag(Var->getLocation(), diag::note_declared_at);
19448 }
19449 return false;
19450 }
19451
19452 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19453 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19454 if (Diagnose) {
19455 S.Diag(Loc, diag::err_ref_vm_type);
19456 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19457 }
19458 return false;
19459 }
19460 // Prohibit structs with flexible array members too.
19461 // We cannot capture what is in the tail end of the struct.
19462 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19463 VTD && VTD->hasFlexibleArrayMember()) {
19464 if (Diagnose) {
19465 if (IsBlock)
19466 S.Diag(Loc, diag::err_ref_flexarray_type);
19467 else
19468 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19469 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19470 }
19471 return false;
19472 }
19473 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19474 // Lambdas and captured statements are not allowed to capture __block
19475 // variables; they don't support the expected semantics.
19476 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19477 if (Diagnose) {
19478 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19479 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19480 }
19481 return false;
19482 }
19483 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19484 if (S.getLangOpts().OpenCL && IsBlock &&
19485 Var->getType()->isBlockPointerType()) {
19486 if (Diagnose)
19487 S.Diag(Loc, diag::err_opencl_block_ref_block);
19488 return false;
19489 }
19490
19491 if (isa<BindingDecl>(Var)) {
19492 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19493 if (Diagnose)
19495 return false;
19496 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19497 S.Diag(Loc, S.LangOpts.CPlusPlus20
19498 ? diag::warn_cxx17_compat_capture_binding
19499 : diag::ext_capture_binding)
19500 << Var;
19501 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19502 }
19503 }
19504
19505 return true;
19506}
19507
19508// Returns true if the capture by block was successful.
19510 SourceLocation Loc, const bool BuildAndDiagnose,
19511 QualType &CaptureType, QualType &DeclRefType,
19512 const bool Nested, Sema &S, bool Invalid) {
19513 bool ByRef = false;
19514
19515 // Blocks are not allowed to capture arrays, excepting OpenCL.
19516 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19517 // (decayed to pointers).
19518 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19519 if (BuildAndDiagnose) {
19520 S.Diag(Loc, diag::err_ref_array_type);
19521 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19522 Invalid = true;
19523 } else {
19524 return false;
19525 }
19526 }
19527
19528 // Forbid the block-capture of autoreleasing variables.
19529 if (!Invalid &&
19531 if (BuildAndDiagnose) {
19532 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19533 << /*block*/ 0;
19534 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19535 Invalid = true;
19536 } else {
19537 return false;
19538 }
19539 }
19540
19541 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19542 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19543 QualType PointeeTy = PT->getPointeeType();
19544
19545 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19547 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19548 if (BuildAndDiagnose) {
19549 SourceLocation VarLoc = Var->getLocation();
19550 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19551 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19552 }
19553 }
19554 }
19555
19556 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19557 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19558 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
19559 // Block capture by reference does not change the capture or
19560 // declaration reference types.
19561 ByRef = true;
19562 } else {
19563 // Block capture by copy introduces 'const'.
19564 CaptureType = CaptureType.getNonReferenceType().withConst();
19565 DeclRefType = CaptureType;
19566 }
19567
19568 // Actually capture the variable.
19569 if (BuildAndDiagnose)
19570 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19571 CaptureType, Invalid);
19572
19573 return !Invalid;
19574}
19575
19576/// Capture the given variable in the captured region.
19579 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19580 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19581 Sema &S, bool Invalid) {
19582 // By default, capture variables by reference.
19583 bool ByRef = true;
19584 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19585 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19586 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19587 // Using an LValue reference type is consistent with Lambdas (see below).
19588 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
19589 bool HasConst = DeclRefType.isConstQualified();
19590 DeclRefType = DeclRefType.getUnqualifiedType();
19591 // Don't lose diagnostics about assignments to const.
19592 if (HasConst)
19593 DeclRefType.addConst();
19594 }
19595 // Do not capture firstprivates in tasks.
19596 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
19597 RSI->OpenMPCaptureLevel) != OMPC_unknown)
19598 return true;
19599 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19600 RSI->OpenMPCaptureLevel);
19601 }
19602
19603 if (ByRef)
19604 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19605 else
19606 CaptureType = DeclRefType;
19607
19608 // Actually capture the variable.
19609 if (BuildAndDiagnose)
19610 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19611 Loc, SourceLocation(), CaptureType, Invalid);
19612
19613 return !Invalid;
19614}
19615
19616/// Capture the given variable in the lambda.
19618 SourceLocation Loc, const bool BuildAndDiagnose,
19619 QualType &CaptureType, QualType &DeclRefType,
19620 const bool RefersToCapturedVariable,
19621 const TryCaptureKind Kind,
19622 SourceLocation EllipsisLoc, const bool IsTopScope,
19623 Sema &S, bool Invalid) {
19624 // Determine whether we are capturing by reference or by value.
19625 bool ByRef = false;
19626 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19627 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19628 } else {
19629 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19630 }
19631
19632 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19634 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19635 Invalid = true;
19636 }
19637
19638 // Compute the type of the field that will capture this variable.
19639 if (ByRef) {
19640 // C++11 [expr.prim.lambda]p15:
19641 // An entity is captured by reference if it is implicitly or
19642 // explicitly captured but not captured by copy. It is
19643 // unspecified whether additional unnamed non-static data
19644 // members are declared in the closure type for entities
19645 // captured by reference.
19646 //
19647 // FIXME: It is not clear whether we want to build an lvalue reference
19648 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19649 // to do the former, while EDG does the latter. Core issue 1249 will
19650 // clarify, but for now we follow GCC because it's a more permissive and
19651 // easily defensible position.
19652 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19653 } else {
19654 // C++11 [expr.prim.lambda]p14:
19655 // For each entity captured by copy, an unnamed non-static
19656 // data member is declared in the closure type. The
19657 // declaration order of these members is unspecified. The type
19658 // of such a data member is the type of the corresponding
19659 // captured entity if the entity is not a reference to an
19660 // object, or the referenced type otherwise. [Note: If the
19661 // captured entity is a reference to a function, the
19662 // corresponding data member is also a reference to a
19663 // function. - end note ]
19664 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19665 if (!RefType->getPointeeType()->isFunctionType())
19666 CaptureType = RefType->getPointeeType();
19667 }
19668
19669 // Forbid the lambda copy-capture of autoreleasing variables.
19670 if (!Invalid &&
19672 if (BuildAndDiagnose) {
19673 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19674 S.Diag(Var->getLocation(), diag::note_previous_decl)
19675 << Var->getDeclName();
19676 Invalid = true;
19677 } else {
19678 return false;
19679 }
19680 }
19681
19682 // Make sure that by-copy captures are of a complete and non-abstract type.
19683 if (!Invalid && BuildAndDiagnose) {
19684 if (!CaptureType->isDependentType() &&
19686 Loc, CaptureType,
19687 diag::err_capture_of_incomplete_or_sizeless_type,
19688 Var->getDeclName()))
19689 Invalid = true;
19690 else if (S.RequireNonAbstractType(Loc, CaptureType,
19691 diag::err_capture_of_abstract_type))
19692 Invalid = true;
19693 }
19694 }
19695
19696 // Compute the type of a reference to this captured variable.
19697 if (ByRef)
19698 DeclRefType = CaptureType.getNonReferenceType();
19699 else {
19700 // C++ [expr.prim.lambda]p5:
19701 // The closure type for a lambda-expression has a public inline
19702 // function call operator [...]. This function call operator is
19703 // declared const (9.3.1) if and only if the lambda-expression's
19704 // parameter-declaration-clause is not followed by mutable.
19705 DeclRefType = CaptureType.getNonReferenceType();
19706 bool Const = LSI->lambdaCaptureShouldBeConst();
19707 // C++ [expr.prim.lambda]p10:
19708 // The type of such a data member is [...] an lvalue reference to the
19709 // referenced function type if the entity is a reference to a function.
19710 // [...]
19711 if (Const && !CaptureType->isReferenceType() &&
19712 !DeclRefType->isFunctionType())
19713 DeclRefType.addConst();
19714 }
19715
19716 // Add the capture.
19717 if (BuildAndDiagnose)
19718 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19719 Loc, EllipsisLoc, CaptureType, Invalid);
19720
19721 return !Invalid;
19722}
19723
19725 const ASTContext &Context) {
19726 // Offer a Copy fix even if the type is dependent.
19727 if (Var->getType()->isDependentType())
19728 return true;
19730 if (T.isTriviallyCopyableType(Context))
19731 return true;
19732 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19733
19734 if (!(RD = RD->getDefinition()))
19735 return false;
19736 if (RD->hasSimpleCopyConstructor())
19737 return true;
19738 if (RD->hasUserDeclaredCopyConstructor())
19739 for (CXXConstructorDecl *Ctor : RD->ctors())
19740 if (Ctor->isCopyConstructor())
19741 return !Ctor->isDeleted();
19742 }
19743 return false;
19744}
19745
19746/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19747/// default capture. Fixes may be omitted if they aren't allowed by the
19748/// standard, for example we can't emit a default copy capture fix-it if we
19749/// already explicitly copy capture capture another variable.
19751 ValueDecl *Var) {
19753 // Don't offer Capture by copy of default capture by copy fixes if Var is
19754 // known not to be copy constructible.
19755 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19756
19757 SmallString<32> FixBuffer;
19758 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19759 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19760 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19761 if (ShouldOfferCopyFix) {
19762 // Offer fixes to insert an explicit capture for the variable.
19763 // [] -> [VarName]
19764 // [OtherCapture] -> [OtherCapture, VarName]
19765 FixBuffer.assign({Separator, Var->getName()});
19766 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19767 << Var << /*value*/ 0
19768 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19769 }
19770 // As above but capture by reference.
19771 FixBuffer.assign({Separator, "&", Var->getName()});
19772 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19773 << Var << /*reference*/ 1
19774 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19775 }
19776
19777 // Only try to offer default capture if there are no captures excluding this
19778 // and init captures.
19779 // [this]: OK.
19780 // [X = Y]: OK.
19781 // [&A, &B]: Don't offer.
19782 // [A, B]: Don't offer.
19783 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19784 return !C.isThisCapture() && !C.isInitCapture();
19785 }))
19786 return;
19787
19788 // The default capture specifiers, '=' or '&', must appear first in the
19789 // capture body.
19790 SourceLocation DefaultInsertLoc =
19792
19793 if (ShouldOfferCopyFix) {
19794 bool CanDefaultCopyCapture = true;
19795 // [=, *this] OK since c++17
19796 // [=, this] OK since c++20
19797 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19798 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19800 : false;
19801 // We can't use default capture by copy if any captures already specified
19802 // capture by copy.
19803 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19804 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19805 })) {
19806 FixBuffer.assign({"=", Separator});
19807 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19808 << /*value*/ 0
19809 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19810 }
19811 }
19812
19813 // We can't use default capture by reference if any captures already specified
19814 // capture by reference.
19815 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19816 return !C.isInitCapture() && C.isReferenceCapture() &&
19817 !C.isThisCapture();
19818 })) {
19819 FixBuffer.assign({"&", Separator});
19820 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19821 << /*reference*/ 1
19822 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19823 }
19824}
19825
19827 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19828 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19829 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19830 // An init-capture is notionally from the context surrounding its
19831 // declaration, but its parent DC is the lambda class.
19832 DeclContext *VarDC = Var->getDeclContext();
19833 DeclContext *DC = CurContext;
19834
19835 // Skip past RequiresExprBodys because they don't constitute function scopes.
19836 while (DC->isRequiresExprBody())
19837 DC = DC->getParent();
19838
19839 // tryCaptureVariable is called every time a DeclRef is formed,
19840 // it can therefore have non-negigible impact on performances.
19841 // For local variables and when there is no capturing scope,
19842 // we can bailout early.
19843 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19844 return true;
19845
19846 // Exception: Function parameters are not tied to the function's DeclContext
19847 // until we enter the function definition. Capturing them anyway would result
19848 // in an out-of-bounds error while traversing DC and its parents.
19849 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
19850 return true;
19851
19852 const auto *VD = dyn_cast<VarDecl>(Var);
19853 if (VD) {
19854 if (VD->isInitCapture())
19855 VarDC = VarDC->getParent();
19856 } else {
19858 }
19859 assert(VD && "Cannot capture a null variable");
19860
19861 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19862 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19863 // We need to sync up the Declaration Context with the
19864 // FunctionScopeIndexToStopAt
19865 if (FunctionScopeIndexToStopAt) {
19866 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19867 unsigned FSIndex = FunctionScopes.size() - 1;
19868 // When we're parsing the lambda parameter list, the current DeclContext is
19869 // NOT the lambda but its parent. So move away the current LSI before
19870 // aligning DC and FunctionScopeIndexToStopAt.
19871 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
19872 FSIndex && LSI && !LSI->AfterParameterList)
19873 --FSIndex;
19874 assert(MaxFunctionScopesIndex <= FSIndex &&
19875 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19876 "FunctionScopes.");
19877 while (FSIndex != MaxFunctionScopesIndex) {
19879 --FSIndex;
19880 }
19881 }
19882
19883 // Capture global variables if it is required to use private copy of this
19884 // variable.
19885 bool IsGlobal = !VD->hasLocalStorage();
19886 if (IsGlobal && !(LangOpts.OpenMP &&
19887 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19888 MaxFunctionScopesIndex)))
19889 return true;
19890
19891 if (isa<VarDecl>(Var))
19892 Var = cast<VarDecl>(Var->getCanonicalDecl());
19893
19894 // Walk up the stack to determine whether we can capture the variable,
19895 // performing the "simple" checks that don't depend on type. We stop when
19896 // we've either hit the declared scope of the variable or find an existing
19897 // capture of that variable. We start from the innermost capturing-entity
19898 // (the DC) and ensure that all intervening capturing-entities
19899 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19900 // declcontext can either capture the variable or have already captured
19901 // the variable.
19902 CaptureType = Var->getType();
19903 DeclRefType = CaptureType.getNonReferenceType();
19904 bool Nested = false;
19905 bool Explicit = (Kind != TryCaptureKind::Implicit);
19906 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19907 do {
19908
19909 LambdaScopeInfo *LSI = nullptr;
19910 if (!FunctionScopes.empty())
19911 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19912 FunctionScopes[FunctionScopesIndex]);
19913
19914 bool IsInScopeDeclarationContext =
19915 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19916
19917 if (LSI && !LSI->AfterParameterList) {
19918 // This allows capturing parameters from a default value which does not
19919 // seems correct
19920 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19921 return true;
19922 }
19923 // If the variable is declared in the current context, there is no need to
19924 // capture it.
19925 if (IsInScopeDeclarationContext &&
19926 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19927 return true;
19928
19929 // Only block literals, captured statements, and lambda expressions can
19930 // capture; other scopes don't work.
19931 DeclContext *ParentDC =
19932 !IsInScopeDeclarationContext
19933 ? DC->getParent()
19934 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19935 BuildAndDiagnose, *this);
19936 // We need to check for the parent *first* because, if we *have*
19937 // private-captured a global variable, we need to recursively capture it in
19938 // intermediate blocks, lambdas, etc.
19939 if (!ParentDC) {
19940 if (IsGlobal) {
19941 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19942 break;
19943 }
19944 return true;
19945 }
19946
19947 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19949
19950 // Check whether we've already captured it.
19951 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19952 DeclRefType)) {
19953 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19954 break;
19955 }
19956
19957 // When evaluating some attributes (like enable_if) we might refer to a
19958 // function parameter appertaining to the same declaration as that
19959 // attribute.
19960 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19961 Parm && Parm->getDeclContext() == DC)
19962 return true;
19963
19964 // If we are instantiating a generic lambda call operator body,
19965 // we do not want to capture new variables. What was captured
19966 // during either a lambdas transformation or initial parsing
19967 // should be used.
19969 if (BuildAndDiagnose) {
19972 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19973 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19974 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19975 buildLambdaCaptureFixit(*this, LSI, Var);
19976 } else
19978 }
19979 return true;
19980 }
19981
19982 // Try to capture variable-length arrays types.
19983 if (Var->getType()->isVariablyModifiedType()) {
19984 // We're going to walk down into the type and look for VLA
19985 // expressions.
19986 QualType QTy = Var->getType();
19987 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19988 QTy = PVD->getOriginalType();
19990 }
19991
19992 if (getLangOpts().OpenMP) {
19993 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19994 // OpenMP private variables should not be captured in outer scope, so
19995 // just break here. Similarly, global variables that are captured in a
19996 // target region should not be captured outside the scope of the region.
19997 if (RSI->CapRegionKind == CR_OpenMP) {
19998 // FIXME: We should support capturing structured bindings in OpenMP.
19999 if (isa<BindingDecl>(Var)) {
20000 if (BuildAndDiagnose) {
20001 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
20002 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
20003 }
20004 return true;
20005 }
20006 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
20007 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
20008 // If the variable is private (i.e. not captured) and has variably
20009 // modified type, we still need to capture the type for correct
20010 // codegen in all regions, associated with the construct. Currently,
20011 // it is captured in the innermost captured region only.
20012 if (IsOpenMPPrivateDecl != OMPC_unknown &&
20013 Var->getType()->isVariablyModifiedType()) {
20014 QualType QTy = Var->getType();
20015 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
20016 QTy = PVD->getOriginalType();
20017 for (int I = 1,
20018 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
20019 I < E; ++I) {
20020 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
20021 FunctionScopes[FunctionScopesIndex - I]);
20022 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
20023 "Wrong number of captured regions associated with the "
20024 "OpenMP construct.");
20025 captureVariablyModifiedType(Context, QTy, OuterRSI);
20026 }
20027 }
20028 bool IsTargetCap =
20029 IsOpenMPPrivateDecl != OMPC_private &&
20030 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
20031 RSI->OpenMPCaptureLevel);
20032 // Do not capture global if it is not privatized in outer regions.
20033 bool IsGlobalCap =
20034 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
20035 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
20036
20037 // When we detect target captures we are looking from inside the
20038 // target region, therefore we need to propagate the capture from the
20039 // enclosing region. Therefore, the capture is not initially nested.
20040 if (IsTargetCap)
20041 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
20042 RSI->OpenMPLevel);
20043
20044 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
20045 (IsGlobal && !IsGlobalCap)) {
20046 Nested = !IsTargetCap;
20047 bool HasConst = DeclRefType.isConstQualified();
20048 DeclRefType = DeclRefType.getUnqualifiedType();
20049 // Don't lose diagnostics about assignments to const.
20050 if (HasConst)
20051 DeclRefType.addConst();
20052 CaptureType = Context.getLValueReferenceType(DeclRefType);
20053 break;
20054 }
20055 }
20056 }
20057 }
20059 // No capture-default, and this is not an explicit capture
20060 // so cannot capture this variable.
20061 if (BuildAndDiagnose) {
20062 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
20063 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
20064 auto *LSI = cast<LambdaScopeInfo>(CSI);
20065 if (LSI->Lambda) {
20066 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
20067 buildLambdaCaptureFixit(*this, LSI, Var);
20068 }
20069 // FIXME: If we error out because an outer lambda can not implicitly
20070 // capture a variable that an inner lambda explicitly captures, we
20071 // should have the inner lambda do the explicit capture - because
20072 // it makes for cleaner diagnostics later. This would purely be done
20073 // so that the diagnostic does not misleadingly claim that a variable
20074 // can not be captured by a lambda implicitly even though it is captured
20075 // explicitly. Suggestion:
20076 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
20077 // at the function head
20078 // - cache the StartingDeclContext - this must be a lambda
20079 // - captureInLambda in the innermost lambda the variable.
20080 }
20081 return true;
20082 }
20083 Explicit = false;
20084 FunctionScopesIndex--;
20085 if (IsInScopeDeclarationContext)
20086 DC = ParentDC;
20087 } while (!VarDC->Equals(DC));
20088
20089 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
20090 // computing the type of the capture at each step, checking type-specific
20091 // requirements, and adding captures if requested.
20092 // If the variable had already been captured previously, we start capturing
20093 // at the lambda nested within that one.
20094 bool Invalid = false;
20095 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
20096 ++I) {
20098
20099 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
20100 // certain types of variables (unnamed, variably modified types etc.)
20101 // so check for eligibility.
20102 if (!Invalid)
20103 Invalid =
20104 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
20105
20106 // After encountering an error, if we're actually supposed to capture, keep
20107 // capturing in nested contexts to suppress any follow-on diagnostics.
20108 if (Invalid && !BuildAndDiagnose)
20109 return true;
20110
20111 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
20112 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20113 DeclRefType, Nested, *this, Invalid);
20114 Nested = true;
20115 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
20117 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
20118 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
20119 Nested = true;
20120 } else {
20122 Invalid =
20123 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20124 DeclRefType, Nested, Kind, EllipsisLoc,
20125 /*IsTopScope*/ I == N - 1, *this, Invalid);
20126 Nested = true;
20127 }
20128
20129 if (Invalid && !BuildAndDiagnose)
20130 return true;
20131 }
20132 return Invalid;
20133}
20134
20136 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20137 QualType CaptureType;
20138 QualType DeclRefType;
20139 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
20140 /*BuildAndDiagnose=*/true, CaptureType,
20141 DeclRefType, nullptr);
20142}
20143
20145 QualType CaptureType;
20146 QualType DeclRefType;
20147 return !tryCaptureVariable(
20149 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);
20150}
20151
20153 assert(Var && "Null value cannot be captured");
20154
20155 QualType CaptureType;
20156 QualType DeclRefType;
20157
20158 // Determine whether we can capture this variable.
20160 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20161 nullptr))
20162 return QualType();
20163
20164 return DeclRefType;
20165}
20166
20167namespace {
20168// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20169// The produced TemplateArgumentListInfo* points to data stored within this
20170// object, so should only be used in contexts where the pointer will not be
20171// used after the CopiedTemplateArgs object is destroyed.
20172class CopiedTemplateArgs {
20173 bool HasArgs;
20174 TemplateArgumentListInfo TemplateArgStorage;
20175public:
20176 template<typename RefExpr>
20177 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20178 if (HasArgs)
20179 E->copyTemplateArgumentsInto(TemplateArgStorage);
20180 }
20181 operator TemplateArgumentListInfo*()
20182#ifdef __has_cpp_attribute
20183#if __has_cpp_attribute(clang::lifetimebound)
20184 [[clang::lifetimebound]]
20185#endif
20186#endif
20187 {
20188 return HasArgs ? &TemplateArgStorage : nullptr;
20189 }
20190};
20191}
20192
20193/// Walk the set of potential results of an expression and mark them all as
20194/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20195///
20196/// \return A new expression if we found any potential results, ExprEmpty() if
20197/// not, and ExprError() if we diagnosed an error.
20199 NonOdrUseReason NOUR) {
20200 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20201 // an object that satisfies the requirements for appearing in a
20202 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20203 // is immediately applied." This function handles the lvalue-to-rvalue
20204 // conversion part.
20205 //
20206 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20207 // transform it into the relevant kind of non-odr-use node and rebuild the
20208 // tree of nodes leading to it.
20209 //
20210 // This is a mini-TreeTransform that only transforms a restricted subset of
20211 // nodes (and only certain operands of them).
20212
20213 // Rebuild a subexpression.
20214 auto Rebuild = [&](Expr *Sub) {
20215 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
20216 };
20217
20218 // Check whether a potential result satisfies the requirements of NOUR.
20219 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20220 // Any entity other than a VarDecl is always odr-used whenever it's named
20221 // in a potentially-evaluated expression.
20222 auto *VD = dyn_cast<VarDecl>(D);
20223 if (!VD)
20224 return true;
20225
20226 // C++2a [basic.def.odr]p4:
20227 // A variable x whose name appears as a potentially-evalauted expression
20228 // e is odr-used by e unless
20229 // -- x is a reference that is usable in constant expressions, or
20230 // -- x is a variable of non-reference type that is usable in constant
20231 // expressions and has no mutable subobjects, and e is an element of
20232 // the set of potential results of an expression of
20233 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20234 // conversion is applied, or
20235 // -- x is a variable of non-reference type, and e is an element of the
20236 // set of potential results of a discarded-value expression to which
20237 // the lvalue-to-rvalue conversion is not applied
20238 //
20239 // We check the first bullet and the "potentially-evaluated" condition in
20240 // BuildDeclRefExpr. We check the type requirements in the second bullet
20241 // in CheckLValueToRValueConversionOperand below.
20242 switch (NOUR) {
20243 case NOUR_None:
20244 case NOUR_Unevaluated:
20245 llvm_unreachable("unexpected non-odr-use-reason");
20246
20247 case NOUR_Constant:
20248 // Constant references were handled when they were built.
20249 if (VD->getType()->isReferenceType())
20250 return true;
20251 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20252 if (RD->hasDefinition() && RD->hasMutableFields())
20253 return true;
20254 if (!VD->isUsableInConstantExpressions(S.Context))
20255 return true;
20256 break;
20257
20258 case NOUR_Discarded:
20259 if (VD->getType()->isReferenceType())
20260 return true;
20261 break;
20262 }
20263 return false;
20264 };
20265
20266 // Check whether this expression may be odr-used in CUDA/HIP.
20267 auto MaybeCUDAODRUsed = [&]() -> bool {
20268 if (!S.LangOpts.CUDA)
20269 return false;
20270 LambdaScopeInfo *LSI = S.getCurLambda();
20271 if (!LSI)
20272 return false;
20273 auto *DRE = dyn_cast<DeclRefExpr>(E);
20274 if (!DRE)
20275 return false;
20276 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
20277 if (!VD)
20278 return false;
20279 return LSI->CUDAPotentialODRUsedVars.count(VD);
20280 };
20281
20282 // Mark that this expression does not constitute an odr-use.
20283 auto MarkNotOdrUsed = [&] {
20284 if (!MaybeCUDAODRUsed()) {
20285 S.MaybeODRUseExprs.remove(E);
20286 if (LambdaScopeInfo *LSI = S.getCurLambda())
20287 LSI->markVariableExprAsNonODRUsed(E);
20288 }
20289 };
20290
20291 // C++2a [basic.def.odr]p2:
20292 // The set of potential results of an expression e is defined as follows:
20293 switch (E->getStmtClass()) {
20294 // -- If e is an id-expression, ...
20295 case Expr::DeclRefExprClass: {
20296 auto *DRE = cast<DeclRefExpr>(E);
20297 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20298 break;
20299
20300 // Rebuild as a non-odr-use DeclRefExpr.
20301 MarkNotOdrUsed();
20302 return DeclRefExpr::Create(
20303 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
20304 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
20305 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
20306 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
20307 }
20308
20309 case Expr::FunctionParmPackExprClass: {
20310 auto *FPPE = cast<FunctionParmPackExpr>(E);
20311 // If any of the declarations in the pack is odr-used, then the expression
20312 // as a whole constitutes an odr-use.
20313 for (ValueDecl *D : *FPPE)
20314 if (IsPotentialResultOdrUsed(D))
20315 return ExprEmpty();
20316
20317 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20318 // nothing cares about whether we marked this as an odr-use, but it might
20319 // be useful for non-compiler tools.
20320 MarkNotOdrUsed();
20321 break;
20322 }
20323
20324 // -- If e is a subscripting operation with an array operand...
20325 case Expr::ArraySubscriptExprClass: {
20326 auto *ASE = cast<ArraySubscriptExpr>(E);
20327 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20328 if (!OldBase->getType()->isArrayType())
20329 break;
20330 ExprResult Base = Rebuild(OldBase);
20331 if (!Base.isUsable())
20332 return Base;
20333 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20334 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20335 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20336 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
20337 ASE->getRBracketLoc());
20338 }
20339
20340 case Expr::MemberExprClass: {
20341 auto *ME = cast<MemberExpr>(E);
20342 // -- If e is a class member access expression [...] naming a non-static
20343 // data member...
20344 if (isa<FieldDecl>(ME->getMemberDecl())) {
20345 ExprResult Base = Rebuild(ME->getBase());
20346 if (!Base.isUsable())
20347 return Base;
20348 return MemberExpr::Create(
20349 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
20350 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
20351 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
20352 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
20353 ME->getObjectKind(), ME->isNonOdrUse());
20354 }
20355
20356 if (ME->getMemberDecl()->isCXXInstanceMember())
20357 break;
20358
20359 // -- If e is a class member access expression naming a static data member,
20360 // ...
20361 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20362 break;
20363
20364 // Rebuild as a non-odr-use MemberExpr.
20365 MarkNotOdrUsed();
20366 return MemberExpr::Create(
20367 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
20368 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
20369 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
20370 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
20371 }
20372
20373 case Expr::BinaryOperatorClass: {
20374 auto *BO = cast<BinaryOperator>(E);
20375 Expr *LHS = BO->getLHS();
20376 Expr *RHS = BO->getRHS();
20377 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20378 if (BO->getOpcode() == BO_PtrMemD) {
20379 ExprResult Sub = Rebuild(LHS);
20380 if (!Sub.isUsable())
20381 return Sub;
20382 BO->setLHS(Sub.get());
20383 // -- If e is a comma expression, ...
20384 } else if (BO->getOpcode() == BO_Comma) {
20385 ExprResult Sub = Rebuild(RHS);
20386 if (!Sub.isUsable())
20387 return Sub;
20388 BO->setRHS(Sub.get());
20389 } else {
20390 break;
20391 }
20392 return ExprResult(BO);
20393 }
20394
20395 // -- If e has the form (e1)...
20396 case Expr::ParenExprClass: {
20397 auto *PE = cast<ParenExpr>(E);
20398 ExprResult Sub = Rebuild(PE->getSubExpr());
20399 if (!Sub.isUsable())
20400 return Sub;
20401 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20402 }
20403
20404 // -- If e is a glvalue conditional expression, ...
20405 // We don't apply this to a binary conditional operator. FIXME: Should we?
20406 case Expr::ConditionalOperatorClass: {
20407 auto *CO = cast<ConditionalOperator>(E);
20408 ExprResult LHS = Rebuild(CO->getLHS());
20409 if (LHS.isInvalid())
20410 return ExprError();
20411 ExprResult RHS = Rebuild(CO->getRHS());
20412 if (RHS.isInvalid())
20413 return ExprError();
20414 if (!LHS.isUsable() && !RHS.isUsable())
20415 return ExprEmpty();
20416 if (!LHS.isUsable())
20417 LHS = CO->getLHS();
20418 if (!RHS.isUsable())
20419 RHS = CO->getRHS();
20420 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20421 CO->getCond(), LHS.get(), RHS.get());
20422 }
20423
20424 // [Clang extension]
20425 // -- If e has the form __extension__ e1...
20426 case Expr::UnaryOperatorClass: {
20427 auto *UO = cast<UnaryOperator>(E);
20428 if (UO->getOpcode() != UO_Extension)
20429 break;
20430 ExprResult Sub = Rebuild(UO->getSubExpr());
20431 if (!Sub.isUsable())
20432 return Sub;
20433 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20434 Sub.get());
20435 }
20436
20437 // [Clang extension]
20438 // -- If e has the form _Generic(...), the set of potential results is the
20439 // union of the sets of potential results of the associated expressions.
20440 case Expr::GenericSelectionExprClass: {
20441 auto *GSE = cast<GenericSelectionExpr>(E);
20442
20443 SmallVector<Expr *, 4> AssocExprs;
20444 bool AnyChanged = false;
20445 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20446 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20447 if (AssocExpr.isInvalid())
20448 return ExprError();
20449 if (AssocExpr.isUsable()) {
20450 AssocExprs.push_back(AssocExpr.get());
20451 AnyChanged = true;
20452 } else {
20453 AssocExprs.push_back(OrigAssocExpr);
20454 }
20455 }
20456
20457 void *ExOrTy = nullptr;
20458 bool IsExpr = GSE->isExprPredicate();
20459 if (IsExpr)
20460 ExOrTy = GSE->getControllingExpr();
20461 else
20462 ExOrTy = GSE->getControllingType();
20463 return AnyChanged ? S.CreateGenericSelectionExpr(
20464 GSE->getGenericLoc(), GSE->getDefaultLoc(),
20465 GSE->getRParenLoc(), IsExpr, ExOrTy,
20466 GSE->getAssocTypeSourceInfos(), AssocExprs)
20467 : ExprEmpty();
20468 }
20469
20470 // [Clang extension]
20471 // -- If e has the form __builtin_choose_expr(...), the set of potential
20472 // results is the union of the sets of potential results of the
20473 // second and third subexpressions.
20474 case Expr::ChooseExprClass: {
20475 auto *CE = cast<ChooseExpr>(E);
20476
20477 ExprResult LHS = Rebuild(CE->getLHS());
20478 if (LHS.isInvalid())
20479 return ExprError();
20480
20481 ExprResult RHS = Rebuild(CE->getLHS());
20482 if (RHS.isInvalid())
20483 return ExprError();
20484
20485 if (!LHS.get() && !RHS.get())
20486 return ExprEmpty();
20487 if (!LHS.isUsable())
20488 LHS = CE->getLHS();
20489 if (!RHS.isUsable())
20490 RHS = CE->getRHS();
20491
20492 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20493 RHS.get(), CE->getRParenLoc());
20494 }
20495
20496 // Step through non-syntactic nodes.
20497 case Expr::ConstantExprClass: {
20498 auto *CE = cast<ConstantExpr>(E);
20499 ExprResult Sub = Rebuild(CE->getSubExpr());
20500 if (!Sub.isUsable())
20501 return Sub;
20502 return ConstantExpr::Create(S.Context, Sub.get());
20503 }
20504
20505 // We could mostly rely on the recursive rebuilding to rebuild implicit
20506 // casts, but not at the top level, so rebuild them here.
20507 case Expr::ImplicitCastExprClass: {
20508 auto *ICE = cast<ImplicitCastExpr>(E);
20509 // Only step through the narrow set of cast kinds we expect to encounter.
20510 // Anything else suggests we've left the region in which potential results
20511 // can be found.
20512 switch (ICE->getCastKind()) {
20513 case CK_NoOp:
20514 case CK_DerivedToBase:
20515 case CK_UncheckedDerivedToBase: {
20516 ExprResult Sub = Rebuild(ICE->getSubExpr());
20517 if (!Sub.isUsable())
20518 return Sub;
20519 CXXCastPath Path(ICE->path());
20520 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20521 ICE->getValueKind(), &Path);
20522 }
20523
20524 default:
20525 break;
20526 }
20527 break;
20528 }
20529
20530 default:
20531 break;
20532 }
20533
20534 // Can't traverse through this node. Nothing to do.
20535 return ExprEmpty();
20536}
20537
20539 // Check whether the operand is or contains an object of non-trivial C union
20540 // type.
20541 if (E->getType().isVolatileQualified() &&
20547
20548 // C++2a [basic.def.odr]p4:
20549 // [...] an expression of non-volatile-qualified non-class type to which
20550 // the lvalue-to-rvalue conversion is applied [...]
20551 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20552 return E;
20553
20556 if (Result.isInvalid())
20557 return ExprError();
20558 return Result.get() ? Result : E;
20559}
20560
20562 if (!Res.isUsable())
20563 return Res;
20564
20565 // If a constant-expression is a reference to a variable where we delay
20566 // deciding whether it is an odr-use, just assume we will apply the
20567 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20568 // (a non-type template argument), we have special handling anyway.
20570}
20571
20573 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20574 // call.
20575 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20576 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20577
20578 for (Expr *E : LocalMaybeODRUseExprs) {
20579 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20580 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20581 DRE->getLocation(), *this);
20582 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20583 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20584 *this);
20585 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20586 for (ValueDecl *VD : *FP)
20587 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20588 } else {
20589 llvm_unreachable("Unexpected expression");
20590 }
20591 }
20592
20593 assert(MaybeODRUseExprs.empty() &&
20594 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20595}
20596
20598 ValueDecl *Var, Expr *E) {
20600 if (!VD)
20601 return;
20602
20603 const bool RefersToEnclosingScope =
20604 (SemaRef.CurContext != VD->getDeclContext() &&
20606 if (RefersToEnclosingScope) {
20607 LambdaScopeInfo *const LSI =
20608 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20609 if (LSI && (!LSI->CallOperator ||
20610 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20611 // If a variable could potentially be odr-used, defer marking it so
20612 // until we finish analyzing the full expression for any
20613 // lvalue-to-rvalue
20614 // or discarded value conversions that would obviate odr-use.
20615 // Add it to the list of potential captures that will be analyzed
20616 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20617 // unless the variable is a reference that was initialized by a constant
20618 // expression (this will never need to be captured or odr-used).
20619 //
20620 // FIXME: We can simplify this a lot after implementing P0588R1.
20621 assert(E && "Capture variable should be used in an expression.");
20622 if (!Var->getType()->isReferenceType() ||
20625 }
20626 }
20627}
20628
20630 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20631 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20632 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20634 "Invalid Expr argument to DoMarkVarDeclReferenced");
20635 Var->setReferenced();
20636
20637 if (Var->isInvalidDecl())
20638 return;
20639
20640 auto *MSI = Var->getMemberSpecializationInfo();
20641 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20643
20644 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20645 bool UsableInConstantExpr =
20647
20648 // Only track variables with internal linkage or local scope.
20649 // Use canonical decl so in-class declarations and out-of-class definitions
20650 // of static data members in anonymous namespaces are tracked as a single
20651 // entry.
20652 const VarDecl *CanonVar = Var->getCanonicalDecl();
20653 if ((CanonVar->isLocalVarDeclOrParm() ||
20654 CanonVar->isInternalLinkageFileVar()) &&
20655 !CanonVar->hasExternalStorage()) {
20656 RefsMinusAssignments.insert({CanonVar, 0}).first->getSecond()++;
20657 }
20658
20659 // C++20 [expr.const]p12:
20660 // A variable [...] is needed for constant evaluation if it is [...] a
20661 // variable whose name appears as a potentially constant evaluated
20662 // expression that is either a contexpr variable or is of non-volatile
20663 // const-qualified integral type or of reference type
20664 bool NeededForConstantEvaluation =
20665 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20666
20667 bool NeedDefinition =
20668 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20669 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20670 Var->getType()->isUndeducedType());
20671
20673 "Can't instantiate a partial template specialization.");
20674
20675 // If this might be a member specialization of a static data member, check
20676 // the specialization is visible. We already did the checks for variable
20677 // template specializations when we created them.
20678 if (NeedDefinition && TSK != TSK_Undeclared &&
20681
20682 // Perform implicit instantiation of static data members, static data member
20683 // templates of class templates, and variable template specializations. Delay
20684 // instantiations of variable templates, except for those that could be used
20685 // in a constant expression.
20686 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20687 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20688 // instantiation declaration if a variable is usable in a constant
20689 // expression (among other cases).
20690 bool TryInstantiating =
20692 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20693
20694 if (TryInstantiating) {
20695 SourceLocation PointOfInstantiation =
20696 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20697 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20698 if (FirstInstantiation) {
20699 PointOfInstantiation = Loc;
20700 if (MSI)
20701 MSI->setPointOfInstantiation(PointOfInstantiation);
20702 // FIXME: Notify listener.
20703 else
20704 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20705 }
20706
20707 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20708 // Do not defer instantiations of variables that could be used in a
20709 // constant expression.
20710 // The type deduction also needs a complete initializer.
20711 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20712 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20713 });
20714
20715 // The size of an incomplete array type can be updated by
20716 // instantiating the initializer. The DeclRefExpr's type should be
20717 // updated accordingly too, or users of it would be confused!
20718 if (E)
20720
20721 // Re-set the member to trigger a recomputation of the dependence bits
20722 // for the expression.
20723 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20724 DRE->setDecl(DRE->getDecl());
20725 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20726 ME->setMemberDecl(ME->getMemberDecl());
20727 } else if (FirstInstantiation) {
20729 .push_back(std::make_pair(Var, PointOfInstantiation));
20730 } else {
20731 bool Inserted = false;
20732 for (auto &I : SemaRef.SavedPendingInstantiations) {
20733 auto Iter = llvm::find_if(
20734 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20735 return P.first == Var;
20736 });
20737 if (Iter != I.end()) {
20738 SemaRef.PendingInstantiations.push_back(*Iter);
20739 I.erase(Iter);
20740 Inserted = true;
20741 break;
20742 }
20743 }
20744
20745 // FIXME: For a specialization of a variable template, we don't
20746 // distinguish between "declaration and type implicitly instantiated"
20747 // and "implicit instantiation of definition requested", so we have
20748 // no direct way to avoid enqueueing the pending instantiation
20749 // multiple times.
20750 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20752 .push_back(std::make_pair(Var, PointOfInstantiation));
20753 }
20754 }
20755 }
20756
20757 // C++2a [basic.def.odr]p4:
20758 // A variable x whose name appears as a potentially-evaluated expression e
20759 // is odr-used by e unless
20760 // -- x is a reference that is usable in constant expressions
20761 // -- x is a variable of non-reference type that is usable in constant
20762 // expressions and has no mutable subobjects [FIXME], and e is an
20763 // element of the set of potential results of an expression of
20764 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20765 // conversion is applied
20766 // -- x is a variable of non-reference type, and e is an element of the set
20767 // of potential results of a discarded-value expression to which the
20768 // lvalue-to-rvalue conversion is not applied [FIXME]
20769 //
20770 // We check the first part of the second bullet here, and
20771 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20772 // FIXME: To get the third bullet right, we need to delay this even for
20773 // variables that are not usable in constant expressions.
20774
20775 // If we already know this isn't an odr-use, there's nothing more to do.
20776 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20777 if (DRE->isNonOdrUse())
20778 return;
20779 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20780 if (ME->isNonOdrUse())
20781 return;
20782
20783 switch (OdrUse) {
20784 case OdrUseContext::None:
20785 // In some cases, a variable may not have been marked unevaluated, if it
20786 // appears in a defaukt initializer.
20787 assert((!E || isa<FunctionParmPackExpr>(E) ||
20789 "missing non-odr-use marking for unevaluated decl ref");
20790 break;
20791
20792 case OdrUseContext::FormallyOdrUsed:
20793 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20794 // behavior.
20795 break;
20796
20797 case OdrUseContext::Used:
20798 // If we might later find that this expression isn't actually an odr-use,
20799 // delay the marking.
20801 SemaRef.MaybeODRUseExprs.insert(E);
20802 else
20803 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20804 break;
20805
20806 case OdrUseContext::Dependent:
20807 // If this is a dependent context, we don't need to mark variables as
20808 // odr-used, but we may still need to track them for lambda capture.
20809 // FIXME: Do we also need to do this inside dependent typeid expressions
20810 // (which are modeled as unevaluated at this point)?
20811 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20812 break;
20813 }
20814}
20815
20817 BindingDecl *BD, Expr *E) {
20818 BD->setReferenced();
20819
20820 if (BD->isInvalidDecl())
20821 return;
20822
20823 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20824 if (OdrUse == OdrUseContext::Used) {
20825 QualType CaptureType, DeclRefType;
20827 /*EllipsisLoc*/ SourceLocation(),
20828 /*BuildAndDiagnose*/ true, CaptureType,
20829 DeclRefType,
20830 /*FunctionScopeIndexToStopAt*/ nullptr);
20831 } else if (OdrUse == OdrUseContext::Dependent) {
20832 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20833 }
20834}
20835
20837 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20838}
20839
20840// C++ [temp.dep.expr]p3:
20841// An id-expression is type-dependent if it contains:
20842// - an identifier associated by name lookup with an entity captured by copy
20843// in a lambda-expression that has an explicit object parameter whose type
20844// is dependent ([dcl.fct]),
20846 Sema &SemaRef, ValueDecl *D, Expr *E) {
20847 auto *ID = dyn_cast<DeclRefExpr>(E);
20848 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20849 return;
20850
20851 // If any enclosing lambda with a dependent explicit object parameter either
20852 // explicitly captures the variable by value, or has a capture default of '='
20853 // and does not capture the variable by reference, then the type of the DRE
20854 // is dependent on the type of that lambda's explicit object parameter.
20855 auto IsDependent = [&]() {
20856 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
20857 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
20858 if (!LSI)
20859 continue;
20860
20861 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
20862 LSI->AfterParameterList)
20863 return false;
20864
20865 const auto *MD = LSI->CallOperator;
20866 if (MD->getType().isNull())
20867 continue;
20868
20869 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20870 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20871 !Ty->getParamType(0)->isDependentType())
20872 continue;
20873
20874 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
20875 if (C->isCopyCapture())
20876 return true;
20877 continue;
20878 }
20879
20880 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20881 return true;
20882 }
20883 return false;
20884 }();
20885
20886 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20887 IsDependent, SemaRef.getASTContext());
20888}
20889
20890static void
20892 bool MightBeOdrUse,
20893 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20896
20897 if (SemaRef.getLangOpts().OpenACC)
20898 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20899
20900 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20902 if (SemaRef.getLangOpts().CPlusPlus)
20904 Var, E);
20905 return;
20906 }
20907
20908 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20910 if (SemaRef.getLangOpts().CPlusPlus)
20912 Decl, E);
20913 return;
20914 }
20915 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20916
20917 // If this is a call to a method via a cast, also mark the method in the
20918 // derived class used in case codegen can devirtualize the call.
20919 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20920 if (!ME)
20921 return;
20922 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20923 if (!MD)
20924 return;
20925 // Only attempt to devirtualize if this is truly a virtual call.
20926 bool IsVirtualCall = MD->isVirtual() &&
20928 if (!IsVirtualCall)
20929 return;
20930
20931 // If it's possible to devirtualize the call, mark the called function
20932 // referenced.
20934 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20935 if (DM)
20936 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20937}
20938
20940 // [basic.def.odr] (CWG 1614)
20941 // A function is named by an expression or conversion [...]
20942 // unless it is a pure virtual function and either the expression is not an
20943 // id-expression naming the function with an explicitly qualified name or
20944 // the expression forms a pointer to member
20945 bool OdrUse = true;
20946 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20947 if (Method->isVirtual() &&
20948 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20949 OdrUse = false;
20950
20951 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20955 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20956 !FD->isDependentContext())
20957 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20958 }
20959 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20961}
20962
20964 // C++11 [basic.def.odr]p2:
20965 // A non-overloaded function whose name appears as a potentially-evaluated
20966 // expression or a member of a set of candidate functions, if selected by
20967 // overload resolution when referred to from a potentially-evaluated
20968 // expression, is odr-used, unless it is a pure virtual function and its
20969 // name is not explicitly qualified.
20970 bool MightBeOdrUse = true;
20972 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20973 if (Method->isPureVirtual())
20974 MightBeOdrUse = false;
20975 }
20976 SourceLocation Loc =
20977 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20978 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20980}
20981
20987
20988/// Perform marking for a reference to an arbitrary declaration. It
20989/// marks the declaration referenced, and performs odr-use checking for
20990/// functions and variables. This method should not be used when building a
20991/// normal expression which refers to a variable.
20993 bool MightBeOdrUse) {
20994 if (MightBeOdrUse) {
20995 if (auto *VD = dyn_cast<VarDecl>(D)) {
20996 MarkVariableReferenced(Loc, VD);
20997 return;
20998 }
20999 }
21000 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
21001 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
21002 return;
21003 }
21004 D->setReferenced();
21005}
21006
21007namespace {
21008 // Mark all of the declarations used by a type as referenced.
21009 // FIXME: Not fully implemented yet! We need to have a better understanding
21010 // of when we're entering a context we should not recurse into.
21011 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
21012 // TreeTransforms rebuilding the type in a new context. Rather than
21013 // duplicating the TreeTransform logic, we should consider reusing it here.
21014 // Currently that causes problems when rebuilding LambdaExprs.
21015class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
21016 Sema &S;
21017 SourceLocation Loc;
21018
21019public:
21020 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
21021
21022 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
21023};
21024}
21025
21026bool MarkReferencedDecls::TraverseTemplateArgument(
21027 const TemplateArgument &Arg) {
21028 {
21029 // A non-type template argument is a constant-evaluated context.
21030 EnterExpressionEvaluationContext Evaluated(
21033 if (Decl *D = Arg.getAsDecl())
21034 S.MarkAnyDeclReferenced(Loc, D, true);
21035 } else if (Arg.getKind() == TemplateArgument::Expression) {
21037 }
21038 }
21039
21041}
21042
21044 MarkReferencedDecls Marker(*this, Loc);
21045 Marker.TraverseType(T);
21046}
21047
21048namespace {
21049/// Helper class that marks all of the declarations referenced by
21050/// potentially-evaluated subexpressions as "referenced".
21051class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
21052public:
21053 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
21054 bool SkipLocalVariables;
21056
21057 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
21059 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
21060
21061 void visitUsedDecl(SourceLocation Loc, Decl *D) {
21063 }
21064
21065 void Visit(Expr *E) {
21066 if (llvm::is_contained(StopAt, E))
21067 return;
21068 Inherited::Visit(E);
21069 }
21070
21071 void VisitConstantExpr(ConstantExpr *E) {
21072 // Don't mark declarations within a ConstantExpression, as this expression
21073 // will be evaluated and folded to a value.
21074 }
21075
21076 void VisitDeclRefExpr(DeclRefExpr *E) {
21077 // If we were asked not to visit local variables, don't.
21078 if (SkipLocalVariables) {
21079 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
21080 if (VD->hasLocalStorage())
21081 return;
21082 }
21083
21084 // FIXME: This can trigger the instantiation of the initializer of a
21085 // variable, which can cause the expression to become value-dependent
21086 // or error-dependent. Do we need to propagate the new dependence bits?
21088 }
21089
21090 void VisitMemberExpr(MemberExpr *E) {
21092 Visit(E->getBase());
21093 }
21094};
21095} // namespace
21096
21098 bool SkipLocalVariables,
21099 ArrayRef<const Expr*> StopAt) {
21100 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
21101}
21102
21103/// Emit a diagnostic when statements are reachable.
21105 const PartialDiagnostic &PD) {
21106 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
21107 // The initializer of a constexpr variable or of the first declaration of a
21108 // static data member is not syntactically a constant evaluated constant,
21109 // but nonetheless is always required to be a constant expression, so we
21110 // can skip diagnosing.
21111 if (Decl &&
21112 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
21113 Decl->isFirstDecl() && !Decl->isInline())))
21114 return false;
21115
21116 if (Stmts.empty()) {
21117 Diag(Loc, PD);
21118 return true;
21119 }
21120
21121 if (getCurFunction()) {
21122 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21123 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21124 return true;
21125 }
21126
21127 // For non-constexpr file-scope variables with reachability context (non-empty
21128 // Stmts), build a CFG for the initializer and check whether the context in
21129 // question is reachable.
21130 if (Decl && Decl->isFileVarDecl()) {
21131 AnalysisWarnings.registerVarDeclWarning(
21132 Decl, sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21133 return true;
21134 }
21135
21136 Diag(Loc, PD);
21137 return true;
21138}
21139
21140/// Emit a diagnostic that describes an effect on the run-time behavior
21141/// of the program being compiled.
21142///
21143/// This routine emits the given diagnostic when the code currently being
21144/// type-checked is "potentially evaluated", meaning that there is a
21145/// possibility that the code will actually be executable. Code in sizeof()
21146/// expressions, code used only during overload resolution, etc., are not
21147/// potentially evaluated. This routine will suppress such diagnostics or,
21148/// in the absolutely nutty case of potentially potentially evaluated
21149/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21150/// later.
21151///
21152/// This routine should be used for all diagnostics that describe the run-time
21153/// behavior of a program, such as passing a non-POD value through an ellipsis.
21154/// Failure to do so will likely result in spurious diagnostics or failures
21155/// during overload resolution or within sizeof/alignof/typeof/typeid.
21157 const PartialDiagnostic &PD) {
21158
21159 if (ExprEvalContexts.back().isDiscardedStatementContext())
21160 return false;
21161
21162 switch (ExprEvalContexts.back().Context) {
21167 // The argument will never be evaluated, so don't complain.
21168 break;
21169
21172 // Relevant diagnostics should be produced by constant evaluation.
21173 break;
21174
21177 return DiagIfReachable(Loc, Stmts, PD);
21178 }
21179
21180 return false;
21181}
21182
21184 const PartialDiagnostic &PD) {
21185 return DiagRuntimeBehavior(
21186 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21187 PD);
21188}
21189
21191 CallExpr *CE, FunctionDecl *FD) {
21192 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21193 return false;
21194
21195 // If we're inside a decltype's expression, don't check for a valid return
21196 // type or construct temporaries until we know whether this is the last call.
21197 if (ExprEvalContexts.back().ExprContext ==
21199 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
21200 return false;
21201 }
21202
21203 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21204 FunctionDecl *FD;
21205 CallExpr *CE;
21206
21207 public:
21208 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21209 : FD(FD), CE(CE) { }
21210
21211 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21212 if (!FD) {
21213 S.Diag(Loc, diag::err_call_incomplete_return)
21214 << T << CE->getSourceRange();
21215 return;
21216 }
21217
21218 S.Diag(Loc, diag::err_call_function_incomplete_return)
21219 << CE->getSourceRange() << FD << T;
21220 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
21221 << FD->getDeclName();
21222 }
21223 } Diagnoser(FD, CE);
21224
21225 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
21226 return true;
21227
21228 return false;
21229}
21230
21231// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21232// will prevent this condition from triggering, which is what we want.
21234 SourceLocation Loc;
21235
21236 unsigned diagnostic = diag::warn_condition_is_assignment;
21237 bool IsOrAssign = false;
21238
21239 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
21240 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21241 return;
21242
21243 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21244
21245 // Greylist some idioms by putting them into a warning subcategory.
21246 if (ObjCMessageExpr *ME
21247 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
21248 Selector Sel = ME->getSelector();
21249
21250 // self = [<foo> init...]
21251 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21252 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21253
21254 // <foo> = [<bar> nextObject]
21255 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
21256 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21257 }
21258
21259 Loc = Op->getOperatorLoc();
21260 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
21261 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21262 return;
21263
21264 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21265 Loc = Op->getOperatorLoc();
21266 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
21267 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
21268 else {
21269 // Not an assignment.
21270 return;
21271 }
21272
21273 Diag(Loc, diagnostic) << E->getSourceRange();
21274
21277 Diag(Loc, diag::note_condition_assign_silence)
21279 << FixItHint::CreateInsertion(Close, ")");
21280
21281 if (IsOrAssign)
21282 Diag(Loc, diag::note_condition_or_assign_to_comparison)
21283 << FixItHint::CreateReplacement(Loc, "!=");
21284 else
21285 Diag(Loc, diag::note_condition_assign_to_comparison)
21286 << FixItHint::CreateReplacement(Loc, "==");
21287}
21288
21290 // Don't warn if the parens came from a macro.
21291 SourceLocation parenLoc = ParenE->getBeginLoc();
21292 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21293 return;
21294 // Don't warn for dependent expressions.
21295 if (ParenE->isTypeDependent())
21296 return;
21297
21298 Expr *E = ParenE->IgnoreParens();
21299 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21300 return;
21301
21302 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
21303 if (opE->getOpcode() == BO_EQ &&
21304 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
21305 == Expr::MLV_Valid) {
21306 SourceLocation Loc = opE->getOperatorLoc();
21307
21308 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
21309 SourceRange ParenERange = ParenE->getSourceRange();
21310 Diag(Loc, diag::note_equality_comparison_silence)
21311 << FixItHint::CreateRemoval(ParenERange.getBegin())
21312 << FixItHint::CreateRemoval(ParenERange.getEnd());
21313 Diag(Loc, diag::note_equality_comparison_to_assign)
21314 << FixItHint::CreateReplacement(Loc, "=");
21315 }
21316}
21317
21319 bool IsConstexpr) {
21321 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
21323
21324 ExprResult result = CheckPlaceholderExpr(E);
21325 if (result.isInvalid()) return ExprError();
21326 E = result.get();
21327
21328 if (!E->isTypeDependent()) {
21329 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21331
21332 if (getLangOpts().CPlusPlus)
21333 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
21334
21336 if (ERes.isInvalid())
21337 return ExprError();
21338 E = ERes.get();
21339
21340 QualType T = E->getType();
21341 if (!T->isScalarType()) { // C99 6.8.4.1p1
21342 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
21343 << T << E->getSourceRange();
21344 return ExprError();
21345 }
21346 CheckBoolLikeConversion(E, Loc);
21347 }
21348
21349 return E;
21350}
21351
21353 Expr *SubExpr, ConditionKind CK,
21354 bool MissingOK) {
21355 // MissingOK indicates whether having no condition expression is valid
21356 // (for loop) or invalid (e.g. while loop).
21357 if (!SubExpr)
21358 return MissingOK ? ConditionResult() : ConditionError();
21359
21361 switch (CK) {
21363 Cond = CheckBooleanCondition(Loc, SubExpr);
21364 break;
21365
21367 // Note: this might produce a FullExpr
21368 Cond = CheckBooleanCondition(Loc, SubExpr, true);
21369 break;
21370
21372 Cond = CheckSwitchCondition(Loc, SubExpr);
21373 break;
21374 }
21375 if (Cond.isInvalid()) {
21376 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
21377 {SubExpr}, PreferredConditionType(CK));
21378 if (!Cond.get())
21379 return ConditionError();
21380 } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))
21381 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
21382
21383 if (!Cond.isUsable())
21384 return ConditionError();
21385
21386 return ConditionResult(*this, nullptr, Cond,
21388}
21389
21390namespace {
21391 /// A visitor for rebuilding a call to an __unknown_any expression
21392 /// to have an appropriate type.
21393 struct RebuildUnknownAnyFunction
21394 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21395
21396 Sema &S;
21397
21398 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21399
21400 ExprResult VisitStmt(Stmt *S) {
21401 llvm_unreachable("unexpected statement!");
21402 }
21403
21404 ExprResult VisitExpr(Expr *E) {
21405 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21406 << E->getSourceRange();
21407 return ExprError();
21408 }
21409
21410 /// Rebuild an expression which simply semantically wraps another
21411 /// expression which it shares the type and value kind of.
21412 template <class T> ExprResult rebuildSugarExpr(T *E) {
21413 ExprResult SubResult = Visit(E->getSubExpr());
21414 if (SubResult.isInvalid()) return ExprError();
21415
21416 Expr *SubExpr = SubResult.get();
21417 E->setSubExpr(SubExpr);
21418 E->setType(SubExpr->getType());
21419 E->setValueKind(SubExpr->getValueKind());
21420 assert(E->getObjectKind() == OK_Ordinary);
21421 return E;
21422 }
21423
21424 ExprResult VisitParenExpr(ParenExpr *E) {
21425 return rebuildSugarExpr(E);
21426 }
21427
21428 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21429 return rebuildSugarExpr(E);
21430 }
21431
21432 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21433 ExprResult SubResult = Visit(E->getSubExpr());
21434 if (SubResult.isInvalid()) return ExprError();
21435
21436 Expr *SubExpr = SubResult.get();
21437 E->setSubExpr(SubExpr);
21438 E->setType(S.Context.getPointerType(SubExpr->getType()));
21439 assert(E->isPRValue());
21440 assert(E->getObjectKind() == OK_Ordinary);
21441 return E;
21442 }
21443
21444 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21445 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21446
21447 E->setType(VD->getType());
21448
21449 assert(E->isPRValue());
21450 if (S.getLangOpts().CPlusPlus &&
21451 !(isa<CXXMethodDecl>(VD) &&
21452 cast<CXXMethodDecl>(VD)->isInstance()))
21454
21455 return E;
21456 }
21457
21458 ExprResult VisitMemberExpr(MemberExpr *E) {
21459 return resolveDecl(E, E->getMemberDecl());
21460 }
21461
21462 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21463 return resolveDecl(E, E->getDecl());
21464 }
21465 };
21466}
21467
21468/// Given a function expression of unknown-any type, try to rebuild it
21469/// to have a function type.
21471 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21472 if (Result.isInvalid()) return ExprError();
21473 return S.DefaultFunctionArrayConversion(Result.get());
21474}
21475
21476namespace {
21477 /// A visitor for rebuilding an expression of type __unknown_anytype
21478 /// into one which resolves the type directly on the referring
21479 /// expression. Strict preservation of the original source
21480 /// structure is not a goal.
21481 struct RebuildUnknownAnyExpr
21482 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21483
21484 Sema &S;
21485
21486 /// The current destination type.
21487 QualType DestType;
21488
21489 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21490 : S(S), DestType(CastType) {}
21491
21492 ExprResult VisitStmt(Stmt *S) {
21493 llvm_unreachable("unexpected statement!");
21494 }
21495
21496 ExprResult VisitExpr(Expr *E) {
21497 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21498 << E->getSourceRange();
21499 return ExprError();
21500 }
21501
21502 ExprResult VisitCallExpr(CallExpr *E);
21503 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21504
21505 /// Rebuild an expression which simply semantically wraps another
21506 /// expression which it shares the type and value kind of.
21507 template <class T> ExprResult rebuildSugarExpr(T *E) {
21508 ExprResult SubResult = Visit(E->getSubExpr());
21509 if (SubResult.isInvalid()) return ExprError();
21510 Expr *SubExpr = SubResult.get();
21511 E->setSubExpr(SubExpr);
21512 E->setType(SubExpr->getType());
21513 E->setValueKind(SubExpr->getValueKind());
21514 assert(E->getObjectKind() == OK_Ordinary);
21515 return E;
21516 }
21517
21518 ExprResult VisitParenExpr(ParenExpr *E) {
21519 return rebuildSugarExpr(E);
21520 }
21521
21522 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21523 return rebuildSugarExpr(E);
21524 }
21525
21526 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21527 const PointerType *Ptr = DestType->getAs<PointerType>();
21528 if (!Ptr) {
21529 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21530 << E->getSourceRange();
21531 return ExprError();
21532 }
21533
21534 if (isa<CallExpr>(E->getSubExpr())) {
21535 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21536 << E->getSourceRange();
21537 return ExprError();
21538 }
21539
21540 assert(E->isPRValue());
21541 assert(E->getObjectKind() == OK_Ordinary);
21542 E->setType(DestType);
21543
21544 // Build the sub-expression as if it were an object of the pointee type.
21545 DestType = Ptr->getPointeeType();
21546 ExprResult SubResult = Visit(E->getSubExpr());
21547 if (SubResult.isInvalid()) return ExprError();
21548 E->setSubExpr(SubResult.get());
21549 return E;
21550 }
21551
21552 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21553
21554 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21555
21556 ExprResult VisitMemberExpr(MemberExpr *E) {
21557 return resolveDecl(E, E->getMemberDecl());
21558 }
21559
21560 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21561 return resolveDecl(E, E->getDecl());
21562 }
21563 };
21564}
21565
21566/// Rebuilds a call expression which yielded __unknown_anytype.
21567ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21568 Expr *CalleeExpr = E->getCallee();
21569
21570 enum FnKind {
21571 FK_MemberFunction,
21572 FK_FunctionPointer,
21573 FK_BlockPointer
21574 };
21575
21576 FnKind Kind;
21577 QualType CalleeType = CalleeExpr->getType();
21578 if (CalleeType == S.Context.BoundMemberTy) {
21580 Kind = FK_MemberFunction;
21581 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21582 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21583 CalleeType = Ptr->getPointeeType();
21584 Kind = FK_FunctionPointer;
21585 } else {
21586 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21587 Kind = FK_BlockPointer;
21588 }
21589 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21590
21591 // Verify that this is a legal result type of a function.
21592 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21593 DestType->isFunctionType()) {
21594 unsigned diagID = diag::err_func_returning_array_function;
21595 if (Kind == FK_BlockPointer)
21596 diagID = diag::err_block_returning_array_function;
21597
21598 S.Diag(E->getExprLoc(), diagID)
21599 << DestType->isFunctionType() << DestType;
21600 return ExprError();
21601 }
21602
21603 // Otherwise, go ahead and set DestType as the call's result.
21604 E->setType(DestType.getNonLValueExprType(S.Context));
21606 assert(E->getObjectKind() == OK_Ordinary);
21607
21608 // Rebuild the function type, replacing the result type with DestType.
21609 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21610 if (Proto) {
21611 // __unknown_anytype(...) is a special case used by the debugger when
21612 // it has no idea what a function's signature is.
21613 //
21614 // We want to build this call essentially under the K&R
21615 // unprototyped rules, but making a FunctionNoProtoType in C++
21616 // would foul up all sorts of assumptions. However, we cannot
21617 // simply pass all arguments as variadic arguments, nor can we
21618 // portably just call the function under a non-variadic type; see
21619 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21620 // However, it turns out that in practice it is generally safe to
21621 // call a function declared as "A foo(B,C,D);" under the prototype
21622 // "A foo(B,C,D,...);". The only known exception is with the
21623 // Windows ABI, where any variadic function is implicitly cdecl
21624 // regardless of its normal CC. Therefore we change the parameter
21625 // types to match the types of the arguments.
21626 //
21627 // This is a hack, but it is far superior to moving the
21628 // corresponding target-specific code from IR-gen to Sema/AST.
21629
21630 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21631 SmallVector<QualType, 8> ArgTypes;
21632 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21633 ArgTypes.reserve(E->getNumArgs());
21634 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21635 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21636 }
21637 ParamTypes = ArgTypes;
21638 }
21639 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21640 Proto->getExtProtoInfo());
21641 } else {
21642 DestType = S.Context.getFunctionNoProtoType(DestType,
21643 FnType->getExtInfo());
21644 }
21645
21646 // Rebuild the appropriate pointer-to-function type.
21647 switch (Kind) {
21648 case FK_MemberFunction:
21649 // Nothing to do.
21650 break;
21651
21652 case FK_FunctionPointer:
21653 DestType = S.Context.getPointerType(DestType);
21654 break;
21655
21656 case FK_BlockPointer:
21657 DestType = S.Context.getBlockPointerType(DestType);
21658 break;
21659 }
21660
21661 // Finally, we can recurse.
21662 ExprResult CalleeResult = Visit(CalleeExpr);
21663 if (!CalleeResult.isUsable()) return ExprError();
21664 E->setCallee(CalleeResult.get());
21665
21666 // Bind a temporary if necessary.
21667 return S.MaybeBindToTemporary(E);
21668}
21669
21670ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21671 // Verify that this is a legal result type of a call.
21672 if (DestType->isArrayType() || DestType->isFunctionType()) {
21673 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21674 << DestType->isFunctionType() << DestType;
21675 return ExprError();
21676 }
21677
21678 // Rewrite the method result type if available.
21679 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21680 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21681 Method->setReturnType(DestType);
21682 }
21683
21684 // Change the type of the message.
21685 E->setType(DestType.getNonReferenceType());
21687
21688 return S.MaybeBindToTemporary(E);
21689}
21690
21691ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21692 // The only case we should ever see here is a function-to-pointer decay.
21693 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21694 assert(E->isPRValue());
21695 assert(E->getObjectKind() == OK_Ordinary);
21696
21697 E->setType(DestType);
21698
21699 // Rebuild the sub-expression as the pointee (function) type.
21700 DestType = DestType->castAs<PointerType>()->getPointeeType();
21701
21702 ExprResult Result = Visit(E->getSubExpr());
21703 if (!Result.isUsable()) return ExprError();
21704
21705 E->setSubExpr(Result.get());
21706 return E;
21707 } else if (E->getCastKind() == CK_LValueToRValue) {
21708 assert(E->isPRValue());
21709 assert(E->getObjectKind() == OK_Ordinary);
21710
21711 assert(isa<BlockPointerType>(E->getType()));
21712
21713 E->setType(DestType);
21714
21715 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21716 DestType = S.Context.getLValueReferenceType(DestType);
21717
21718 ExprResult Result = Visit(E->getSubExpr());
21719 if (!Result.isUsable()) return ExprError();
21720
21721 E->setSubExpr(Result.get());
21722 return E;
21723 } else {
21724 llvm_unreachable("Unhandled cast type!");
21725 }
21726}
21727
21728ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21729 ExprValueKind ValueKind = VK_LValue;
21730 QualType Type = DestType;
21731
21732 // We know how to make this work for certain kinds of decls:
21733
21734 // - functions
21735 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21736 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21737 DestType = Ptr->getPointeeType();
21738 ExprResult Result = resolveDecl(E, VD);
21739 if (Result.isInvalid()) return ExprError();
21740 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21741 VK_PRValue);
21742 }
21743
21744 if (!Type->isFunctionType()) {
21745 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21746 << VD << E->getSourceRange();
21747 return ExprError();
21748 }
21749 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21750 // We must match the FunctionDecl's type to the hack introduced in
21751 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21752 // type. See the lengthy commentary in that routine.
21753 QualType FDT = FD->getType();
21754 const FunctionType *FnType = FDT->castAs<FunctionType>();
21755 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21756 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21757 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21758 SourceLocation Loc = FD->getLocation();
21759 FunctionDecl *NewFD = FunctionDecl::Create(
21760 S.Context, FD->getDeclContext(), Loc, Loc,
21761 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21763 false /*isInlineSpecified*/, FD->hasPrototype(),
21764 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21765
21766 if (FD->getQualifier())
21767 NewFD->setQualifierInfo(FD->getQualifierLoc());
21768
21769 SmallVector<ParmVarDecl*, 16> Params;
21770 for (const auto &AI : FT->param_types()) {
21771 ParmVarDecl *Param =
21772 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21773 Param->setScopeInfo(0, Params.size());
21774 Params.push_back(Param);
21775 }
21776 NewFD->setParams(Params);
21777 DRE->setDecl(NewFD);
21778 VD = DRE->getDecl();
21779 }
21780 }
21781
21782 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21783 if (MD->isInstance()) {
21784 ValueKind = VK_PRValue;
21786 }
21787
21788 // Function references aren't l-values in C.
21789 if (!S.getLangOpts().CPlusPlus)
21790 ValueKind = VK_PRValue;
21791
21792 // - variables
21793 } else if (isa<VarDecl>(VD)) {
21794 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21795 Type = RefTy->getPointeeType();
21796 } else if (Type->isFunctionType()) {
21797 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21798 << VD << E->getSourceRange();
21799 return ExprError();
21800 }
21801
21802 // - nothing else
21803 } else {
21804 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21805 << VD << E->getSourceRange();
21806 return ExprError();
21807 }
21808
21809 // Modifying the declaration like this is friendly to IR-gen but
21810 // also really dangerous.
21811 VD->setType(DestType);
21812 E->setType(Type);
21813 E->setValueKind(ValueKind);
21814 return E;
21815}
21816
21819 ExprValueKind &VK, CXXCastPath &Path) {
21820 // The type we're casting to must be either void or complete.
21821 if (!CastType->isVoidType() &&
21823 diag::err_typecheck_cast_to_incomplete))
21824 return ExprError();
21825
21826 // Rewrite the casted expression from scratch.
21827 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21828 if (!result.isUsable()) return ExprError();
21829
21830 CastExpr = result.get();
21832 CastKind = CK_NoOp;
21833
21834 return CastExpr;
21835}
21836
21838 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21839}
21840
21842 Expr *arg, QualType &paramType) {
21843 // If the syntactic form of the argument is not an explicit cast of
21844 // any sort, just do default argument promotion.
21845 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21846 if (!castArg) {
21848 if (result.isInvalid()) return ExprError();
21849 paramType = result.get()->getType();
21850 return result;
21851 }
21852
21853 // Otherwise, use the type that was written in the explicit cast.
21854 assert(!arg->hasPlaceholderType());
21855 paramType = castArg->getTypeAsWritten();
21856
21857 // Copy-initialize a parameter of that type.
21858 InitializedEntity entity =
21860 /*consumed*/ false);
21861 return PerformCopyInitialization(entity, callLoc, arg);
21862}
21863
21865 Expr *orig = E;
21866 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21867 while (true) {
21868 E = E->IgnoreParenImpCasts();
21869 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21870 E = call->getCallee();
21871 diagID = diag::err_uncasted_call_of_unknown_any;
21872 } else {
21873 break;
21874 }
21875 }
21876
21877 SourceLocation loc;
21878 NamedDecl *d;
21879 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21880 loc = ref->getLocation();
21881 d = ref->getDecl();
21882 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21883 loc = mem->getMemberLoc();
21884 d = mem->getMemberDecl();
21885 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21886 diagID = diag::err_uncasted_call_of_unknown_any;
21887 loc = msg->getSelectorStartLoc();
21888 d = msg->getMethodDecl();
21889 if (!d) {
21890 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21891 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21892 << orig->getSourceRange();
21893 return ExprError();
21894 }
21895 } else {
21896 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21897 << E->getSourceRange();
21898 return ExprError();
21899 }
21900
21901 S.Diag(loc, diagID) << d << orig->getSourceRange();
21902
21903 // Never recoverable.
21904 return ExprError();
21905}
21906
21908 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21909 if (!placeholderType) return E;
21910
21911 switch (placeholderType->getKind()) {
21912 case BuiltinType::UnresolvedTemplate: {
21913 auto *ULE = cast<UnresolvedLookupExpr>(E->IgnoreParens());
21914 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21915 // There's only one FoundDecl for UnresolvedTemplate type. See
21916 // BuildTemplateIdExpr.
21917 NamedDecl *Temp = *ULE->decls_begin();
21918 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
21919
21920 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21921 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21922 // as it models only the unqualified-id case, where this case can clearly be
21923 // qualified. Thus we can't just qualify an assumed template.
21924 TemplateName TN;
21925 if (auto *TD = dyn_cast<TemplateDecl>(Temp))
21926 TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),
21927 TemplateName(TD));
21928 else
21929 TN = Context.getAssumedTemplateName(NameInfo.getName());
21930
21931 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21932 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21933 Diag(Temp->getLocation(), diag::note_referenced_type_template)
21934 << IsTypeAliasTemplateDecl;
21935
21936 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21937 bool HasAnyDependentTA = false;
21938 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21939 HasAnyDependentTA |= Arg.getArgument().isDependent();
21940 TAL.addArgument(Arg);
21941 }
21942
21943 QualType TST;
21944 {
21945 SFINAETrap Trap(*this);
21946 TST = CheckTemplateIdType(
21947 ElaboratedTypeKeyword::None, TN, NameInfo.getBeginLoc(), TAL,
21948 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21949 }
21950 if (TST.isNull())
21951 TST = Context.getTemplateSpecializationType(
21952 ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),
21953 /*CanonicalArgs=*/{},
21954 HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21955 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},
21956 TST);
21957 }
21958
21959 // Overloaded expressions.
21960 case BuiltinType::Overload: {
21961 // Try to resolve a single function template specialization.
21962 // This is obligatory.
21963 ExprResult Result = E;
21965 return Result;
21966
21967 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21968 // leaves Result unchanged on failure.
21969 Result = E;
21971 return Result;
21972
21973 // If that failed, try to recover with a call.
21974 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21975 /*complain*/ true);
21976 return Result;
21977 }
21978
21979 // Bound member functions.
21980 case BuiltinType::BoundMember: {
21981 ExprResult result = E;
21982 const Expr *BME = E->IgnoreParens();
21983 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21984 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21986 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21987 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21988 if (ME->getMemberNameInfo().getName().getNameKind() ==
21990 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21991 }
21992 tryToRecoverWithCall(result, PD,
21993 /*complain*/ true);
21994 return result;
21995 }
21996
21997 // ARC unbridged casts.
21998 case BuiltinType::ARCUnbridgedCast: {
21999 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
22000 ObjC().diagnoseARCUnbridgedCast(realCast);
22001 return realCast;
22002 }
22003
22004 // Expressions of unknown type.
22005 case BuiltinType::UnknownAny:
22006 return diagnoseUnknownAnyExpr(*this, E);
22007
22008 // Pseudo-objects.
22009 case BuiltinType::PseudoObject:
22010 return PseudoObject().checkRValue(E);
22011
22012 case BuiltinType::BuiltinFn: {
22013 // Accept __noop without parens by implicitly converting it to a call expr.
22014 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
22015 if (DRE) {
22016 auto *FD = cast<FunctionDecl>(DRE->getDecl());
22017 unsigned BuiltinID = FD->getBuiltinID();
22018 if (BuiltinID == Builtin::BI__noop) {
22019 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
22020 CK_BuiltinFnToFnPtr)
22021 .get();
22022 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
22025 }
22026
22027 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
22028 // Any use of these other than a direct call is ill-formed as of C++20,
22029 // because they are not addressable functions. In earlier language
22030 // modes, warn and force an instantiation of the real body.
22031 Diag(E->getBeginLoc(),
22033 ? diag::err_use_of_unaddressable_function
22034 : diag::warn_cxx20_compat_use_of_unaddressable_function);
22035 if (FD->isImplicitlyInstantiable()) {
22036 // Require a definition here because a normal attempt at
22037 // instantiation for a builtin will be ignored, and we won't try
22038 // again later. We assume that the definition of the template
22039 // precedes this use.
22041 /*Recursive=*/false,
22042 /*DefinitionRequired=*/true,
22043 /*AtEndOfTU=*/false);
22044 }
22045 // Produce a properly-typed reference to the function.
22046 CXXScopeSpec SS;
22047 SS.Adopt(DRE->getQualifierLoc());
22048 TemplateArgumentListInfo TemplateArgs;
22049 DRE->copyTemplateArgumentsInto(TemplateArgs);
22050 return BuildDeclRefExpr(
22051 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
22052 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
22053 DRE->getTemplateKeywordLoc(),
22054 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
22055 }
22056 }
22057
22058 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
22059 return ExprError();
22060 }
22061
22062 case BuiltinType::IncompleteMatrixIdx: {
22063 auto *MS = cast<MatrixSubscriptExpr>(E->IgnoreParens());
22064 // At this point, we know there was no second [] to complete the operator.
22065 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
22066 if (getLangOpts().HLSL) {
22068 MS->getBase(), MS->getRowIdx(), E->getExprLoc());
22069 }
22070 Diag(MS->getRowIdx()->getBeginLoc(), diag::err_matrix_incomplete_index);
22071 return ExprError();
22072 }
22073
22074 // Expressions of unknown type.
22075 case BuiltinType::ArraySection:
22076 // If we've already diagnosed something on the array section type, we
22077 // shouldn't need to do any further diagnostic here.
22078 if (!E->containsErrors())
22079 Diag(E->getBeginLoc(), diag::err_array_section_use)
22080 << cast<ArraySectionExpr>(E->IgnoreParens())->isOMPArraySection();
22081 return ExprError();
22082
22083 // Expressions of unknown type.
22084 case BuiltinType::OMPArrayShaping:
22085 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
22086
22087 case BuiltinType::OMPIterator:
22088 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
22089
22090 // Everything else should be impossible.
22091#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
22092 case BuiltinType::Id:
22093#include "clang/Basic/OpenCLImageTypes.def"
22094#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
22095 case BuiltinType::Id:
22096#include "clang/Basic/OpenCLExtensionTypes.def"
22097#define SVE_TYPE(Name, Id, SingletonId) \
22098 case BuiltinType::Id:
22099#include "clang/Basic/AArch64ACLETypes.def"
22100#define PPC_VECTOR_TYPE(Name, Id, Size) \
22101 case BuiltinType::Id:
22102#include "clang/Basic/PPCTypes.def"
22103#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22104#include "clang/Basic/RISCVVTypes.def"
22105#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22106#include "clang/Basic/WebAssemblyReferenceTypes.def"
22107#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
22108#include "clang/Basic/AMDGPUTypes.def"
22109#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22110#include "clang/Basic/HLSLIntangibleTypes.def"
22111#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
22112#define PLACEHOLDER_TYPE(Id, SingletonId)
22113#include "clang/AST/BuiltinTypes.def"
22114 break;
22115 }
22116
22117 llvm_unreachable("invalid placeholder type!");
22118}
22119
22121 if (E->isTypeDependent())
22122 return true;
22124 return E->getType()->isIntegralOrEnumerationType();
22125 return false;
22126}
22127
22129 ArrayRef<Expr *> SubExprs, QualType T) {
22130 if (!Context.getLangOpts().RecoveryAST)
22131 return ExprError();
22132
22133 if (isSFINAEContext())
22134 return ExprError();
22135
22136 if (T.isNull() || T->isUndeducedType() ||
22137 !Context.getLangOpts().RecoveryASTType)
22138 // We don't know the concrete type, fallback to dependent type.
22139 T = Context.DependentTy;
22140
22141 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
22142}
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 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 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 Decl * getPredefinedExprDecl(DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
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:563
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:588
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.
Defines enumerations for the type traits support.
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:508
bool hasValue() const
Definition APValue.h:483
bool isInt() const
Definition APValue.h:485
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:974
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:809
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:805
const LangOptions & getLangOpts() const
Definition ASTContext.h:962
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition ASTContext.h:927
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:924
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:1777
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3800
QualType getElementType() const
Definition TypeBase.h:3798
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition Expr.h:6736
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:2187
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:2140
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:5104
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:2212
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:2149
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:4713
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4707
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.cpp:5443
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition Decl.h:4789
void setBlockMissingReturnType(bool val=true)
Definition Decl.h:4846
void setIsVariadic(bool value)
Definition Decl.h:4783
SourceLocation getCaretLocation() const
Definition Decl.h:4780
void setBody(CompoundStmt *B)
Definition Decl.h:4787
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:4793
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition Decl.cpp:5454
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5647
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6675
Pointer to a block type.
Definition TypeBase.h:3606
This class is used for builtin types like 'int'.
Definition TypeBase.h:3228
bool isSVEBool() const
Definition TypeBase.h:3305
Kind getKind() const
Definition TypeBase.h:3276
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:1967
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:1552
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
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:3295
Represents a C++ base or member initializer.
Definition DeclCXX.h:2398
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1274
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:1381
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:2522
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:85
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition ExprCXX.h:156
SourceRange getSourceRange() const
Definition ExprCXX.h:168
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition ExprCXX.cpp:1998
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition ExprCXX.h:2749
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:604
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:2085
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:1943
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:1158
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:3339
QualType getElementType() const
Definition TypeBase.h:3349
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:5126
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3611
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1750
bool body_empty() const
Definition Stmt.h:1794
Stmt * body_back()
Definition Stmt.h:1818
ConditionalOperator - The ?
Definition Expr.h:4397
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3880
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3900
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:4451
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4470
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4467
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:1474
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:2255
bool isRequiresExprBody() const
Definition DeclBase.h:2211
DeclContextLookupResult lookup_result
Definition DeclBase.h:2594
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.
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:776
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:591
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:2015
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1952
DeclaratorContext getContext() const
Definition DeclSpec.h:2124
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2135
bool isInvalidType() const
Definition DeclSpec.h:2766
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2382
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:961
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:730
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseLambdaCapture(MaybeConst< LambdaExpr > *LE, const LambdaCapture *C, MaybeConst< Expr > *Init)
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
Represents a reference to emded data.
Definition Expr.h:5132
RAII object that enters a new expression evaluation context.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4219
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:3126
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:3055
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:3104
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:3099
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3087
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition Expr.cpp:3108
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:3095
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:3348
@ 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:3697
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:3079
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:4077
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:4329
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:6613
ExtVectorType - Extended vector type.
Definition TypeBase.h:4331
Represents difference between two FPOptions values.
bool isFPConstrained() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3195
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3298
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3375
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3431
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:2027
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:2216
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2828
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3824
bool isImmediateFunction() const
Definition Decl.cpp:3317
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4001
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3739
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3842
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2952
QualType getReturnType() const
Definition Decl.h:2876
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2805
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2470
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3595
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isImmediateEscalating() const
Definition Decl.cpp:3288
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2964
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4107
bool isConsteval() const
Definition Decl.h:2509
size_t param_size() const
Definition Decl.h:2821
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3176
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition Decl.cpp:4017
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition Decl.h:2912
Represents a reference to a function parameter pack, init-capture pack, or binding pack that has been...
Definition ExprCXX.h:4841
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4870
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5875
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5678
bool isParamConsumed(unsigned I) const
Definition TypeBase.h:5889
unsigned getNumParams() const
Definition TypeBase.h:5649
QualType getParamType(unsigned i) const
Definition TypeBase.h:5651
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5775
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5660
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5656
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5811
Declaration of a template function.
unsigned getNumParams() const
Definition TypeLoc.h:1716
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1722
SourceLocation getLocalRangeEnd() const
Definition TypeLoc.h:1668
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1725
SourceLocation getLocalRangeBegin() const
Definition TypeLoc.h:1660
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4678
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4749
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4606
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
ExtInfo getExtInfo() const
Definition TypeBase.h:4923
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:4915
bool getCFIUncheckedCalleeAttr() const
Determine whether this is a function prototype that includes the cfi_unchecked_callee attribute.
Definition Type.cpp:3702
QualType getReturnType() const
Definition TypeBase.h:4907
bool getCmseNSCallAttr() const
Definition TypeBase.h:4921
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4935
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:4725
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:2079
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:3502
Describes an C or C++ initializer list.
Definition Expr.h:5305
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
Describes the capture of a variable or of this, or of a C++1y init-capture.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1972
capture_iterator capture_begin() const
Retrieve an iterator pointing to the first lambda capture.
Definition ExprCXX.cpp:1370
static LambdaExpr * Create(const ASTContext &C, CXXRecordDecl *Class, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, ArrayRef< Expr * > CaptureInits, SourceLocation ClosingBrace, bool ContainsUnexpandedParameterPack)
Construct a new lambda expression.
Definition ExprCXX.cpp:1319
SourceLocation getEndLoc() const LLVM_READONLY
Definition ExprCXX.h:2190
bool hasExplicitParameters() const
Determine whether this lambda has an explicit parameter list vs.
Definition ExprCXX.h:2175
SourceRange getIntroducerRange() const
Retrieve the source range covering the lambda introducer, which contains the explicit capture list su...
Definition ExprCXX.h:2123
unsigned capture_size() const
Determine the number of captures in this lambda.
Definition ExprCXX.h:2053
bool isInitCapture(const LambdaCapture *Capture) const
Determine whether one of this lambda's captures is an init-capture.
Definition ExprCXX.cpp:1365
CXXMethodDecl * getCallOperator() const
Retrieve the function call operator associated with this lambda expression.
Definition ExprCXX.cpp:1411
bool hasExplicitResultType() const
Whether this lambda had its result type explicitly specified.
Definition ExprCXX.h:2178
capture_iterator capture_end() const
Retrieve an iterator pointing past the end of the sequence of lambda captures.
Definition ExprCXX.cpp:1374
SourceLocation getCaptureDefaultLoc() const
Retrieve the location of this lambda's capture-default, if any.
Definition ExprCXX.h:2030
llvm::iterator_range< capture_init_iterator > capture_inits()
Retrieve the initialization expressions for this lambda's captures.
Definition ExprCXX.h:2087
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2098
LambdaCaptureDefault getCaptureDefault() const
Determine the default capture kind for this lambda.
Definition ExprCXX.h:2025
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1407
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:1074
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:319
Represents the results of name lookup.
Definition Lookup.h:147
DeclClass * getAsSingle() const
Definition Lookup.h:558
A global _GUID constant.
Definition DeclCXX.h:4419
MS property subscript expression.
Definition ExprCXX.h:1010
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:4401
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4415
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:1756
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:1800
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:1681
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:1154
bool hasDefinition() const
Determine whether this class has been defined.
Definition DeclObjC.h:1528
ivar_iterator ivar_begin() const
Definition DeclObjC.h:1453
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:349
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8009
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition ExprObjC.h:1529
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:580
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprObjC.h:626
SourceLocation getLocation() const
Definition ExprObjC.h:623
SourceLocation getOpLoc() const
Definition ExprObjC.h:631
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:610
bool isArrow() const
Definition ExprObjC.h:618
SourceLocation getEndLoc() const LLVM_READONLY
Definition ExprObjC.h:629
const Expr * getBase() const
Definition ExprObjC.h:614
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:971
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1395
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
ImplicitParamDecl * getSelfDecl() const
Definition DeclObjC.h:418
bool isClassMethod() const
Definition DeclObjC.h:434
Represents a pointer to an Objective C object.
Definition TypeBase.h:8065
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:8184
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2084
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:1659
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:3132
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3193
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:6115
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:4976
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition Expr.h:6113
SourceLocation getLParenLoc() const
Definition Expr.h:6132
SourceLocation getRParenLoc() const
Definition Expr.h:6133
Represents a parameter to a function.
Definition Decl.h:1817
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1850
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:2934
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
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:6807
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8536
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:3686
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:1431
QualType withConst() const
Definition TypeBase.h:1174
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1171
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8573
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:8487
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:1453
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:8632
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition Type.cpp:3046
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1194
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C.
Definition TypeBase.h:8639
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8520
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:1560
bool isCanonical() const
Definition TypeBase.h:8504
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1324
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
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:8612
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8479
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:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
void removeObjCLifetime()
Definition TypeBase.h:551
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
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:708
void removeAddressSpace()
Definition TypeBase.h:596
void setAddressSpace(LangAS space)
Definition TypeBase.h:591
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
Qualifiers withoutObjCLifetime() const
Definition TypeBase.h:533
Qualifiers withoutObjCGCAttr() const
Definition TypeBase.h:528
LangAS getAddressSpace() const
Definition TypeBase.h:571
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:750
Represents a struct/union/class.
Definition Decl.h:4360
bool hasFlexibleArrayMember() const
Definition Decl.h:4393
field_iterator field_end() const
Definition Decl.h:4566
field_range fields() const
Definition Decl.h:4563
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4548
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition Expr.cpp:5470
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:3637
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:410
bool Contains(const Scope &rhs) const
Returns if rhs has a higher scope depth than this.
Definition Scope.h:619
bool isInCFunctionScope() const
isInObjcMethodScope - Return true if this scope is, or is contained, in an C function body.
Definition Scope.h:430
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:469
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:1764
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:858
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:378
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:8529
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12547
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12591
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7798
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:1449
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:8282
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13683
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1142
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:8332
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
bool isAlwaysConstantEvaluatedContext() const
Definition Sema.h:8250
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:955
bool isAttrContext() const
Definition Sema.h:7039
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:8325
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9415
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9454
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9423
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:1534
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:1252
SemaCUDA & CUDA()
Definition Sema.h:1474
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:7919
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7921
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7920
bool needsRebuildOfDefaultArgOrInit() const
Definition Sema.h:8270
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:8412
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1245
Preprocessor & getPreprocessor() const
Definition Sema.h:939
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7017
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2427
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:8401
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition Sema.h:8313
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:6846
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:2078
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:1559
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:7029
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:1725
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:840
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:1309
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:8237
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:937
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:1519
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:2937
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:761
bool isImmediateFunctionContext() const
Definition Sema.h:8262
ASTContext & getASTContext() const
Definition Sema.h:940
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1082
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition SemaExpr.cpp:771
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:762
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition SemaExpr.cpp:890
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:6164
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6166
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:1213
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1730
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:11509
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:512
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:8297
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:935
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8395
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
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:14560
const LangOptions & getLangOpts() const
Definition Sema.h:933
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:2558
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:1524
ReuseLambdaContextDecl_t
Definition Sema.h:7108
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:1308
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:2236
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:1307
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2673
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:959
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6590
SemaHLSL & HLSL()
Definition Sema.h:1484
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:15791
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:5326
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:7053
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6620
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:14105
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:869
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:1342
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:7050
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:2410
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:645
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:8266
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:8133
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2628
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1447
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:12618
SemaOpenCL & OpenCL()
Definition Sema.h:1529
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:14114
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:8258
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1705
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:6849
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:14049
SourceManager & getSourceManager() const
Definition Sema.h:938
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:7562
@ NTCUK_Destruct
Definition Sema.h:4144
@ NTCUK_Copy
Definition Sema.h:4145
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition Sema.h:8411
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:2458
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:6847
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:13782
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:15563
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:2613
bool isConstantEvaluatedContext() const
Definition Sema.h:2640
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:1310
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4703
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:7057
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:1347
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14097
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:6791
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6813
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6803
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6818
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6808
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6828
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6797
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6823
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6838
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:1268
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:8248
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:8398
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:1312
@ TemplateNameIsRequired
Definition Sema.h:11486
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:790
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:1311
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:934
FPOptions CurFPFeatures
Definition Sema.h:1305
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:521
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:1589
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:6624
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:631
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:2219
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:8056
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9468
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9474
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9466
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9471
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9482
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9478
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:6505
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition Sema.h:14093
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:7905
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:1544
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2604
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:8274
SemaARM & ARM()
Definition Sema.h:1454
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:11056
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:8743
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:5023
SourceLocation getBeginLoc() const
Definition Expr.h:5068
const DeclContext * getParentContext() const
If the SourceLocExpr has been resolved return the subexpression representing the resolved value.
Definition Expr.h:5064
SourceLocation getEndLoc() const
Definition Expr.h:5069
SourceLocIdentKind getIdentKind() const
Definition Expr.h:5043
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:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
StmtClass getStmtClass() const
Definition Stmt.h:1503
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:3853
bool isUnion() const
Definition Decl.h:3963
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:736
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:336
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.
ExprResult TransformInitializer(Expr *Init, bool NotCopyInit)
EnsureImmediateInvocationInDefaultArgs & getDerived()
Represents a declaration of a type.
Definition Decl.h:3548
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3582
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:2735
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8418
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:8429
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2545
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition TypeBase.h:9118
bool isBlockPointerType() const
Definition TypeBase.h:8704
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
bool isObjCBuiltinType() const
Definition TypeBase.h:8914
bool isMFloat8Type() const
Definition TypeBase.h:9075
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:9237
bool isIncompleteArrayType() const
Definition TypeBase.h:8791
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:9026
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:9217
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:8783
bool isCharType() const
Definition Type.cpp:2197
bool isFunctionPointerType() const
Definition TypeBase.h:8751
bool isArithmeticType() const
Definition Type.cpp:2426
bool isConstantMatrixType() const
Definition TypeBase.h:8851
bool isPointerType() const
Definition TypeBase.h:8684
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
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:9344
bool isReferenceType() const
Definition TypeBase.h:8708
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:9138
bool isEnumeralType() const
Definition TypeBase.h:8815
bool isScalarType() const
Definition TypeBase.h:9156
bool isVariableArrayType() const
Definition TypeBase.h:8795
bool isSizelessBuiltinType() const
Definition Type.cpp:2627
bool isClkEventT() const
Definition TypeBase.h:8936
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:8884
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:9172
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:8827
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:8831
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:8948
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition TypeBase.h:9044
bool isPipeType() const
Definition TypeBase.h:8955
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2854
bool isBitIntType() const
Definition TypeBase.h:8959
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9019
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8807
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
bool isAnyComplexType() const
Definition TypeBase.h:8819
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9110
bool isHalfType() const
Definition TypeBase.h:9054
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9126
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2465
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition Type.cpp:2458
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9032
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:8940
bool isMemberPointerType() const
Definition TypeBase.h:8765
bool isAtomicType() const
Definition TypeBase.h:8876
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9200
bool isObjCIdType() const
Definition TypeBase.h:8896
bool isMatrixType() const
Definition TypeBase.h:8847
bool isOverflowBehaviorType() const
Definition TypeBase.h:8855
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:2864
bool isComplexIntegerType() const
Definition Type.cpp:767
bool isUnscopedEnumerationType() const
Definition Type.cpp:2190
bool isObjCObjectType() const
Definition TypeBase.h:8867
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition Type.cpp:5365
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9330
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5454
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9193
bool isHLSLResourceRecord() const
Definition Type.cpp:5514
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isDoubleType() const
Definition TypeBase.h:9067
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:8680
bool isObjCObjectPointerType() const
Definition TypeBase.h:8863
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:9152
bool isVectorType() const
Definition TypeBase.h:8823
bool isObjCQualifiedClassType() const
Definition TypeBase.h:8890
bool isObjCClassType() const
Definition TypeBase.h:8902
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:2985
@ STK_FloatingComplex
Definition TypeBase.h:2828
@ STK_ObjCObjectPointer
Definition TypeBase.h:2822
@ STK_IntegralComplex
Definition TypeBase.h:2827
@ STK_MemberPointer
Definition TypeBase.h:2823
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:2992
bool isAnyPointerType() const
Definition TypeBase.h:8692
bool isRealType() const
Definition Type.cpp:2415
TypeClass getTypeClass() const
Definition TypeBase.h:2445
bool isSubscriptableVectorType() const
Definition TypeBase.h:8843
bool isSamplerT() const
Definition TypeBase.h:8928
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
bool isNullPtrType() const
Definition TypeBase.h:9087
bool isRecordType() const
Definition TypeBase.h:8811
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5518
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:5156
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:5161
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4476
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1039
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1127
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1121
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1091
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3390
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:4126
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition ExprCXX.cpp:1690
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:1652
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:644
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:5578
VarDecl * getPotentiallyDecomposedVarDecl()
Definition DeclCXX.cpp:3693
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:932
bool hasInit() const
Definition Decl.cpp:2377
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2236
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1600
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:940
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:1304
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:2465
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:2868
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1573
const Expr * getInit() const
Definition Decl.h:1389
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:1316
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2354
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:2507
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:2761
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1283
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:2740
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2859
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4030
Expr * getSizeExpr() const
Definition TypeBase.h:4044
Represents a GCC generic vector type.
Definition TypeBase.h:4239
unsigned getNumElements() const
Definition TypeBase.h:4254
VectorKind getVectorKind() const
Definition TypeBase.h:4259
QualType getElementType() const
Definition TypeBase.h:4253
Retains information about a block that is currently being parsed.
Definition ScopeInfo.h:786
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition ScopeInfo.h:792
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition ScopeInfo.h:796
ValueDecl * getVariable() const
Definition ScopeInfo.h:671
bool isBlockCapture() const
Definition ScopeInfo.h:652
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:682
void markUsed(bool IsODRUse)
Definition ScopeInfo.h:664
bool isInvalid() const
Definition ScopeInfo.h:657
bool isThisCapture() const
Definition ScopeInfo.h:645
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition ScopeInfo.h:691
bool isCopyCapture() const
Definition ScopeInfo.h:650
bool isNested() const
Definition ScopeInfo.h:655
Retains information about a captured region.
Definition ScopeInfo.h:812
unsigned short CapRegionKind
The kind of captured region.
Definition ScopeInfo.h:827
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:741
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:728
bool ContainsUnexpandedParameterPack
Whether this contains an unexpanded parameter pack.
Definition ScopeInfo.h:724
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:717
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:704
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of 'this'; zero if 'this' is not captured.
Definition ScopeInfo.h:714
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition ScopeInfo.h:754
llvm::DenseMap< ValueDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition ScopeInfo.h:710
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:751
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:733
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition ScopeInfo.h:767
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:1086
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:489
llvm::SmallVector< AddrLabelExpr *, 4 > AddrLabels
The set of GNU address of label extension "&&label".
Definition ScopeInfo.h:246
bool HasOMPDeclareReductionCombiner
True if current scope is for OpenMP declare reduction combiner.
Definition ScopeInfo.h:135
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:880
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:988
void addPotentialThisCapture(SourceLocation Loc)
Definition ScopeInfo.h:994
llvm::SmallPtrSet< VarDecl *, 4 > CUDAPotentialODRUsedVars
Variables that are potentially ODR-used in CUDA/HIP.
Definition ScopeInfo.h:949
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:867
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition ScopeInfo.h:888
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:875
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:870
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:95
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:27
The JSON file list parser is used to communicate input to InstallAPI.
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:63
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:1033
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1031
@ 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
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition TypeTraits.h:51
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:905
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
const char * getTraitSpelling(ExpressionTrait T) LLVM_READONLY
Return the spelling of the type trait TT. Never null.
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:4209
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4218
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4203
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4206
@ Neon
is ARM Neon vector
Definition TypeBase.h:4212
@ Generic
not a target-specific vector type
Definition TypeBase.h:4200
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4224
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4227
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4221
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:5010
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5991
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:1772
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
TreeTransform< EnsureImmediateInvocationInDefaultArgs > Base
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:5099
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:5456
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13211
Data structure used to record current or nested expression evaluation contexts.
Definition Sema.h:6853
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition Sema.h:6888
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6939
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition Sema.h:6873
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition Sema.h:6893
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:6901
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition Sema.h:6897
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6907
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:6868
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:6915
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition Sema.h:6858
ExpressionEvaluationContext Context
The expression evaluation context.
Definition Sema.h:6855
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition Sema.h:6862
Abstract class used to diagnose incomplete types.
Definition Sema.h:8339
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.