clang 22.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/Attrs.inc"
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"
33#include "clang/AST/Type.h"
34#include "clang/AST/TypeLoc.h"
45#include "clang/Sema/DeclSpec.h"
50#include "clang/Sema/Lookup.h"
51#include "clang/Sema/Overload.h"
53#include "clang/Sema/Scope.h"
55#include "clang/Sema/SemaARM.h"
56#include "clang/Sema/SemaCUDA.h"
58#include "clang/Sema/SemaHLSL.h"
59#include "clang/Sema/SemaObjC.h"
62#include "clang/Sema/Template.h"
63#include "llvm/ADT/STLExtras.h"
64#include "llvm/ADT/StringExtras.h"
65#include "llvm/Support/ConvertUTF.h"
66#include "llvm/Support/SaveAndRestore.h"
67#include "llvm/Support/TimeProfiler.h"
68#include "llvm/Support/TypeSize.h"
69#include <limits>
70#include <optional>
71
72using namespace clang;
73using namespace sema;
74
75bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
76 // See if this is an auto-typed variable whose initializer we are parsing.
77 if (ParsingInitForAutoVars.count(D))
78 return false;
79
80 // See if this is a deleted function.
81 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
82 if (FD->isDeleted())
83 return false;
84
85 // If the function has a deduced return type, and we can't deduce it,
86 // then we can't use it either.
87 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
88 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
89 return false;
90
91 // See if this is an aligned allocation/deallocation function that is
92 // unavailable.
93 if (TreatUnavailableAsInvalid &&
95 return false;
96 }
97
98 // See if this function is unavailable.
99 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
100 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
101 return false;
102
104 return false;
105
106 return true;
107}
108
110 // Warn if this is used but marked unused.
111 if (const auto *A = D->getAttr<UnusedAttr>()) {
112 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
113 // should diagnose them.
114 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
115 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
116 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
117 if (DC && !DC->hasAttr<UnusedAttr>())
118 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
119 }
120 }
121}
122
124 assert(Decl && Decl->isDeleted());
125
126 if (Decl->isDefaulted()) {
127 // If the method was explicitly defaulted, point at that declaration.
128 if (!Decl->isImplicit())
129 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
130
131 // Try to diagnose why this special member function was implicitly
132 // deleted. This might fail, if that reason no longer applies.
134 return;
135 }
136
137 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
138 if (Ctor && Ctor->isInheritingConstructor())
140
141 Diag(Decl->getLocation(), diag::note_availability_specified_here)
142 << Decl << 1;
143}
144
145/// Determine whether a FunctionDecl was ever declared with an
146/// explicit storage class.
148 for (auto *I : D->redecls()) {
149 if (I->getStorageClass() != SC_None)
150 return true;
151 }
152 return false;
153}
154
155/// Check whether we're in an extern inline function and referring to a
156/// variable or function with internal linkage (C11 6.7.4p3).
157///
158/// This is only a warning because we used to silently accept this code, but
159/// in many cases it will not behave correctly. This is not enabled in C++ mode
160/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
161/// and so while there may still be user mistakes, most of the time we can't
162/// prove that there are errors.
164 const NamedDecl *D,
165 SourceLocation Loc) {
166 // This is disabled under C++; there are too many ways for this to fire in
167 // contexts where the warning is a false positive, or where it is technically
168 // correct but benign.
169 //
170 // WG14 N3622 which removed the constraint entirely in C2y. It is left
171 // enabled in earlier language modes because this is a constraint in those
172 // language modes. But in C2y mode, we still want to issue the "incompatible
173 // with previous standards" diagnostic, too.
174 if (S.getLangOpts().CPlusPlus)
175 return;
176
177 // Check if this is an inlined function or method.
178 FunctionDecl *Current = S.getCurFunctionDecl();
179 if (!Current)
180 return;
181 if (!Current->isInlined())
182 return;
183 if (!Current->isExternallyVisible())
184 return;
185
186 // Check if the decl has internal linkage.
188 return;
189
190 // Downgrade from ExtWarn to Extension if
191 // (1) the supposedly external inline function is in the main file,
192 // and probably won't be included anywhere else.
193 // (2) the thing we're referencing is a pure function.
194 // (3) the thing we're referencing is another inline function.
195 // This last can give us false negatives, but it's better than warning on
196 // wrappers for simple C library functions.
197 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
198 unsigned DiagID;
199 if (S.getLangOpts().C2y)
200 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
201 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
203 DiagID = diag::ext_internal_in_extern_inline_quiet;
204 else
205 DiagID = diag::ext_internal_in_extern_inline;
206
207 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
209 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
210 << D;
211}
212
214 const FunctionDecl *First = Cur->getFirstDecl();
215
216 // Suggest "static" on the function, if possible.
218 SourceLocation DeclBegin = First->getSourceRange().getBegin();
219 Diag(DeclBegin, diag::note_convert_inline_to_static)
220 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
221 }
222}
223
225 const ObjCInterfaceDecl *UnknownObjCClass,
226 bool ObjCPropertyAccess,
227 bool AvoidPartialAvailabilityChecks,
228 ObjCInterfaceDecl *ClassReceiver,
229 bool SkipTrailingRequiresClause) {
230 SourceLocation Loc = Locs.front();
232 // If there were any diagnostics suppressed by template argument deduction,
233 // emit them now.
234 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
235 if (Pos != SuppressedDiagnostics.end()) {
236 for (const auto &[DiagLoc, PD] : Pos->second) {
237 DiagnosticBuilder Builder(Diags.Report(DiagLoc, PD.getDiagID()));
238 PD.Emit(Builder);
239 }
240 // Clear out the list of suppressed diagnostics, so that we don't emit
241 // them again for this specialization. However, we don't obsolete this
242 // entry from the table, because we want to avoid ever emitting these
243 // diagnostics again.
244 Pos->second.clear();
245 }
246
247 // C++ [basic.start.main]p3:
248 // The function 'main' shall not be used within a program.
249 if (cast<FunctionDecl>(D)->isMain())
250 Diag(Loc, diag::ext_main_used);
251
253 }
254
255 // See if this is an auto-typed variable whose initializer we are parsing.
256 if (ParsingInitForAutoVars.count(D)) {
257 if (isa<BindingDecl>(D)) {
258 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
259 << D->getDeclName();
260 } else {
261 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
262 << diag::ParsingInitFor::Var << D->getDeclName()
263 << cast<VarDecl>(D)->getType();
264 }
265 return true;
266 }
267
268 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
269 // See if this is a deleted function.
270 if (FD->isDeleted()) {
271 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
272 if (Ctor && Ctor->isInheritingConstructor())
273 Diag(Loc, diag::err_deleted_inherited_ctor_use)
274 << Ctor->getParent()
275 << Ctor->getInheritedConstructor().getConstructor()->getParent();
276 else {
277 StringLiteral *Msg = FD->getDeletedMessage();
278 Diag(Loc, diag::err_deleted_function_use)
279 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
280 }
282 return true;
283 }
284
285 // [expr.prim.id]p4
286 // A program that refers explicitly or implicitly to a function with a
287 // trailing requires-clause whose constraint-expression is not satisfied,
288 // other than to declare it, is ill-formed. [...]
289 //
290 // See if this is a function with constraints that need to be satisfied.
291 // Check this before deducing the return type, as it might instantiate the
292 // definition.
293 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
294 ConstraintSatisfaction Satisfaction;
295 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
296 /*ForOverloadResolution*/ true))
297 // A diagnostic will have already been generated (non-constant
298 // constraint expression, for example)
299 return true;
300 if (!Satisfaction.IsSatisfied) {
301 Diag(Loc,
302 diag::err_reference_to_function_with_unsatisfied_constraints)
303 << D;
304 DiagnoseUnsatisfiedConstraint(Satisfaction);
305 return true;
306 }
307 }
308
309 // If the function has a deduced return type, and we can't deduce it,
310 // then we can't use it either.
311 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
312 DeduceReturnType(FD, Loc))
313 return true;
314
315 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
316 return true;
317
318 }
319
320 if (auto *Concept = dyn_cast<ConceptDecl>(D);
322 return true;
323
324 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
325 // Lambdas are only default-constructible or assignable in C++2a onwards.
326 if (MD->getParent()->isLambda() &&
328 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
329 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
330 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
332 }
333 }
334
335 auto getReferencedObjCProp = [](const NamedDecl *D) ->
336 const ObjCPropertyDecl * {
337 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
338 return MD->findPropertyDecl();
339 return nullptr;
340 };
341 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
342 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
343 return true;
344 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
345 return true;
346 }
347
348 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
349 // Only the variables omp_in and omp_out are allowed in the combiner.
350 // Only the variables omp_priv and omp_orig are allowed in the
351 // initializer-clause.
352 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
353 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
354 isa<VarDecl>(D)) {
355 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
357 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
358 return true;
359 }
360
361 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
362 // List-items in map clauses on this construct may only refer to the declared
363 // variable var and entities that could be referenced by a procedure defined
364 // at the same location.
365 // [OpenMP 5.2] Also allow iterator declared variables.
366 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
367 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
368 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
370 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
371 return true;
372 }
373
374 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
375 Diag(Loc, diag::err_use_of_empty_using_if_exists);
376 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
377 return true;
378 }
379
380 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
381 AvoidPartialAvailabilityChecks, ClassReceiver);
382
383 DiagnoseUnusedOfDecl(*this, D, Loc);
384
386
387 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
388 if (getLangOpts().getFPEvalMethod() !=
390 PP.getLastFPEvalPragmaLocation().isValid() &&
391 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
392 Diag(D->getLocation(),
393 diag::err_type_available_only_in_default_eval_method)
394 << D->getName();
395 }
396
397 if (auto *VD = dyn_cast<ValueDecl>(D))
398 checkTypeSupport(VD->getType(), Loc, VD);
399
400 if (LangOpts.SYCLIsDevice ||
401 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
402 if (!Context.getTargetInfo().isTLSSupported())
403 if (const auto *VD = dyn_cast<VarDecl>(D))
404 if (VD->getTLSKind() != VarDecl::TLS_None)
405 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
406 }
407
408 return false;
409}
410
412 ArrayRef<Expr *> Args) {
413 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
414 if (!Attr)
415 return;
416
417 // The number of formal parameters of the declaration.
418 unsigned NumFormalParams;
419
420 // The kind of declaration. This is also an index into a %select in
421 // the diagnostic.
422 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
423
424 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
425 NumFormalParams = MD->param_size();
426 CalleeKind = CK_Method;
427 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
428 NumFormalParams = FD->param_size();
429 CalleeKind = CK_Function;
430 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
431 QualType Ty = VD->getType();
432 const FunctionType *Fn = nullptr;
433 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
434 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
435 if (!Fn)
436 return;
437 CalleeKind = CK_Function;
438 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
439 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
440 CalleeKind = CK_Block;
441 } else {
442 return;
443 }
444
445 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
446 NumFormalParams = proto->getNumParams();
447 else
448 NumFormalParams = 0;
449 } else {
450 return;
451 }
452
453 // "NullPos" is the number of formal parameters at the end which
454 // effectively count as part of the variadic arguments. This is
455 // useful if you would prefer to not have *any* formal parameters,
456 // but the language forces you to have at least one.
457 unsigned NullPos = Attr->getNullPos();
458 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
459 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
460
461 // The number of arguments which should follow the sentinel.
462 unsigned NumArgsAfterSentinel = Attr->getSentinel();
463
464 // If there aren't enough arguments for all the formal parameters,
465 // the sentinel, and the args after the sentinel, complain.
466 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
467 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
468 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
469 return;
470 }
471
472 // Otherwise, find the sentinel expression.
473 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
474 if (!SentinelExpr)
475 return;
476 if (SentinelExpr->isValueDependent())
477 return;
478 if (Context.isSentinelNullExpr(SentinelExpr))
479 return;
480
481 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
482 // or 'NULL' if those are actually defined in the context. Only use
483 // 'nil' for ObjC methods, where it's much more likely that the
484 // variadic arguments form a list of object pointers.
485 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
486 std::string NullValue;
487 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
488 NullValue = "nil";
489 else if (getLangOpts().CPlusPlus11)
490 NullValue = "nullptr";
491 else if (PP.isMacroDefined("NULL"))
492 NullValue = "NULL";
493 else
494 NullValue = "(void*) 0";
495
496 if (MissingNilLoc.isInvalid())
497 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
498 else
499 Diag(MissingNilLoc, diag::warn_missing_sentinel)
500 << int(CalleeKind)
501 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
502 Diag(D->getLocation(), diag::note_sentinel_here)
503 << int(CalleeKind) << Attr->getRange();
504}
505
507 return E ? E->getSourceRange() : SourceRange();
508}
509
510//===----------------------------------------------------------------------===//
511// Standard Promotions and Conversions
512//===----------------------------------------------------------------------===//
513
514/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
516 // Handle any placeholder expressions which made it here.
517 if (E->hasPlaceholderType()) {
519 if (result.isInvalid()) return ExprError();
520 E = result.get();
521 }
522
523 QualType Ty = E->getType();
524 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
525
526 if (Ty->isFunctionType()) {
527 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
528 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
530 return ExprError();
531
532 E = ImpCastExprToType(E, Context.getPointerType(Ty),
533 CK_FunctionToPointerDecay).get();
534 } else if (Ty->isArrayType()) {
535 // In C90 mode, arrays only promote to pointers if the array expression is
536 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
537 // type 'array of type' is converted to an expression that has type 'pointer
538 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
539 // that has type 'array of type' ...". The relevant change is "an lvalue"
540 // (C90) to "an expression" (C99).
541 //
542 // C++ 4.2p1:
543 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
544 // T" can be converted to an rvalue of type "pointer to T".
545 //
546 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
547 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
548 CK_ArrayToPointerDecay);
549 if (Res.isInvalid())
550 return ExprError();
551 E = Res.get();
552 }
553 }
554 return E;
555}
556
558 // Check to see if we are dereferencing a null pointer. If so,
559 // and if not volatile-qualified, this is undefined behavior that the
560 // optimizer will delete, so warn about it. People sometimes try to use this
561 // to get a deterministic trap and are surprised by clang's behavior. This
562 // only handles the pattern "*null", which is a very syntactic check.
563 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
564 if (UO && UO->getOpcode() == UO_Deref &&
565 UO->getSubExpr()->getType()->isPointerType()) {
566 const LangAS AS =
567 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
568 if ((!isTargetAddressSpace(AS) ||
569 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
570 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
572 !UO->getType().isVolatileQualified()) {
573 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
574 S.PDiag(diag::warn_indirection_through_null)
575 << UO->getSubExpr()->getSourceRange());
576 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
577 S.PDiag(diag::note_indirection_through_null));
578 }
579 }
580}
581
582static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
583 SourceLocation AssignLoc,
584 const Expr* RHS) {
585 const ObjCIvarDecl *IV = OIRE->getDecl();
586 if (!IV)
587 return;
588
589 DeclarationName MemberName = IV->getDeclName();
591 if (!Member || !Member->isStr("isa"))
592 return;
593
594 const Expr *Base = OIRE->getBase();
595 QualType BaseType = Base->getType();
596 if (OIRE->isArrow())
597 BaseType = BaseType->getPointeeType();
598 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
599 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
600 ObjCInterfaceDecl *ClassDeclared = nullptr;
601 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
602 if (!ClassDeclared->getSuperClass()
603 && (*ClassDeclared->ivar_begin()) == IV) {
604 if (RHS) {
605 NamedDecl *ObjectSetClass =
607 &S.Context.Idents.get("object_setClass"),
609 if (ObjectSetClass) {
610 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
611 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
613 "object_setClass(")
615 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
616 << FixItHint::CreateInsertion(RHSLocEnd, ")");
617 }
618 else
619 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
620 } else {
621 NamedDecl *ObjectGetClass =
623 &S.Context.Idents.get("object_getClass"),
625 if (ObjectGetClass)
626 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
628 "object_getClass(")
630 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
631 else
632 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
633 }
634 S.Diag(IV->getLocation(), diag::note_ivar_decl);
635 }
636 }
637}
638
640 // Handle any placeholder expressions which made it here.
641 if (E->hasPlaceholderType()) {
643 if (result.isInvalid()) return ExprError();
644 E = result.get();
645 }
646
647 // C++ [conv.lval]p1:
648 // A glvalue of a non-function, non-array type T can be
649 // converted to a prvalue.
650 if (!E->isGLValue()) return E;
651
652 QualType T = E->getType();
653 assert(!T.isNull() && "r-value conversion on typeless expression?");
654
655 // lvalue-to-rvalue conversion cannot be applied to types that decay to
656 // pointers (i.e. function or array types).
657 if (T->canDecayToPointerType())
658 return E;
659
660 // We don't want to throw lvalue-to-rvalue casts on top of
661 // expressions of certain types in C++.
662 if (getLangOpts().CPlusPlus) {
663 if (T == Context.OverloadTy || T->isRecordType() ||
664 (T->isDependentType() && !T->isAnyPointerType() &&
665 !T->isMemberPointerType()))
666 return E;
667 }
668
669 // The C standard is actually really unclear on this point, and
670 // DR106 tells us what the result should be but not why. It's
671 // generally best to say that void types just doesn't undergo
672 // lvalue-to-rvalue at all. Note that expressions of unqualified
673 // 'void' type are never l-values, but qualified void can be.
674 if (T->isVoidType())
675 return E;
676
677 // OpenCL usually rejects direct accesses to values of 'half' type.
678 if (getLangOpts().OpenCL &&
679 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
680 T->isHalfType()) {
681 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
682 << 0 << T;
683 return ExprError();
684 }
685
687 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
688 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
689 &Context.Idents.get("object_getClass"),
691 if (ObjectGetClass)
692 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
693 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
695 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
696 else
697 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
698 }
699 else if (const ObjCIvarRefExpr *OIRE =
700 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
701 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
702
703 // C++ [conv.lval]p1:
704 // [...] If T is a non-class type, the type of the prvalue is the
705 // cv-unqualified version of T. Otherwise, the type of the
706 // rvalue is T.
707 //
708 // C99 6.3.2.1p2:
709 // If the lvalue has qualified type, the value has the unqualified
710 // version of the type of the lvalue; otherwise, the value has the
711 // type of the lvalue.
712 if (T.hasQualifiers())
713 T = T.getUnqualifiedType();
714
715 // Under the MS ABI, lock down the inheritance model now.
716 if (T->isMemberPointerType() &&
717 Context.getTargetInfo().getCXXABI().isMicrosoft())
718 (void)isCompleteType(E->getExprLoc(), T);
719
721 if (Res.isInvalid())
722 return Res;
723 E = Res.get();
724
725 // Loading a __weak object implicitly retains the value, so we need a cleanup to
726 // balance that.
728 Cleanup.setExprNeedsCleanups(true);
729
731 Cleanup.setExprNeedsCleanups(true);
732
734 return ExprError();
735
736 // C++ [conv.lval]p3:
737 // If T is cv std::nullptr_t, the result is a null pointer constant.
738 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
739 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
741
742 // C11 6.3.2.1p2:
743 // ... if the lvalue has atomic type, the value has the non-atomic version
744 // of the type of the lvalue ...
745 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
746 T = Atomic->getValueType().getUnqualifiedType();
747 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
748 nullptr, VK_PRValue, FPOptionsOverride());
749 }
750
751 return Res;
752}
753
756 if (Res.isInvalid())
757 return ExprError();
758 Res = DefaultLvalueConversion(Res.get());
759 if (Res.isInvalid())
760 return ExprError();
761 return Res;
762}
763
765 QualType Ty = E->getType();
766 ExprResult Res = E;
767 // Only do implicit cast for a function type, but not for a pointer
768 // to function type.
769 if (Ty->isFunctionType()) {
770 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
771 CK_FunctionToPointerDecay);
772 if (Res.isInvalid())
773 return ExprError();
774 }
775 Res = DefaultLvalueConversion(Res.get());
776 if (Res.isInvalid())
777 return ExprError();
778 return Res.get();
779}
780
781/// UsualUnaryFPConversions - Promotes floating-point types according to the
782/// current language semantics.
784 QualType Ty = E->getType();
785 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
786
787 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
788 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
789 (getLangOpts().getFPEvalMethod() !=
791 PP.getLastFPEvalPragmaLocation().isValid())) {
792 switch (EvalMethod) {
793 default:
794 llvm_unreachable("Unrecognized float evaluation method");
795 break;
797 llvm_unreachable("Float evaluation method should be set by now");
798 break;
800 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
801 // Widen the expression to double.
802 return Ty->isComplexType()
804 Context.getComplexType(Context.DoubleTy),
805 CK_FloatingComplexCast)
806 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
807 break;
809 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
810 // Widen the expression to long double.
811 return Ty->isComplexType()
813 E, Context.getComplexType(Context.LongDoubleTy),
814 CK_FloatingComplexCast)
815 : ImpCastExprToType(E, Context.LongDoubleTy,
816 CK_FloatingCast);
817 break;
818 }
819 }
820
821 // Half FP have to be promoted to float unless it is natively supported
822 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
823 return ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast);
824
825 return E;
826}
827
828/// UsualUnaryConversions - Performs various conversions that are common to most
829/// operators (C99 6.3). The conversions of array and function types are
830/// sometimes suppressed. For example, the array->pointer conversion doesn't
831/// apply if the array is an argument to the sizeof or address (&) operators.
832/// In these instances, this routine should *not* be called.
834 // First, convert to an r-value.
836 if (Res.isInvalid())
837 return ExprError();
838
839 // Promote floating-point types.
840 Res = UsualUnaryFPConversions(Res.get());
841 if (Res.isInvalid())
842 return ExprError();
843 E = Res.get();
844
845 QualType Ty = E->getType();
846 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
847
848 // Try to perform integral promotions if the object has a theoretically
849 // promotable type.
851 // C99 6.3.1.1p2:
852 //
853 // The following may be used in an expression wherever an int or
854 // unsigned int may be used:
855 // - an object or expression with an integer type whose integer
856 // conversion rank is less than or equal to the rank of int
857 // and unsigned int.
858 // - A bit-field of type _Bool, int, signed int, or unsigned int.
859 //
860 // If an int can represent all values of the original type, the
861 // value is converted to an int; otherwise, it is converted to an
862 // unsigned int. These are called the integer promotions. All
863 // other types are unchanged by the integer promotions.
864
865 QualType PTy = Context.isPromotableBitField(E);
866 if (!PTy.isNull()) {
867 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
868 return E;
869 }
870 if (Context.isPromotableIntegerType(Ty)) {
871 QualType PT = Context.getPromotedIntegerType(Ty);
872 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
873 return E;
874 }
875 }
876 return E;
877}
878
879/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
880/// do not have a prototype. Arguments that have type float or __fp16
881/// are promoted to double. All other argument types are converted by
882/// UsualUnaryConversions().
884 QualType Ty = E->getType();
885 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
886
888 if (Res.isInvalid())
889 return ExprError();
890 E = Res.get();
891
892 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
893 // promote to double.
894 // Note that default argument promotion applies only to float (and
895 // half/fp16); it does not apply to _Float16.
896 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
897 if (BTy && (BTy->getKind() == BuiltinType::Half ||
898 BTy->getKind() == BuiltinType::Float)) {
899 if (getLangOpts().OpenCL &&
900 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
901 if (BTy->getKind() == BuiltinType::Half) {
902 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
903 }
904 } else {
905 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
906 }
907 }
908 if (BTy &&
909 getLangOpts().getExtendIntArgs() ==
911 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
912 Context.getTypeSizeInChars(BTy) <
913 Context.getTypeSizeInChars(Context.LongLongTy)) {
914 E = (Ty->isUnsignedIntegerType())
915 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
916 .get()
917 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
918 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
919 "Unexpected typesize for LongLongTy");
920 }
921
922 // C++ performs lvalue-to-rvalue conversion as a default argument
923 // promotion, even on class types, but note:
924 // C++11 [conv.lval]p2:
925 // When an lvalue-to-rvalue conversion occurs in an unevaluated
926 // operand or a subexpression thereof the value contained in the
927 // referenced object is not accessed. Otherwise, if the glvalue
928 // has a class type, the conversion copy-initializes a temporary
929 // of type T from the glvalue and the result of the conversion
930 // is a prvalue for the temporary.
931 // FIXME: add some way to gate this entire thing for correctness in
932 // potentially potentially evaluated contexts.
936 E->getExprLoc(), E);
937 if (Temp.isInvalid())
938 return ExprError();
939 E = Temp.get();
940 }
941
942 // C++ [expr.call]p7, per CWG722:
943 // An argument that has (possibly cv-qualified) type std::nullptr_t is
944 // converted to void* ([conv.ptr]).
945 // (This does not apply to C23 nullptr)
947 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
948
949 return E;
950}
951
953 if (Ty->isIncompleteType()) {
954 // C++11 [expr.call]p7:
955 // After these conversions, if the argument does not have arithmetic,
956 // enumeration, pointer, pointer to member, or class type, the program
957 // is ill-formed.
958 //
959 // Since we've already performed null pointer conversion, array-to-pointer
960 // decay and function-to-pointer decay, the only such type in C++ is cv
961 // void. This also handles initializer lists as variadic arguments.
962 if (Ty->isVoidType())
963 return VarArgKind::Invalid;
964
965 if (Ty->isObjCObjectType())
966 return VarArgKind::Invalid;
967 return VarArgKind::Valid;
968 }
969
971 return VarArgKind::Invalid;
972
973 if (Context.getTargetInfo().getTriple().isWasm() &&
975 return VarArgKind::Invalid;
976 }
977
978 if (Ty.isCXX98PODType(Context))
979 return VarArgKind::Valid;
980
981 // C++11 [expr.call]p7:
982 // Passing a potentially-evaluated argument of class type (Clause 9)
983 // having a non-trivial copy constructor, a non-trivial move constructor,
984 // or a non-trivial destructor, with no corresponding parameter,
985 // is conditionally-supported with implementation-defined semantics.
988 if (!Record->hasNonTrivialCopyConstructor() &&
989 !Record->hasNonTrivialMoveConstructor() &&
990 !Record->hasNonTrivialDestructor())
992
993 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
994 return VarArgKind::Valid;
995
996 if (Ty->isObjCObjectType())
997 return VarArgKind::Invalid;
998
999 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1000 return VarArgKind::Valid;
1001
1002 if (getLangOpts().MSVCCompat)
1004
1005 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1006 return VarArgKind::Valid;
1007
1008 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1009 // permitted to reject them. We should consider doing so.
1010 return VarArgKind::Undefined;
1011}
1012
1014 // Don't allow one to pass an Objective-C interface to a vararg.
1015 const QualType &Ty = E->getType();
1016 VarArgKind VAK = isValidVarArgType(Ty);
1017
1018 // Complain about passing non-POD types through varargs.
1019 switch (VAK) {
1022 E->getBeginLoc(), nullptr,
1023 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1024 [[fallthrough]];
1025 case VarArgKind::Valid:
1026 if (Ty->isRecordType()) {
1027 // This is unlikely to be what the user intended. If the class has a
1028 // 'c_str' member function, the user probably meant to call that.
1029 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1030 PDiag(diag::warn_pass_class_arg_to_vararg)
1031 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1032 }
1033 break;
1034
1037 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1038 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1039 << getLangOpts().CPlusPlus11 << Ty << CT);
1040 break;
1041
1044 Diag(E->getBeginLoc(),
1045 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1046 << Ty << CT;
1047 else if (Ty->isObjCObjectType())
1048 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1049 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1050 << Ty << CT);
1051 else
1052 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1053 << isa<InitListExpr>(E) << Ty << CT;
1054 break;
1055 }
1056}
1057
1059 FunctionDecl *FDecl) {
1060 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1061 // Strip the unbridged-cast placeholder expression off, if applicable.
1062 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1063 (CT == VariadicCallType::Method ||
1064 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1065 E = ObjC().stripARCUnbridgedCast(E);
1066
1067 // Otherwise, do normal placeholder checking.
1068 } else {
1069 ExprResult ExprRes = CheckPlaceholderExpr(E);
1070 if (ExprRes.isInvalid())
1071 return ExprError();
1072 E = ExprRes.get();
1073 }
1074 }
1075
1077 if (ExprRes.isInvalid())
1078 return ExprError();
1079
1080 // Copy blocks to the heap.
1081 if (ExprRes.get()->getType()->isBlockPointerType())
1082 maybeExtendBlockObject(ExprRes);
1083
1084 E = ExprRes.get();
1085
1086 // Diagnostics regarding non-POD argument types are
1087 // emitted along with format string checking in Sema::CheckFunctionCall().
1089 // Turn this into a trap.
1090 CXXScopeSpec SS;
1091 SourceLocation TemplateKWLoc;
1092 UnqualifiedId Name;
1093 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1094 E->getBeginLoc());
1095 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1096 /*HasTrailingLParen=*/true,
1097 /*IsAddressOfOperand=*/false);
1098 if (TrapFn.isInvalid())
1099 return ExprError();
1100
1101 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1102 E->getEndLoc());
1103 if (Call.isInvalid())
1104 return ExprError();
1105
1106 ExprResult Comma =
1107 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1108 if (Comma.isInvalid())
1109 return ExprError();
1110 return Comma.get();
1111 }
1112
1113 if (!getLangOpts().CPlusPlus &&
1115 diag::err_call_incomplete_argument))
1116 return ExprError();
1117
1118 return E;
1119}
1120
1121/// Convert complex integers to complex floats and real integers to
1122/// real floats as required for complex arithmetic. Helper function of
1123/// UsualArithmeticConversions()
1124///
1125/// \return false if the integer expression is an integer type and is
1126/// successfully converted to the (complex) float type.
1128 ExprResult &ComplexExpr,
1129 QualType IntTy,
1130 QualType ComplexTy,
1131 bool SkipCast) {
1132 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1133 if (SkipCast) return false;
1134 if (IntTy->isIntegerType()) {
1135 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1136 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1137 } else {
1138 assert(IntTy->isComplexIntegerType());
1139 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1140 CK_IntegralComplexToFloatingComplex);
1141 }
1142 return false;
1143}
1144
1145// This handles complex/complex, complex/float, or float/complex.
1146// When both operands are complex, the shorter operand is converted to the
1147// type of the longer, and that is the type of the result. This corresponds
1148// to what is done when combining two real floating-point operands.
1149// The fun begins when size promotion occur across type domains.
1150// From H&S 6.3.4: When one operand is complex and the other is a real
1151// floating-point type, the less precise type is converted, within it's
1152// real or complex domain, to the precision of the other type. For example,
1153// when combining a "long double" with a "double _Complex", the
1154// "double _Complex" is promoted to "long double _Complex".
1156 QualType ShorterType,
1157 QualType LongerType,
1158 bool PromotePrecision) {
1159 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1160 QualType Result =
1161 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1162
1163 if (PromotePrecision) {
1164 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1165 Shorter =
1166 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1167 } else {
1168 if (LongerIsComplex)
1169 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1170 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1171 }
1172 }
1173 return Result;
1174}
1175
1176/// Handle arithmetic conversion with complex types. Helper function of
1177/// UsualArithmeticConversions()
1179 ExprResult &RHS, QualType LHSType,
1180 QualType RHSType, bool IsCompAssign) {
1181 // Handle (complex) integer types.
1182 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1183 /*SkipCast=*/false))
1184 return LHSType;
1185 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1186 /*SkipCast=*/IsCompAssign))
1187 return RHSType;
1188
1189 // Compute the rank of the two types, regardless of whether they are complex.
1190 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1191 if (Order < 0)
1192 // Promote the precision of the LHS if not an assignment.
1193 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1194 /*PromotePrecision=*/!IsCompAssign);
1195 // Promote the precision of the RHS unless it is already the same as the LHS.
1196 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1197 /*PromotePrecision=*/Order > 0);
1198}
1199
1200/// Handle arithmetic conversion from integer to float. Helper function
1201/// of UsualArithmeticConversions()
1203 ExprResult &IntExpr,
1204 QualType FloatTy, QualType IntTy,
1205 bool ConvertFloat, bool ConvertInt) {
1206 if (IntTy->isIntegerType()) {
1207 if (ConvertInt)
1208 // Convert intExpr to the lhs floating point type.
1209 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1210 CK_IntegralToFloating);
1211 return FloatTy;
1212 }
1213
1214 // Convert both sides to the appropriate complex float.
1215 assert(IntTy->isComplexIntegerType());
1216 QualType result = S.Context.getComplexType(FloatTy);
1217
1218 // _Complex int -> _Complex float
1219 if (ConvertInt)
1220 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1221 CK_IntegralComplexToFloatingComplex);
1222
1223 // float -> _Complex float
1224 if (ConvertFloat)
1225 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1226 CK_FloatingRealToComplex);
1227
1228 return result;
1229}
1230
1231/// Handle arithmethic conversion with floating point types. Helper
1232/// function of UsualArithmeticConversions()
1234 ExprResult &RHS, QualType LHSType,
1235 QualType RHSType, bool IsCompAssign) {
1236 bool LHSFloat = LHSType->isRealFloatingType();
1237 bool RHSFloat = RHSType->isRealFloatingType();
1238
1239 // N1169 4.1.4: If one of the operands has a floating type and the other
1240 // operand has a fixed-point type, the fixed-point operand
1241 // is converted to the floating type [...]
1242 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1243 if (LHSFloat)
1244 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1245 else if (!IsCompAssign)
1246 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1247 return LHSFloat ? LHSType : RHSType;
1248 }
1249
1250 // If we have two real floating types, convert the smaller operand
1251 // to the bigger result.
1252 if (LHSFloat && RHSFloat) {
1253 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1254 if (order > 0) {
1255 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1256 return LHSType;
1257 }
1258
1259 assert(order < 0 && "illegal float comparison");
1260 if (!IsCompAssign)
1261 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1262 return RHSType;
1263 }
1264
1265 if (LHSFloat) {
1266 // Half FP has to be promoted to float unless it is natively supported
1267 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1268 LHSType = S.Context.FloatTy;
1269
1270 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1271 /*ConvertFloat=*/!IsCompAssign,
1272 /*ConvertInt=*/ true);
1273 }
1274 assert(RHSFloat);
1275 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1276 /*ConvertFloat=*/ true,
1277 /*ConvertInt=*/!IsCompAssign);
1278}
1279
1280/// Diagnose attempts to convert between __float128, __ibm128 and
1281/// long double if there is no support for such conversion.
1282/// Helper function of UsualArithmeticConversions().
1283static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1284 QualType RHSType) {
1285 // No issue if either is not a floating point type.
1286 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1287 return false;
1288
1289 // No issue if both have the same 128-bit float semantics.
1290 auto *LHSComplex = LHSType->getAs<ComplexType>();
1291 auto *RHSComplex = RHSType->getAs<ComplexType>();
1292
1293 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1294 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1295
1296 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1297 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1298
1299 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1300 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1301 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1302 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1303 return false;
1304
1305 return true;
1306}
1307
1308typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1309
1310namespace {
1311/// These helper callbacks are placed in an anonymous namespace to
1312/// permit their use as function template parameters.
1313ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1314 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1315}
1316
1317ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1318 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1319 CK_IntegralComplexCast);
1320}
1321}
1322
1323/// Handle integer arithmetic conversions. Helper function of
1324/// UsualArithmeticConversions()
1325template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1327 ExprResult &RHS, QualType LHSType,
1328 QualType RHSType, bool IsCompAssign) {
1329 // The rules for this case are in C99 6.3.1.8
1330 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1331 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1332 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1333 if (LHSSigned == RHSSigned) {
1334 // Same signedness; use the higher-ranked type
1335 if (order >= 0) {
1336 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1337 return LHSType;
1338 } else if (!IsCompAssign)
1339 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1340 return RHSType;
1341 } else if (order != (LHSSigned ? 1 : -1)) {
1342 // The unsigned type has greater than or equal rank to the
1343 // signed type, so use the unsigned type
1344 if (RHSSigned) {
1345 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1346 return LHSType;
1347 } else if (!IsCompAssign)
1348 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1349 return RHSType;
1350 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1351 // The two types are different widths; if we are here, that
1352 // means the signed type is larger than the unsigned type, so
1353 // use the signed type.
1354 if (LHSSigned) {
1355 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1356 return LHSType;
1357 } else if (!IsCompAssign)
1358 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1359 return RHSType;
1360 } else {
1361 // The signed type is higher-ranked than the unsigned type,
1362 // but isn't actually any bigger (like unsigned int and long
1363 // on most 32-bit systems). Use the unsigned type corresponding
1364 // to the signed type.
1365 QualType result =
1366 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1367 RHS = (*doRHSCast)(S, RHS.get(), result);
1368 if (!IsCompAssign)
1369 LHS = (*doLHSCast)(S, LHS.get(), result);
1370 return result;
1371 }
1372}
1373
1374/// Handle conversions with GCC complex int extension. Helper function
1375/// of UsualArithmeticConversions()
1377 ExprResult &RHS, QualType LHSType,
1378 QualType RHSType,
1379 bool IsCompAssign) {
1380 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1381 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1382
1383 if (LHSComplexInt && RHSComplexInt) {
1384 QualType LHSEltType = LHSComplexInt->getElementType();
1385 QualType RHSEltType = RHSComplexInt->getElementType();
1386 QualType ScalarType =
1388 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1389
1390 return S.Context.getComplexType(ScalarType);
1391 }
1392
1393 if (LHSComplexInt) {
1394 QualType LHSEltType = LHSComplexInt->getElementType();
1395 QualType ScalarType =
1397 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1399 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1400 CK_IntegralRealToComplex);
1401
1402 return ComplexType;
1403 }
1404
1405 assert(RHSComplexInt);
1406
1407 QualType RHSEltType = RHSComplexInt->getElementType();
1408 QualType ScalarType =
1410 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1412
1413 if (!IsCompAssign)
1414 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1415 CK_IntegralRealToComplex);
1416 return ComplexType;
1417}
1418
1419/// Return the rank of a given fixed point or integer type. The value itself
1420/// doesn't matter, but the values must be increasing with proper increasing
1421/// rank as described in N1169 4.1.1.
1422static unsigned GetFixedPointRank(QualType Ty) {
1423 const auto *BTy = Ty->getAs<BuiltinType>();
1424 assert(BTy && "Expected a builtin type.");
1425
1426 switch (BTy->getKind()) {
1427 case BuiltinType::ShortFract:
1428 case BuiltinType::UShortFract:
1429 case BuiltinType::SatShortFract:
1430 case BuiltinType::SatUShortFract:
1431 return 1;
1432 case BuiltinType::Fract:
1433 case BuiltinType::UFract:
1434 case BuiltinType::SatFract:
1435 case BuiltinType::SatUFract:
1436 return 2;
1437 case BuiltinType::LongFract:
1438 case BuiltinType::ULongFract:
1439 case BuiltinType::SatLongFract:
1440 case BuiltinType::SatULongFract:
1441 return 3;
1442 case BuiltinType::ShortAccum:
1443 case BuiltinType::UShortAccum:
1444 case BuiltinType::SatShortAccum:
1445 case BuiltinType::SatUShortAccum:
1446 return 4;
1447 case BuiltinType::Accum:
1448 case BuiltinType::UAccum:
1449 case BuiltinType::SatAccum:
1450 case BuiltinType::SatUAccum:
1451 return 5;
1452 case BuiltinType::LongAccum:
1453 case BuiltinType::ULongAccum:
1454 case BuiltinType::SatLongAccum:
1455 case BuiltinType::SatULongAccum:
1456 return 6;
1457 default:
1458 if (BTy->isInteger())
1459 return 0;
1460 llvm_unreachable("Unexpected fixed point or integer type");
1461 }
1462}
1463
1464/// handleFixedPointConversion - Fixed point operations between fixed
1465/// point types and integers or other fixed point types do not fall under
1466/// usual arithmetic conversion since these conversions could result in loss
1467/// of precsision (N1169 4.1.4). These operations should be calculated with
1468/// the full precision of their result type (N1169 4.1.6.2.1).
1470 QualType RHSTy) {
1471 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1472 "Expected at least one of the operands to be a fixed point type");
1473 assert((LHSTy->isFixedPointOrIntegerType() ||
1474 RHSTy->isFixedPointOrIntegerType()) &&
1475 "Special fixed point arithmetic operation conversions are only "
1476 "applied to ints or other fixed point types");
1477
1478 // If one operand has signed fixed-point type and the other operand has
1479 // unsigned fixed-point type, then the unsigned fixed-point operand is
1480 // converted to its corresponding signed fixed-point type and the resulting
1481 // type is the type of the converted operand.
1482 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1484 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1486
1487 // The result type is the type with the highest rank, whereby a fixed-point
1488 // conversion rank is always greater than an integer conversion rank; if the
1489 // type of either of the operands is a saturating fixedpoint type, the result
1490 // type shall be the saturating fixed-point type corresponding to the type
1491 // with the highest rank; the resulting value is converted (taking into
1492 // account rounding and overflow) to the precision of the resulting type.
1493 // Same ranks between signed and unsigned types are resolved earlier, so both
1494 // types are either signed or both unsigned at this point.
1495 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1496 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1497
1498 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1499
1501 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1502
1503 return ResultTy;
1504}
1505
1506/// Check that the usual arithmetic conversions can be performed on this pair of
1507/// expressions that might be of enumeration type.
1509 SourceLocation Loc,
1510 ArithConvKind ACK) {
1511 // C++2a [expr.arith.conv]p1:
1512 // If one operand is of enumeration type and the other operand is of a
1513 // different enumeration type or a floating-point type, this behavior is
1514 // deprecated ([depr.arith.conv.enum]).
1515 //
1516 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1517 // Eventually we will presumably reject these cases (in C++23 onwards?).
1519 R = RHS->getEnumCoercedType(Context);
1520 bool LEnum = L->isUnscopedEnumerationType(),
1521 REnum = R->isUnscopedEnumerationType();
1522 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1523 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1524 (REnum && L->isFloatingType())) {
1525 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1527 ? diag::warn_arith_conv_enum_float_cxx20
1528 : diag::warn_arith_conv_enum_float)
1529 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1530 << L << R;
1531 } else if (!IsCompAssign && LEnum && REnum &&
1532 !Context.hasSameUnqualifiedType(L, R)) {
1533 unsigned DiagID;
1534 // In C++ 26, usual arithmetic conversions between 2 different enum types
1535 // are ill-formed.
1537 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1538 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1539 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1540 // If either enumeration type is unnamed, it's less likely that the
1541 // user cares about this, but this situation is still deprecated in
1542 // C++2a. Use a different warning group.
1543 DiagID = getLangOpts().CPlusPlus20
1544 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1545 : diag::warn_arith_conv_mixed_anon_enum_types;
1546 } else if (ACK == ArithConvKind::Conditional) {
1547 // Conditional expressions are separated out because they have
1548 // historically had a different warning flag.
1549 DiagID = getLangOpts().CPlusPlus20
1550 ? diag::warn_conditional_mixed_enum_types_cxx20
1551 : diag::warn_conditional_mixed_enum_types;
1552 } else if (ACK == ArithConvKind::Comparison) {
1553 // Comparison expressions are separated out because they have
1554 // historically had a different warning flag.
1555 DiagID = getLangOpts().CPlusPlus20
1556 ? diag::warn_comparison_mixed_enum_types_cxx20
1557 : diag::warn_comparison_mixed_enum_types;
1558 } else {
1559 DiagID = getLangOpts().CPlusPlus20
1560 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1561 : diag::warn_arith_conv_mixed_enum_types;
1562 }
1563 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1564 << (int)ACK << L << R;
1565 }
1566}
1567
1569 Expr *RHS, SourceLocation Loc,
1570 ArithConvKind ACK) {
1571 QualType LHSType = LHS->getType().getUnqualifiedType();
1572 QualType RHSType = RHS->getType().getUnqualifiedType();
1573
1574 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1575 !RHSType->isUnicodeCharacterType())
1576 return;
1577
1578 if (ACK == ArithConvKind::Comparison) {
1579 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1580 return;
1581
1582 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1583 if (T->isChar8Type())
1584 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1585 if (T->isChar16Type())
1586 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1587 assert(T->isChar32Type());
1588 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1589 };
1590
1591 Expr::EvalResult LHSRes, RHSRes;
1592 bool LHSSuccess = LHS->EvaluateAsInt(LHSRes, SemaRef.getASTContext(),
1594 SemaRef.isConstantEvaluatedContext());
1595 bool RHSuccess = RHS->EvaluateAsInt(RHSRes, SemaRef.getASTContext(),
1597 SemaRef.isConstantEvaluatedContext());
1598
1599 // Don't warn if the one known value is a representable
1600 // in the type of both expressions.
1601 if (LHSSuccess != RHSuccess) {
1602 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1603 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1604 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1605 return;
1606 }
1607
1608 if (!LHSSuccess || !RHSuccess) {
1609 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types)
1610 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1611 << RHSType;
1612 return;
1613 }
1614
1615 llvm::APSInt LHSValue(32);
1616 LHSValue = LHSRes.Val.getInt();
1617 llvm::APSInt RHSValue(32);
1618 RHSValue = RHSRes.Val.getInt();
1619
1620 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1621 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1622 if (LHSSafe && RHSSafe)
1623 return;
1624
1625 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types_constant)
1626 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1627 << FormatUTFCodeUnitAsCodepoint(LHSValue.getExtValue(), LHSType)
1628 << FormatUTFCodeUnitAsCodepoint(RHSValue.getExtValue(), RHSType);
1629 return;
1630 }
1631
1632 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1633 return;
1634
1635 SemaRef.Diag(Loc, diag::warn_arith_conv_mixed_unicode_types)
1636 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1637 << RHSType;
1638}
1639
1640/// UsualArithmeticConversions - Performs various conversions that are common to
1641/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1642/// routine returns the first non-arithmetic type found. The client is
1643/// responsible for emitting appropriate error diagnostics.
1645 SourceLocation Loc,
1646 ArithConvKind ACK) {
1647
1648 checkEnumArithmeticConversions(LHS.get(), RHS.get(), Loc, ACK);
1649
1650 CheckUnicodeArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1651
1652 if (ACK != ArithConvKind::CompAssign) {
1653 LHS = UsualUnaryConversions(LHS.get());
1654 if (LHS.isInvalid())
1655 return QualType();
1656 }
1657
1658 RHS = UsualUnaryConversions(RHS.get());
1659 if (RHS.isInvalid())
1660 return QualType();
1661
1662 // For conversion purposes, we ignore any qualifiers.
1663 // For example, "const float" and "float" are equivalent.
1664 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1665 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1666
1667 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1668 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1669 LHSType = AtomicLHS->getValueType();
1670
1671 // If both types are identical, no conversion is needed.
1672 if (Context.hasSameType(LHSType, RHSType))
1673 return Context.getCommonSugaredType(LHSType, RHSType);
1674
1675 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1676 // The caller can deal with this (e.g. pointer + int).
1677 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1678 return QualType();
1679
1680 // Apply unary and bitfield promotions to the LHS's type.
1681 QualType LHSUnpromotedType = LHSType;
1682 if (Context.isPromotableIntegerType(LHSType))
1683 LHSType = Context.getPromotedIntegerType(LHSType);
1684 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1685 if (!LHSBitfieldPromoteTy.isNull())
1686 LHSType = LHSBitfieldPromoteTy;
1687 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1688 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1689
1690 // If both types are identical, no conversion is needed.
1691 if (Context.hasSameType(LHSType, RHSType))
1692 return Context.getCommonSugaredType(LHSType, RHSType);
1693
1694 // At this point, we have two different arithmetic types.
1695
1696 // Diagnose attempts to convert between __ibm128, __float128 and long double
1697 // where such conversions currently can't be handled.
1698 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1699 return QualType();
1700
1701 // Handle complex types first (C99 6.3.1.8p1).
1702 if (LHSType->isComplexType() || RHSType->isComplexType())
1703 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1705
1706 // Now handle "real" floating types (i.e. float, double, long double).
1707 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1708 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1710
1711 // Handle GCC complex int extension.
1712 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1713 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1715
1716 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1717 return handleFixedPointConversion(*this, LHSType, RHSType);
1718
1719 // Finally, we have two differing integer types.
1721 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1722}
1723
1724//===----------------------------------------------------------------------===//
1725// Semantic Analysis for various Expression Types
1726//===----------------------------------------------------------------------===//
1727
1728
1730 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1731 bool PredicateIsExpr, void *ControllingExprOrType,
1732 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1733 unsigned NumAssocs = ArgTypes.size();
1734 assert(NumAssocs == ArgExprs.size());
1735
1736 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1737 for (unsigned i = 0; i < NumAssocs; ++i) {
1738 if (ArgTypes[i])
1739 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1740 else
1741 Types[i] = nullptr;
1742 }
1743
1744 // If we have a controlling type, we need to convert it from a parsed type
1745 // into a semantic type and then pass that along.
1746 if (!PredicateIsExpr) {
1747 TypeSourceInfo *ControllingType;
1748 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1749 &ControllingType);
1750 assert(ControllingType && "couldn't get the type out of the parser");
1751 ControllingExprOrType = ControllingType;
1752 }
1753
1755 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1756 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1757 delete [] Types;
1758 return ER;
1759}
1760
1762 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1763 bool PredicateIsExpr, void *ControllingExprOrType,
1765 unsigned NumAssocs = Types.size();
1766 assert(NumAssocs == Exprs.size());
1767 assert(ControllingExprOrType &&
1768 "Must have either a controlling expression or a controlling type");
1769
1770 Expr *ControllingExpr = nullptr;
1771 TypeSourceInfo *ControllingType = nullptr;
1772 if (PredicateIsExpr) {
1773 // Decay and strip qualifiers for the controlling expression type, and
1774 // handle placeholder type replacement. See committee discussion from WG14
1775 // DR423.
1779 reinterpret_cast<Expr *>(ControllingExprOrType));
1780 if (R.isInvalid())
1781 return ExprError();
1782 ControllingExpr = R.get();
1783 } else {
1784 // The extension form uses the type directly rather than converting it.
1785 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1786 if (!ControllingType)
1787 return ExprError();
1788 }
1789
1790 bool TypeErrorFound = false,
1791 IsResultDependent = ControllingExpr
1792 ? ControllingExpr->isTypeDependent()
1793 : ControllingType->getType()->isDependentType(),
1794 ContainsUnexpandedParameterPack =
1795 ControllingExpr
1796 ? ControllingExpr->containsUnexpandedParameterPack()
1797 : ControllingType->getType()->containsUnexpandedParameterPack();
1798
1799 // The controlling expression is an unevaluated operand, so side effects are
1800 // likely unintended.
1801 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1802 ControllingExpr->HasSideEffects(Context, false))
1803 Diag(ControllingExpr->getExprLoc(),
1804 diag::warn_side_effects_unevaluated_context);
1805
1806 for (unsigned i = 0; i < NumAssocs; ++i) {
1807 if (Exprs[i]->containsUnexpandedParameterPack())
1808 ContainsUnexpandedParameterPack = true;
1809
1810 if (Types[i]) {
1811 if (Types[i]->getType()->containsUnexpandedParameterPack())
1812 ContainsUnexpandedParameterPack = true;
1813
1814 if (Types[i]->getType()->isDependentType()) {
1815 IsResultDependent = true;
1816 } else {
1817 // We relax the restriction on use of incomplete types and non-object
1818 // types with the type-based extension of _Generic. Allowing incomplete
1819 // objects means those can be used as "tags" for a type-safe way to map
1820 // to a value. Similarly, matching on function types rather than
1821 // function pointer types can be useful. However, the restriction on VM
1822 // types makes sense to retain as there are open questions about how
1823 // the selection can be made at compile time.
1824 //
1825 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1826 // complete object type other than a variably modified type."
1827 // C2y removed the requirement that an expression form must
1828 // use a complete type, though it's still as-if the type has undergone
1829 // lvalue conversion. We support this as an extension in C23 and
1830 // earlier because GCC does so.
1831 unsigned D = 0;
1832 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1833 D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete
1834 : diag::ext_assoc_type_incomplete;
1835 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1836 D = diag::err_assoc_type_nonobject;
1837 else if (Types[i]->getType()->isVariablyModifiedType())
1838 D = diag::err_assoc_type_variably_modified;
1839 else if (ControllingExpr) {
1840 // Because the controlling expression undergoes lvalue conversion,
1841 // array conversion, and function conversion, an association which is
1842 // of array type, function type, or is qualified can never be
1843 // reached. We will warn about this so users are less surprised by
1844 // the unreachable association. However, we don't have to handle
1845 // function types; that's not an object type, so it's handled above.
1846 //
1847 // The logic is somewhat different for C++ because C++ has different
1848 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1849 // If T is a non-class type, the type of the prvalue is the cv-
1850 // unqualified version of T. Otherwise, the type of the prvalue is T.
1851 // The result of these rules is that all qualified types in an
1852 // association in C are unreachable, and in C++, only qualified non-
1853 // class types are unreachable.
1854 //
1855 // NB: this does not apply when the first operand is a type rather
1856 // than an expression, because the type form does not undergo
1857 // conversion.
1858 unsigned Reason = 0;
1859 QualType QT = Types[i]->getType();
1860 if (QT->isArrayType())
1861 Reason = 1;
1862 else if (QT.hasQualifiers() &&
1863 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1864 Reason = 2;
1865
1866 if (Reason)
1867 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1868 diag::warn_unreachable_association)
1869 << QT << (Reason - 1);
1870 }
1871
1872 if (D != 0) {
1873 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1874 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1875 if (getDiagnostics().getDiagnosticLevel(
1876 D, Types[i]->getTypeLoc().getBeginLoc()) >=
1878 TypeErrorFound = true;
1879 }
1880
1881 // C11 6.5.1.1p2 "No two generic associations in the same generic
1882 // selection shall specify compatible types."
1883 for (unsigned j = i+1; j < NumAssocs; ++j)
1884 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1885 Context.typesAreCompatible(Types[i]->getType(),
1886 Types[j]->getType())) {
1887 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1888 diag::err_assoc_compatible_types)
1889 << Types[j]->getTypeLoc().getSourceRange()
1890 << Types[j]->getType()
1891 << Types[i]->getType();
1892 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1893 diag::note_compat_assoc)
1894 << Types[i]->getTypeLoc().getSourceRange()
1895 << Types[i]->getType();
1896 TypeErrorFound = true;
1897 }
1898 }
1899 }
1900 }
1901 if (TypeErrorFound)
1902 return ExprError();
1903
1904 // If we determined that the generic selection is result-dependent, don't
1905 // try to compute the result expression.
1906 if (IsResultDependent) {
1907 if (ControllingExpr)
1908 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1909 Types, Exprs, DefaultLoc, RParenLoc,
1910 ContainsUnexpandedParameterPack);
1911 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1912 Exprs, DefaultLoc, RParenLoc,
1913 ContainsUnexpandedParameterPack);
1914 }
1915
1916 SmallVector<unsigned, 1> CompatIndices;
1917 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
1918 // Look at the canonical type of the controlling expression in case it was a
1919 // deduced type like __auto_type. However, when issuing diagnostics, use the
1920 // type the user wrote in source rather than the canonical one.
1921 for (unsigned i = 0; i < NumAssocs; ++i) {
1922 if (!Types[i])
1923 DefaultIndex = i;
1924 else if (ControllingExpr &&
1925 Context.typesAreCompatible(
1926 ControllingExpr->getType().getCanonicalType(),
1927 Types[i]->getType()))
1928 CompatIndices.push_back(i);
1929 else if (ControllingType &&
1930 Context.typesAreCompatible(
1931 ControllingType->getType().getCanonicalType(),
1932 Types[i]->getType()))
1933 CompatIndices.push_back(i);
1934 }
1935
1936 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1937 TypeSourceInfo *ControllingType) {
1938 // We strip parens here because the controlling expression is typically
1939 // parenthesized in macro definitions.
1940 if (ControllingExpr)
1941 ControllingExpr = ControllingExpr->IgnoreParens();
1942
1943 SourceRange SR = ControllingExpr
1944 ? ControllingExpr->getSourceRange()
1945 : ControllingType->getTypeLoc().getSourceRange();
1946 QualType QT = ControllingExpr ? ControllingExpr->getType()
1947 : ControllingType->getType();
1948
1949 return std::make_pair(SR, QT);
1950 };
1951
1952 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1953 // type compatible with at most one of the types named in its generic
1954 // association list."
1955 if (CompatIndices.size() > 1) {
1956 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1957 SourceRange SR = P.first;
1958 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1959 << SR << P.second << (unsigned)CompatIndices.size();
1960 for (unsigned I : CompatIndices) {
1961 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1962 diag::note_compat_assoc)
1963 << Types[I]->getTypeLoc().getSourceRange()
1964 << Types[I]->getType();
1965 }
1966 return ExprError();
1967 }
1968
1969 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1970 // its controlling expression shall have type compatible with exactly one of
1971 // the types named in its generic association list."
1972 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
1973 CompatIndices.size() == 0) {
1974 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1975 SourceRange SR = P.first;
1976 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1977 return ExprError();
1978 }
1979
1980 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1981 // type name that is compatible with the type of the controlling expression,
1982 // then the result expression of the generic selection is the expression
1983 // in that generic association. Otherwise, the result expression of the
1984 // generic selection is the expression in the default generic association."
1985 unsigned ResultIndex =
1986 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1987
1988 if (ControllingExpr) {
1990 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1991 ContainsUnexpandedParameterPack, ResultIndex);
1992 }
1994 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1995 ContainsUnexpandedParameterPack, ResultIndex);
1996}
1997
1999 switch (Kind) {
2000 default:
2001 llvm_unreachable("unexpected TokenKind");
2002 case tok::kw___func__:
2003 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2004 case tok::kw___FUNCTION__:
2006 case tok::kw___FUNCDNAME__:
2007 return PredefinedIdentKind::FuncDName; // [MS]
2008 case tok::kw___FUNCSIG__:
2009 return PredefinedIdentKind::FuncSig; // [MS]
2010 case tok::kw_L__FUNCTION__:
2011 return PredefinedIdentKind::LFunction; // [MS]
2012 case tok::kw_L__FUNCSIG__:
2013 return PredefinedIdentKind::LFuncSig; // [MS]
2014 case tok::kw___PRETTY_FUNCTION__:
2016 }
2017}
2018
2019/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2020/// to determine the value of a PredefinedExpr. This can be either a
2021/// block, lambda, captured statement, function, otherwise a nullptr.
2024 DC = DC->getParent();
2025 return cast_or_null<Decl>(DC);
2026}
2027
2028/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2029/// location of the token and the offset of the ud-suffix within it.
2031 unsigned Offset) {
2032 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
2033 S.getLangOpts());
2034}
2035
2036/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2037/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2039 IdentifierInfo *UDSuffix,
2040 SourceLocation UDSuffixLoc,
2041 ArrayRef<Expr*> Args,
2042 SourceLocation LitEndLoc) {
2043 assert(Args.size() <= 2 && "too many arguments for literal operator");
2044
2045 QualType ArgTy[2];
2046 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2047 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2048 if (ArgTy[ArgIdx]->isArrayType())
2049 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
2050 }
2051
2052 DeclarationName OpName =
2054 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2055 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2056
2057 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2058 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
2059 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2060 /*AllowStringTemplatePack*/ false,
2061 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2062 return ExprError();
2063
2064 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
2065}
2066
2068 // StringToks needs backing storage as it doesn't hold array elements itself
2069 std::vector<Token> ExpandedToks;
2070 if (getLangOpts().MicrosoftExt)
2071 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2072
2073 StringLiteralParser Literal(StringToks, PP,
2075 if (Literal.hadError)
2076 return ExprError();
2077
2078 SmallVector<SourceLocation, 4> StringTokLocs;
2079 for (const Token &Tok : StringToks)
2080 StringTokLocs.push_back(Tok.getLocation());
2081
2082 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2084 false, {}, StringTokLocs);
2085
2086 if (!Literal.getUDSuffix().empty()) {
2087 SourceLocation UDSuffixLoc =
2088 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2089 Literal.getUDSuffixOffset());
2090 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2091 }
2092
2093 return Lit;
2094}
2095
2096std::vector<Token>
2098 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2099 // local macros that expand to string literals that may be concatenated.
2100 // These macros are expanded here (in Sema), because StringLiteralParser
2101 // (in Lex) doesn't know the enclosing function (because it hasn't been
2102 // parsed yet).
2103 assert(getLangOpts().MicrosoftExt);
2104
2105 // Note: Although function local macros are defined only inside functions,
2106 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2107 // expansion of macros into empty string literals without additional checks.
2108 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2109 if (!CurrentDecl)
2110 CurrentDecl = Context.getTranslationUnitDecl();
2111
2112 std::vector<Token> ExpandedToks;
2113 ExpandedToks.reserve(Toks.size());
2114 for (const Token &Tok : Toks) {
2116 assert(tok::isStringLiteral(Tok.getKind()));
2117 ExpandedToks.emplace_back(Tok);
2118 continue;
2119 }
2120 if (isa<TranslationUnitDecl>(CurrentDecl))
2121 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2122 // Stringify predefined expression
2123 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2124 << Tok.getKind();
2125 SmallString<64> Str;
2126 llvm::raw_svector_ostream OS(Str);
2127 Token &Exp = ExpandedToks.emplace_back();
2128 Exp.startToken();
2129 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2130 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2131 OS << 'L';
2132 Exp.setKind(tok::wide_string_literal);
2133 } else {
2134 Exp.setKind(tok::string_literal);
2135 }
2136 OS << '"'
2138 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2139 << '"';
2140 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2141 }
2142 return ExpandedToks;
2143}
2144
2147 assert(!StringToks.empty() && "Must have at least one string!");
2148
2149 // StringToks needs backing storage as it doesn't hold array elements itself
2150 std::vector<Token> ExpandedToks;
2151 if (getLangOpts().MicrosoftExt)
2152 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2153
2154 StringLiteralParser Literal(StringToks, PP);
2155 if (Literal.hadError)
2156 return ExprError();
2157
2158 SmallVector<SourceLocation, 4> StringTokLocs;
2159 for (const Token &Tok : StringToks)
2160 StringTokLocs.push_back(Tok.getLocation());
2161
2162 QualType CharTy = Context.CharTy;
2164 if (Literal.isWide()) {
2165 CharTy = Context.getWideCharType();
2167 } else if (Literal.isUTF8()) {
2168 if (getLangOpts().Char8)
2169 CharTy = Context.Char8Ty;
2170 else if (getLangOpts().C23)
2171 CharTy = Context.UnsignedCharTy;
2173 } else if (Literal.isUTF16()) {
2174 CharTy = Context.Char16Ty;
2176 } else if (Literal.isUTF32()) {
2177 CharTy = Context.Char32Ty;
2179 } else if (Literal.isPascal()) {
2180 CharTy = Context.UnsignedCharTy;
2181 }
2182
2183 // Warn on u8 string literals before C++20 and C23, whose type
2184 // was an array of char before but becomes an array of char8_t.
2185 // In C++20, it cannot be used where a pointer to char is expected.
2186 // In C23, it might have an unexpected value if char was signed.
2187 if (Kind == StringLiteralKind::UTF8 &&
2189 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2190 : !getLangOpts().C23)) {
2191 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2192 ? diag::warn_cxx20_compat_utf8_string
2193 : diag::warn_c23_compat_utf8_string);
2194
2195 // Create removals for all 'u8' prefixes in the string literal(s). This
2196 // ensures C++20/C23 compatibility (but may change the program behavior when
2197 // built by non-Clang compilers for which the execution character set is
2198 // not always UTF-8).
2199 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2200 SourceLocation RemovalDiagLoc;
2201 for (const Token &Tok : StringToks) {
2202 if (Tok.getKind() == tok::utf8_string_literal) {
2203 if (RemovalDiagLoc.isInvalid())
2204 RemovalDiagLoc = Tok.getLocation();
2206 Tok.getLocation(),
2207 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2209 }
2210 }
2211 Diag(RemovalDiagLoc, RemovalDiag);
2212 }
2213
2214 QualType StrTy =
2215 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2216
2217 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2219 Context, Literal.GetString(), Kind, Literal.Pascal, StrTy, StringTokLocs);
2220 if (Literal.getUDSuffix().empty())
2221 return Lit;
2222
2223 // We're building a user-defined literal.
2224 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2225 SourceLocation UDSuffixLoc =
2226 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2227 Literal.getUDSuffixOffset());
2228
2229 // Make sure we're allowed user-defined literals here.
2230 if (!UDLScope)
2231 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2232
2233 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2234 // operator "" X (str, len)
2235 QualType SizeType = Context.getSizeType();
2236
2237 DeclarationName OpName =
2238 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2239 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2240 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2241
2242 QualType ArgTy[] = {
2243 Context.getArrayDecayedType(StrTy), SizeType
2244 };
2245
2246 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2247 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2248 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2249 /*AllowStringTemplatePack*/ true,
2250 /*DiagnoseMissing*/ true, Lit)) {
2251
2252 case LOLR_Cooked: {
2253 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2254 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2255 StringTokLocs[0]);
2256 Expr *Args[] = { Lit, LenArg };
2257
2258 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2259 }
2260
2261 case LOLR_Template: {
2262 TemplateArgumentListInfo ExplicitArgs;
2263 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2264 TemplateArgumentLocInfo ArgInfo(Lit);
2265 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2266 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2267 &ExplicitArgs);
2268 }
2269
2271 TemplateArgumentListInfo ExplicitArgs;
2272
2273 unsigned CharBits = Context.getIntWidth(CharTy);
2274 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2275 llvm::APSInt Value(CharBits, CharIsUnsigned);
2276
2277 TemplateArgument TypeArg(CharTy);
2278 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2279 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2280
2281 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2282 Value = Lit->getCodeUnit(I);
2283 TemplateArgument Arg(Context, Value, CharTy);
2285 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2286 }
2287 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2288 &ExplicitArgs);
2289 }
2290 case LOLR_Raw:
2292 llvm_unreachable("unexpected literal operator lookup result");
2293 case LOLR_Error:
2294 return ExprError();
2295 }
2296 llvm_unreachable("unexpected literal operator lookup result");
2297}
2298
2301 SourceLocation Loc,
2302 const CXXScopeSpec *SS) {
2303 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2304 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2305}
2306
2309 const DeclarationNameInfo &NameInfo,
2310 const CXXScopeSpec *SS, NamedDecl *FoundD,
2311 SourceLocation TemplateKWLoc,
2312 const TemplateArgumentListInfo *TemplateArgs) {
2315 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2316 TemplateArgs);
2317}
2318
2319// CUDA/HIP: Check whether a captured reference variable is referencing a
2320// host variable in a device or host device lambda.
2322 VarDecl *VD) {
2323 if (!S.getLangOpts().CUDA || !VD->hasInit())
2324 return false;
2325 assert(VD->getType()->isReferenceType());
2326
2327 // Check whether the reference variable is referencing a host variable.
2328 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2329 if (!DRE)
2330 return false;
2331 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2332 if (!Referee || !Referee->hasGlobalStorage() ||
2333 Referee->hasAttr<CUDADeviceAttr>())
2334 return false;
2335
2336 // Check whether the current function is a device or host device lambda.
2337 // Check whether the reference variable is a capture by getDeclContext()
2338 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2339 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2340 if (MD && MD->getParent()->isLambda() &&
2341 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2342 VD->getDeclContext() != MD)
2343 return true;
2344
2345 return false;
2346}
2347
2349 // A declaration named in an unevaluated operand never constitutes an odr-use.
2351 return NOUR_Unevaluated;
2352
2353 // C++2a [basic.def.odr]p4:
2354 // A variable x whose name appears as a potentially-evaluated expression e
2355 // is odr-used by e unless [...] x is a reference that is usable in
2356 // constant expressions.
2357 // CUDA/HIP:
2358 // If a reference variable referencing a host variable is captured in a
2359 // device or host device lambda, the value of the referee must be copied
2360 // to the capture and the reference variable must be treated as odr-use
2361 // since the value of the referee is not known at compile time and must
2362 // be loaded from the captured.
2363 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2364 if (VD->getType()->isReferenceType() &&
2365 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2367 VD->isUsableInConstantExpressions(Context))
2368 return NOUR_Constant;
2369 }
2370
2371 // All remaining non-variable cases constitute an odr-use. For variables, we
2372 // need to wait and see how the expression is used.
2373 return NOUR_None;
2374}
2375
2378 const DeclarationNameInfo &NameInfo,
2379 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2380 SourceLocation TemplateKWLoc,
2381 const TemplateArgumentListInfo *TemplateArgs) {
2382 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2383 NeedToCaptureVariable(D, NameInfo.getLoc());
2384
2386 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2387 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2389
2390 // C++ [except.spec]p17:
2391 // An exception-specification is considered to be needed when:
2392 // - in an expression, the function is the unique lookup result or
2393 // the selected member of a set of overloaded functions.
2394 //
2395 // We delay doing this until after we've built the function reference and
2396 // marked it as used so that:
2397 // a) if the function is defaulted, we get errors from defining it before /
2398 // instead of errors from computing its exception specification, and
2399 // b) if the function is a defaulted comparison, we can use the body we
2400 // build when defining it as input to the exception specification
2401 // computation rather than computing a new body.
2402 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2403 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2404 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2405 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2406 }
2407 }
2408
2409 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2411 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2413
2414 const auto *FD = dyn_cast<FieldDecl>(D);
2415 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2416 FD = IFD->getAnonField();
2417 if (FD) {
2418 UnusedPrivateFields.remove(FD);
2419 // Just in case we're building an illegal pointer-to-member.
2420 if (FD->isBitField())
2422 }
2423
2424 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2425 // designates a bit-field.
2426 if (const auto *BD = dyn_cast<BindingDecl>(D))
2427 if (const auto *BE = BD->getBinding())
2428 E->setObjectKind(BE->getObjectKind());
2429
2430 return E;
2431}
2432
2433void
2436 DeclarationNameInfo &NameInfo,
2437 const TemplateArgumentListInfo *&TemplateArgs) {
2439 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2440 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2441
2442 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2443 Id.TemplateId->NumArgs);
2444 translateTemplateArguments(TemplateArgsPtr, Buffer);
2445
2446 TemplateName TName = Id.TemplateId->Template.get();
2448 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2449 TemplateArgs = &Buffer;
2450 } else {
2451 NameInfo = GetNameFromUnqualifiedId(Id);
2452 TemplateArgs = nullptr;
2453 }
2454}
2455
2457 // During a default argument instantiation the CurContext points
2458 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2459 // function parameter list, hence add an explicit check.
2460 bool isDefaultArgument =
2461 !CodeSynthesisContexts.empty() &&
2462 CodeSynthesisContexts.back().Kind ==
2464 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2465 bool isInstance = CurMethod && CurMethod->isInstance() &&
2466 R.getNamingClass() == CurMethod->getParent() &&
2467 !isDefaultArgument;
2468
2469 // There are two ways we can find a class-scope declaration during template
2470 // instantiation that we did not find in the template definition: if it is a
2471 // member of a dependent base class, or if it is declared after the point of
2472 // use in the same class. Distinguish these by comparing the class in which
2473 // the member was found to the naming class of the lookup.
2474 unsigned DiagID = diag::err_found_in_dependent_base;
2475 unsigned NoteID = diag::note_member_declared_at;
2477 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2478 : diag::err_found_later_in_class;
2479 } else if (getLangOpts().MSVCCompat) {
2480 DiagID = diag::ext_found_in_dependent_base;
2481 NoteID = diag::note_dependent_member_use;
2482 }
2483
2484 if (isInstance) {
2485 // Give a code modification hint to insert 'this->'.
2486 Diag(R.getNameLoc(), DiagID)
2487 << R.getLookupName()
2488 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2490 } else {
2491 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2492 // they're not shadowed).
2493 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2494 }
2495
2496 for (const NamedDecl *D : R)
2497 Diag(D->getLocation(), NoteID);
2498
2499 // Return true if we are inside a default argument instantiation
2500 // and the found name refers to an instance member function, otherwise
2501 // the caller will try to create an implicit member call and this is wrong
2502 // for default arguments.
2503 //
2504 // FIXME: Is this special case necessary? We could allow the caller to
2505 // diagnose this.
2506 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2507 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2508 return true;
2509 }
2510
2511 // Tell the callee to try to recover.
2512 return false;
2513}
2514
2517 TemplateArgumentListInfo *ExplicitTemplateArgs,
2518 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2519 DeclarationName Name = R.getLookupName();
2521
2522 unsigned diagnostic = diag::err_undeclared_var_use;
2523 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2527 diagnostic = diag::err_undeclared_use;
2528 diagnostic_suggest = diag::err_undeclared_use_suggest;
2529 }
2530
2531 // If the original lookup was an unqualified lookup, fake an
2532 // unqualified lookup. This is useful when (for example) the
2533 // original lookup would not have found something because it was a
2534 // dependent name.
2535 DeclContext *DC =
2536 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2537 while (DC) {
2538 if (isa<CXXRecordDecl>(DC)) {
2539 if (ExplicitTemplateArgs) {
2541 R, S, SS, Context.getCanonicalTagType(cast<CXXRecordDecl>(DC)),
2542 /*EnteringContext*/ false, TemplateNameIsRequired,
2543 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2544 return true;
2545 } else {
2546 LookupQualifiedName(R, DC);
2547 }
2548
2549 if (!R.empty()) {
2550 // Don't give errors about ambiguities in this lookup.
2552
2553 // If there's a best viable function among the results, only mention
2554 // that one in the notes.
2555 OverloadCandidateSet Candidates(R.getNameLoc(),
2557 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2559 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2560 OR_Success) {
2561 R.clear();
2562 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2563 R.resolveKind();
2564 }
2565
2567 }
2568
2569 R.clear();
2570 }
2571
2572 DC = DC->getLookupParent();
2573 }
2574
2575 // We didn't find anything, so try to correct for a typo.
2576 TypoCorrection Corrected;
2577 if (S && (Corrected =
2579 CCC, CorrectTypoKind::ErrorRecovery, LookupCtx))) {
2580 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2581 bool DroppedSpecifier =
2582 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2583 R.setLookupName(Corrected.getCorrection());
2584
2585 bool AcceptableWithRecovery = false;
2586 bool AcceptableWithoutRecovery = false;
2587 NamedDecl *ND = Corrected.getFoundDecl();
2588 if (ND) {
2589 if (Corrected.isOverloaded()) {
2593 for (NamedDecl *CD : Corrected) {
2594 if (FunctionTemplateDecl *FTD =
2595 dyn_cast<FunctionTemplateDecl>(CD))
2597 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2598 Args, OCS);
2599 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2600 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2602 Args, OCS);
2603 }
2604 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2605 case OR_Success:
2606 ND = Best->FoundDecl;
2607 Corrected.setCorrectionDecl(ND);
2608 break;
2609 default:
2610 // FIXME: Arbitrarily pick the first declaration for the note.
2611 Corrected.setCorrectionDecl(ND);
2612 break;
2613 }
2614 }
2615 R.addDecl(ND);
2616 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2619 if (!Record)
2623 }
2624
2625 auto *UnderlyingND = ND->getUnderlyingDecl();
2626 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2627 isa<FunctionTemplateDecl>(UnderlyingND);
2628 // FIXME: If we ended up with a typo for a type name or
2629 // Objective-C class name, we're in trouble because the parser
2630 // is in the wrong place to recover. Suggest the typo
2631 // correction, but don't make it a fix-it since we're not going
2632 // to recover well anyway.
2633 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2634 getAsTypeTemplateDecl(UnderlyingND) ||
2635 isa<ObjCInterfaceDecl>(UnderlyingND);
2636 } else {
2637 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2638 // because we aren't able to recover.
2639 AcceptableWithoutRecovery = true;
2640 }
2641
2642 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2643 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2644 ? diag::note_implicit_param_decl
2645 : diag::note_previous_decl;
2646 if (SS.isEmpty())
2647 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name << NameRange,
2648 PDiag(NoteID), AcceptableWithRecovery);
2649 else
2650 diagnoseTypo(Corrected,
2651 PDiag(diag::err_no_member_suggest)
2652 << Name << computeDeclContext(SS, false)
2653 << DroppedSpecifier << NameRange,
2654 PDiag(NoteID), AcceptableWithRecovery);
2655
2656 // Tell the callee whether to try to recover.
2657 return !AcceptableWithRecovery;
2658 }
2659 }
2660 R.clear();
2661
2662 // Emit a special diagnostic for failed member lookups.
2663 // FIXME: computing the declaration context might fail here (?)
2664 if (!SS.isEmpty()) {
2665 Diag(R.getNameLoc(), diag::err_no_member)
2666 << Name << computeDeclContext(SS, false) << NameRange;
2667 return true;
2668 }
2669
2670 // Give up, we can't recover.
2671 Diag(R.getNameLoc(), diagnostic) << Name << NameRange;
2672 return true;
2673}
2674
2675/// In Microsoft mode, if we are inside a template class whose parent class has
2676/// dependent base classes, and we can't resolve an unqualified identifier, then
2677/// assume the identifier is a member of a dependent base class. We can only
2678/// recover successfully in static methods, instance methods, and other contexts
2679/// where 'this' is available. This doesn't precisely match MSVC's
2680/// instantiation model, but it's close enough.
2681static Expr *
2683 DeclarationNameInfo &NameInfo,
2684 SourceLocation TemplateKWLoc,
2685 const TemplateArgumentListInfo *TemplateArgs) {
2686 // Only try to recover from lookup into dependent bases in static methods or
2687 // contexts where 'this' is available.
2688 QualType ThisType = S.getCurrentThisType();
2689 const CXXRecordDecl *RD = nullptr;
2690 if (!ThisType.isNull())
2691 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2692 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2693 RD = MD->getParent();
2694 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2695 return nullptr;
2696
2697 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2698 // is available, suggest inserting 'this->' as a fixit.
2699 SourceLocation Loc = NameInfo.getLoc();
2700 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2701 DB << NameInfo.getName() << RD;
2702
2703 if (!ThisType.isNull()) {
2704 DB << FixItHint::CreateInsertion(Loc, "this->");
2706 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2707 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2708 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2709 }
2710
2711 // Synthesize a fake NNS that points to the derived class. This will
2712 // perform name lookup during template instantiation.
2713 CXXScopeSpec SS;
2714 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD)->getTypePtr());
2715 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2717 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2718 TemplateArgs);
2719}
2720
2723 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2724 bool HasTrailingLParen, bool IsAddressOfOperand,
2726 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2727 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2728 "cannot be direct & operand and have a trailing lparen");
2729 if (SS.isInvalid())
2730 return ExprError();
2731
2732 TemplateArgumentListInfo TemplateArgsBuffer;
2733
2734 // Decompose the UnqualifiedId into the following data.
2735 DeclarationNameInfo NameInfo;
2736 const TemplateArgumentListInfo *TemplateArgs;
2737 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2738
2739 DeclarationName Name = NameInfo.getName();
2741 SourceLocation NameLoc = NameInfo.getLoc();
2742
2743 if (II && II->isEditorPlaceholder()) {
2744 // FIXME: When typed placeholders are supported we can create a typed
2745 // placeholder expression node.
2746 return ExprError();
2747 }
2748
2749 // This specially handles arguments of attributes appertains to a type of C
2750 // struct field such that the name lookup within a struct finds the member
2751 // name, which is not the case for other contexts in C.
2752 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2753 // See if this is reference to a field of struct.
2754 LookupResult R(*this, NameInfo, LookupMemberName);
2755 // LookupName handles a name lookup from within anonymous struct.
2756 if (LookupName(R, S)) {
2757 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2758 QualType type = VD->getType().getNonReferenceType();
2759 // This will eventually be translated into MemberExpr upon
2760 // the use of instantiated struct fields.
2761 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2762 }
2763 }
2764 }
2765
2766 // Perform the required lookup.
2767 LookupResult R(*this, NameInfo,
2771 if (TemplateKWLoc.isValid() || TemplateArgs) {
2772 // Lookup the template name again to correctly establish the context in
2773 // which it was found. This is really unfortunate as we already did the
2774 // lookup to determine that it was a template name in the first place. If
2775 // this becomes a performance hit, we can work harder to preserve those
2776 // results until we get here but it's likely not worth it.
2777 AssumedTemplateKind AssumedTemplate;
2778 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2779 /*EnteringContext=*/false, TemplateKWLoc,
2780 &AssumedTemplate))
2781 return ExprError();
2782
2784 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2785 IsAddressOfOperand, TemplateArgs);
2786 } else {
2787 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2788 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2789 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2790
2791 // If the result might be in a dependent base class, this is a dependent
2792 // id-expression.
2794 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2795 IsAddressOfOperand, TemplateArgs);
2796
2797 // If this reference is in an Objective-C method, then we need to do
2798 // some special Objective-C lookup, too.
2799 if (IvarLookupFollowUp) {
2800 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2801 if (E.isInvalid())
2802 return ExprError();
2803
2804 if (Expr *Ex = E.getAs<Expr>())
2805 return Ex;
2806 }
2807 }
2808
2809 if (R.isAmbiguous())
2810 return ExprError();
2811
2812 // This could be an implicitly declared function reference if the language
2813 // mode allows it as a feature.
2814 if (R.empty() && HasTrailingLParen && II &&
2815 getLangOpts().implicitFunctionsAllowed()) {
2816 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2817 if (D) R.addDecl(D);
2818 }
2819
2820 // Determine whether this name might be a candidate for
2821 // argument-dependent lookup.
2822 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2823
2824 if (R.empty() && !ADL) {
2825 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2826 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2827 TemplateKWLoc, TemplateArgs))
2828 return E;
2829 }
2830
2831 // Don't diagnose an empty lookup for inline assembly.
2832 if (IsInlineAsmIdentifier)
2833 return ExprError();
2834
2835 // If this name wasn't predeclared and if this is not a function
2836 // call, diagnose the problem.
2837 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2838 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2839 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2840 "Typo correction callback misconfigured");
2841 if (CCC) {
2842 // Make sure the callback knows what the typo being diagnosed is.
2843 CCC->setTypoName(II);
2844 if (SS.isValid())
2845 CCC->setTypoNNS(SS.getScopeRep());
2846 }
2847 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2848 // a template name, but we happen to have always already looked up the name
2849 // before we get here if it must be a template name.
2850 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2851 {}, nullptr))
2852 return ExprError();
2853
2854 assert(!R.empty() &&
2855 "DiagnoseEmptyLookup returned false but added no results");
2856
2857 // If we found an Objective-C instance variable, let
2858 // LookupInObjCMethod build the appropriate expression to
2859 // reference the ivar.
2860 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2861 R.clear();
2862 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2863 // In a hopelessly buggy code, Objective-C instance variable
2864 // lookup fails and no expression will be built to reference it.
2865 if (!E.isInvalid() && !E.get())
2866 return ExprError();
2867 return E;
2868 }
2869 }
2870
2871 // This is guaranteed from this point on.
2872 assert(!R.empty() || ADL);
2873
2874 // Check whether this might be a C++ implicit instance member access.
2875 // C++ [class.mfct.non-static]p3:
2876 // When an id-expression that is not part of a class member access
2877 // syntax and not used to form a pointer to member is used in the
2878 // body of a non-static member function of class X, if name lookup
2879 // resolves the name in the id-expression to a non-static non-type
2880 // member of some class C, the id-expression is transformed into a
2881 // class member access expression using (*this) as the
2882 // postfix-expression to the left of the . operator.
2883 //
2884 // But we don't actually need to do this for '&' operands if R
2885 // resolved to a function or overloaded function set, because the
2886 // expression is ill-formed if it actually works out to be a
2887 // non-static member function:
2888 //
2889 // C++ [expr.ref]p4:
2890 // Otherwise, if E1.E2 refers to a non-static member function. . .
2891 // [t]he expression can be used only as the left-hand operand of a
2892 // member function call.
2893 //
2894 // There are other safeguards against such uses, but it's important
2895 // to get this right here so that we don't end up making a
2896 // spuriously dependent expression if we're inside a dependent
2897 // instance method.
2898 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2899 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2900 S);
2901
2902 if (TemplateArgs || TemplateKWLoc.isValid()) {
2903
2904 // In C++1y, if this is a variable template id, then check it
2905 // in BuildTemplateIdExpr().
2906 // The single lookup result must be a variable template declaration.
2910 assert(R.getAsSingle<TemplateDecl>() &&
2911 "There should only be one declaration found.");
2912 }
2913
2914 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2915 }
2916
2917 return BuildDeclarationNameExpr(SS, R, ADL);
2918}
2919
2921 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2922 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
2923 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2924 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
2925
2926 if (R.isAmbiguous())
2927 return ExprError();
2928
2930 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2931 NameInfo, /*TemplateArgs=*/nullptr);
2932
2933 if (R.empty()) {
2934 // Don't diagnose problems with invalid record decl, the secondary no_member
2935 // diagnostic during template instantiation is likely bogus, e.g. if a class
2936 // is invalid because it's derived from an invalid base class, then missing
2937 // members were likely supposed to be inherited.
2939 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2940 if (CD->isInvalidDecl())
2941 return ExprError();
2942 Diag(NameInfo.getLoc(), diag::err_no_member)
2943 << NameInfo.getName() << DC << SS.getRange();
2944 return ExprError();
2945 }
2946
2947 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2948 QualType ET;
2949 TypeLocBuilder TLB;
2950 if (auto *TagD = dyn_cast<TagDecl>(TD)) {
2951 ET = SemaRef.Context.getTagType(ElaboratedTypeKeyword::None,
2952 SS.getScopeRep(), TagD,
2953 /*OwnsTag=*/false);
2954 auto TL = TLB.push<TagTypeLoc>(ET);
2956 TL.setQualifierLoc(SS.getWithLocInContext(Context));
2957 TL.setNameLoc(NameInfo.getLoc());
2958 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(TD)) {
2959 ET = SemaRef.Context.getTypedefType(ElaboratedTypeKeyword::None,
2960 SS.getScopeRep(), TypedefD);
2961 TLB.push<TypedefTypeLoc>(ET).set(
2962 /*ElaboratedKeywordLoc=*/SourceLocation(),
2963 SS.getWithLocInContext(Context), NameInfo.getLoc());
2964 } else {
2965 // FIXME: What else can appear here?
2966 ET = SemaRef.Context.getTypeDeclType(TD);
2967 TLB.pushTypeSpec(ET).setNameLoc(NameInfo.getLoc());
2968 assert(SS.isEmpty());
2969 }
2970
2971 // Diagnose a missing typename if this resolved unambiguously to a type in
2972 // a dependent context. If we can recover with a type, downgrade this to
2973 // a warning in Microsoft compatibility mode.
2974 unsigned DiagID = diag::err_typename_missing;
2975 if (RecoveryTSI && getLangOpts().MSVCCompat)
2976 DiagID = diag::ext_typename_missing;
2977 SourceLocation Loc = SS.getBeginLoc();
2978 auto D = Diag(Loc, DiagID);
2979 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
2980
2981 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2982 // context.
2983 if (!RecoveryTSI)
2984 return ExprError();
2985
2986 // Only issue the fixit if we're prepared to recover.
2987 D << FixItHint::CreateInsertion(Loc, "typename ");
2988
2989 // Recover by pretending this was an elaborated type.
2990 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2991
2992 return ExprEmpty();
2993 }
2994
2995 // If necessary, build an implicit class member access.
2996 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2998 /*TemplateKWLoc=*/SourceLocation(),
2999 R, /*TemplateArgs=*/nullptr,
3000 /*S=*/nullptr);
3001
3002 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
3003}
3004
3006 NestedNameSpecifier Qualifier,
3007 NamedDecl *FoundDecl,
3008 NamedDecl *Member) {
3009 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3010 if (!RD)
3011 return From;
3012
3013 QualType DestRecordType;
3014 QualType DestType;
3015 QualType FromRecordType;
3016 QualType FromType = From->getType();
3017 bool PointerConversions = false;
3018 if (isa<FieldDecl>(Member)) {
3019 DestRecordType = Context.getCanonicalTagType(RD);
3020 auto FromPtrType = FromType->getAs<PointerType>();
3021 DestRecordType = Context.getAddrSpaceQualType(
3022 DestRecordType, FromPtrType
3023 ? FromType->getPointeeType().getAddressSpace()
3024 : FromType.getAddressSpace());
3025
3026 if (FromPtrType) {
3027 DestType = Context.getPointerType(DestRecordType);
3028 FromRecordType = FromPtrType->getPointeeType();
3029 PointerConversions = true;
3030 } else {
3031 DestType = DestRecordType;
3032 FromRecordType = FromType;
3033 }
3034 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3035 if (!Method->isImplicitObjectMemberFunction())
3036 return From;
3037
3038 DestType = Method->getThisType().getNonReferenceType();
3039 DestRecordType = Method->getFunctionObjectParameterType();
3040
3041 if (FromType->getAs<PointerType>()) {
3042 FromRecordType = FromType->getPointeeType();
3043 PointerConversions = true;
3044 } else {
3045 FromRecordType = FromType;
3046 DestType = DestRecordType;
3047 }
3048
3049 LangAS FromAS = FromRecordType.getAddressSpace();
3050 LangAS DestAS = DestRecordType.getAddressSpace();
3051 if (FromAS != DestAS) {
3052 QualType FromRecordTypeWithoutAS =
3053 Context.removeAddrSpaceQualType(FromRecordType);
3054 QualType FromTypeWithDestAS =
3055 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3056 if (PointerConversions)
3057 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3058 From = ImpCastExprToType(From, FromTypeWithDestAS,
3059 CK_AddressSpaceConversion, From->getValueKind())
3060 .get();
3061 }
3062 } else {
3063 // No conversion necessary.
3064 return From;
3065 }
3066
3067 if (DestType->isDependentType() || FromType->isDependentType())
3068 return From;
3069
3070 // If the unqualified types are the same, no conversion is necessary.
3071 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3072 return From;
3073
3074 SourceRange FromRange = From->getSourceRange();
3075 SourceLocation FromLoc = FromRange.getBegin();
3076
3077 ExprValueKind VK = From->getValueKind();
3078
3079 // C++ [class.member.lookup]p8:
3080 // [...] Ambiguities can often be resolved by qualifying a name with its
3081 // class name.
3082 //
3083 // If the member was a qualified name and the qualified referred to a
3084 // specific base subobject type, we'll cast to that intermediate type
3085 // first and then to the object in which the member is declared. That allows
3086 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3087 //
3088 // class Base { public: int x; };
3089 // class Derived1 : public Base { };
3090 // class Derived2 : public Base { };
3091 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3092 //
3093 // void VeryDerived::f() {
3094 // x = 17; // error: ambiguous base subobjects
3095 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3096 // }
3097 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3098 QualType QType = QualType(Qualifier.getAsType(), 0);
3099 assert(QType->isRecordType() && "lookup done with non-record type");
3100
3101 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3102
3103 // In C++98, the qualifier type doesn't actually have to be a base
3104 // type of the object type, in which case we just ignore it.
3105 // Otherwise build the appropriate casts.
3106 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3107 CXXCastPath BasePath;
3108 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3109 FromLoc, FromRange, &BasePath))
3110 return ExprError();
3111
3112 if (PointerConversions)
3113 QType = Context.getPointerType(QType);
3114 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3115 VK, &BasePath).get();
3116
3117 FromType = QType;
3118 FromRecordType = QRecordType;
3119
3120 // If the qualifier type was the same as the destination type,
3121 // we're done.
3122 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3123 return From;
3124 }
3125 }
3126
3127 CXXCastPath BasePath;
3128 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3129 FromLoc, FromRange, &BasePath,
3130 /*IgnoreAccess=*/true))
3131 return ExprError();
3132
3133 // Propagate qualifiers to base subobjects as per:
3134 // C++ [basic.type.qualifier]p1.2:
3135 // A volatile object is [...] a subobject of a volatile object.
3136 Qualifiers FromTypeQuals = FromType.getQualifiers();
3137 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3138 DestType = Context.getQualifiedType(DestType, FromTypeQuals);
3139
3140 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, VK,
3141 &BasePath);
3142}
3143
3145 const LookupResult &R,
3146 bool HasTrailingLParen) {
3147 // Only when used directly as the postfix-expression of a call.
3148 if (!HasTrailingLParen)
3149 return false;
3150
3151 // Never if a scope specifier was provided.
3152 if (SS.isNotEmpty())
3153 return false;
3154
3155 // Only in C++ or ObjC++.
3156 if (!getLangOpts().CPlusPlus)
3157 return false;
3158
3159 // Turn off ADL when we find certain kinds of declarations during
3160 // normal lookup:
3161 for (const NamedDecl *D : R) {
3162 // C++0x [basic.lookup.argdep]p3:
3163 // -- a declaration of a class member
3164 // Since using decls preserve this property, we check this on the
3165 // original decl.
3166 if (D->isCXXClassMember())
3167 return false;
3168
3169 // C++0x [basic.lookup.argdep]p3:
3170 // -- a block-scope function declaration that is not a
3171 // using-declaration
3172 // NOTE: we also trigger this for function templates (in fact, we
3173 // don't check the decl type at all, since all other decl types
3174 // turn off ADL anyway).
3175 if (isa<UsingShadowDecl>(D))
3176 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3177 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3178 return false;
3179
3180 // C++0x [basic.lookup.argdep]p3:
3181 // -- a declaration that is neither a function or a function
3182 // template
3183 // And also for builtin functions.
3184 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3185 // But also builtin functions.
3186 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3187 return false;
3188 } else if (!isa<FunctionTemplateDecl>(D))
3189 return false;
3190 }
3191
3192 return true;
3193}
3194
3195
3196/// Diagnoses obvious problems with the use of the given declaration
3197/// as an expression. This is only actually called for lookups that
3198/// were not overloaded, and it doesn't promise that the declaration
3199/// will in fact be used.
3201 bool AcceptInvalid) {
3202 if (D->isInvalidDecl() && !AcceptInvalid)
3203 return true;
3204
3205 if (isa<TypedefNameDecl>(D)) {
3206 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3207 return true;
3208 }
3209
3210 if (isa<ObjCInterfaceDecl>(D)) {
3211 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3212 return true;
3213 }
3214
3215 if (isa<NamespaceDecl>(D)) {
3216 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3217 return true;
3218 }
3219
3220 return false;
3221}
3222
3223// Certain multiversion types should be treated as overloaded even when there is
3224// only one result.
3226 assert(R.isSingleResult() && "Expected only a single result");
3227 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3228 return FD &&
3229 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3230}
3231
3233 LookupResult &R, bool NeedsADL,
3234 bool AcceptInvalidDecl) {
3235 // If this is a single, fully-resolved result and we don't need ADL,
3236 // just build an ordinary singleton decl ref.
3237 if (!NeedsADL && R.isSingleResult() &&
3241 R.getRepresentativeDecl(), nullptr,
3242 AcceptInvalidDecl);
3243
3244 // We only need to check the declaration if there's exactly one
3245 // result, because in the overloaded case the results can only be
3246 // functions and function templates.
3248 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3249 AcceptInvalidDecl))
3250 return ExprError();
3251
3252 // Otherwise, just build an unresolved lookup expression. Suppress
3253 // any lookup-related diagnostics; we'll hash these out later, when
3254 // we've picked a target.
3256
3259 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3260 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3261
3262 return ULE;
3263}
3264
3266 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3267 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3268 bool AcceptInvalidDecl) {
3269 assert(D && "Cannot refer to a NULL declaration");
3270 assert(!isa<FunctionTemplateDecl>(D) &&
3271 "Cannot refer unambiguously to a function template");
3272
3273 SourceLocation Loc = NameInfo.getLoc();
3274 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3275 // Recovery from invalid cases (e.g. D is an invalid Decl).
3276 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3277 // diagnostics, as invalid decls use int as a fallback type.
3278 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3279 }
3280
3281 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3282 // Specifically diagnose references to class templates that are missing
3283 // a template argument list.
3284 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3285 return ExprError();
3286 }
3287
3288 // Make sure that we're referring to a value.
3290 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3291 Diag(D->getLocation(), diag::note_declared_at);
3292 return ExprError();
3293 }
3294
3295 // Check whether this declaration can be used. Note that we suppress
3296 // this check when we're going to perform argument-dependent lookup
3297 // on this function name, because this might not be the function
3298 // that overload resolution actually selects.
3299 if (DiagnoseUseOfDecl(D, Loc))
3300 return ExprError();
3301
3302 auto *VD = cast<ValueDecl>(D);
3303
3304 // Only create DeclRefExpr's for valid Decl's.
3305 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3306 return ExprError();
3307
3308 // Handle members of anonymous structs and unions. If we got here,
3309 // and the reference is to a class member indirect field, then this
3310 // must be the subject of a pointer-to-member expression.
3311 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3312 IndirectField && !IndirectField->isCXXClassMember())
3314 IndirectField);
3315
3316 QualType type = VD->getType();
3317 if (type.isNull())
3318 return ExprError();
3319 ExprValueKind valueKind = VK_PRValue;
3320
3321 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3322 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3323 // is expanded by some outer '...' in the context of the use.
3324 type = type.getNonPackExpansionType();
3325
3326 switch (D->getKind()) {
3327 // Ignore all the non-ValueDecl kinds.
3328#define ABSTRACT_DECL(kind)
3329#define VALUE(type, base)
3330#define DECL(type, base) case Decl::type:
3331#include "clang/AST/DeclNodes.inc"
3332 llvm_unreachable("invalid value decl kind");
3333
3334 // These shouldn't make it here.
3335 case Decl::ObjCAtDefsField:
3336 llvm_unreachable("forming non-member reference to ivar?");
3337
3338 // Enum constants are always r-values and never references.
3339 // Unresolved using declarations are dependent.
3340 case Decl::EnumConstant:
3341 case Decl::UnresolvedUsingValue:
3342 case Decl::OMPDeclareReduction:
3343 case Decl::OMPDeclareMapper:
3344 valueKind = VK_PRValue;
3345 break;
3346
3347 // Fields and indirect fields that got here must be for
3348 // pointer-to-member expressions; we just call them l-values for
3349 // internal consistency, because this subexpression doesn't really
3350 // exist in the high-level semantics.
3351 case Decl::Field:
3352 case Decl::IndirectField:
3353 case Decl::ObjCIvar:
3354 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3355 "building reference to field in C?");
3356
3357 // These can't have reference type in well-formed programs, but
3358 // for internal consistency we do this anyway.
3359 type = type.getNonReferenceType();
3360 valueKind = VK_LValue;
3361 break;
3362
3363 // Non-type template parameters are either l-values or r-values
3364 // depending on the type.
3365 case Decl::NonTypeTemplateParm: {
3366 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3367 type = reftype->getPointeeType();
3368 valueKind = VK_LValue; // even if the parameter is an r-value reference
3369 break;
3370 }
3371
3372 // [expr.prim.id.unqual]p2:
3373 // If the entity is a template parameter object for a template
3374 // parameter of type T, the type of the expression is const T.
3375 // [...] The expression is an lvalue if the entity is a [...] template
3376 // parameter object.
3377 if (type->isRecordType()) {
3378 type = type.getUnqualifiedType().withConst();
3379 valueKind = VK_LValue;
3380 break;
3381 }
3382
3383 // For non-references, we need to strip qualifiers just in case
3384 // the template parameter was declared as 'const int' or whatever.
3385 valueKind = VK_PRValue;
3386 type = type.getUnqualifiedType();
3387 break;
3388 }
3389
3390 case Decl::Var:
3391 case Decl::VarTemplateSpecialization:
3392 case Decl::VarTemplatePartialSpecialization:
3393 case Decl::Decomposition:
3394 case Decl::Binding:
3395 case Decl::OMPCapturedExpr:
3396 // In C, "extern void blah;" is valid and is an r-value.
3397 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3398 type->isVoidType()) {
3399 valueKind = VK_PRValue;
3400 break;
3401 }
3402 [[fallthrough]];
3403
3404 case Decl::ImplicitParam:
3405 case Decl::ParmVar: {
3406 // These are always l-values.
3407 valueKind = VK_LValue;
3408 type = type.getNonReferenceType();
3409
3410 // FIXME: Does the addition of const really only apply in
3411 // potentially-evaluated contexts? Since the variable isn't actually
3412 // captured in an unevaluated context, it seems that the answer is no.
3413 if (!isUnevaluatedContext()) {
3414 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3415 if (!CapturedType.isNull())
3416 type = CapturedType;
3417 }
3418 break;
3419 }
3420
3421 case Decl::Function: {
3422 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3423 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3424 type = Context.BuiltinFnTy;
3425 valueKind = VK_PRValue;
3426 break;
3427 }
3428 }
3429
3430 const FunctionType *fty = type->castAs<FunctionType>();
3431
3432 // If we're referring to a function with an __unknown_anytype
3433 // result type, make the entire expression __unknown_anytype.
3434 if (fty->getReturnType() == Context.UnknownAnyTy) {
3435 type = Context.UnknownAnyTy;
3436 valueKind = VK_PRValue;
3437 break;
3438 }
3439
3440 // Functions are l-values in C++.
3441 if (getLangOpts().CPlusPlus) {
3442 valueKind = VK_LValue;
3443 break;
3444 }
3445
3446 // C99 DR 316 says that, if a function type comes from a
3447 // function definition (without a prototype), that type is only
3448 // used for checking compatibility. Therefore, when referencing
3449 // the function, we pretend that we don't have the full function
3450 // type.
3451 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3452 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3453 fty->getExtInfo());
3454
3455 // Functions are r-values in C.
3456 valueKind = VK_PRValue;
3457 break;
3458 }
3459
3460 case Decl::CXXDeductionGuide:
3461 llvm_unreachable("building reference to deduction guide");
3462
3463 case Decl::MSProperty:
3464 case Decl::MSGuid:
3465 case Decl::TemplateParamObject:
3466 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3467 // capture in OpenMP, or duplicated between host and device?
3468 valueKind = VK_LValue;
3469 break;
3470
3471 case Decl::UnnamedGlobalConstant:
3472 valueKind = VK_LValue;
3473 break;
3474
3475 case Decl::CXXMethod:
3476 // If we're referring to a method with an __unknown_anytype
3477 // result type, make the entire expression __unknown_anytype.
3478 // This should only be possible with a type written directly.
3479 if (const FunctionProtoType *proto =
3480 dyn_cast<FunctionProtoType>(VD->getType()))
3481 if (proto->getReturnType() == Context.UnknownAnyTy) {
3482 type = Context.UnknownAnyTy;
3483 valueKind = VK_PRValue;
3484 break;
3485 }
3486
3487 // C++ methods are l-values if static, r-values if non-static.
3488 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3489 valueKind = VK_LValue;
3490 break;
3491 }
3492 [[fallthrough]];
3493
3494 case Decl::CXXConversion:
3495 case Decl::CXXDestructor:
3496 case Decl::CXXConstructor:
3497 valueKind = VK_PRValue;
3498 break;
3499 }
3500
3501 auto *E =
3502 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3503 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3504 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3505 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3506 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3507 // diagnostics).
3508 if (VD->isInvalidDecl() && E)
3509 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3510 return E;
3511}
3512
3513static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3515 Target.resize(CharByteWidth * (Source.size() + 1));
3516 char *ResultPtr = &Target[0];
3517 const llvm::UTF8 *ErrorPtr;
3518 bool success =
3519 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3520 (void)success;
3521 assert(success);
3522 Target.resize(ResultPtr - &Target[0]);
3523}
3524
3527 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3528 if (!currentDecl) {
3529 Diag(Loc, diag::ext_predef_outside_function);
3530 currentDecl = Context.getTranslationUnitDecl();
3531 }
3532
3533 QualType ResTy;
3534 StringLiteral *SL = nullptr;
3535 if (cast<DeclContext>(currentDecl)->isDependentContext())
3536 ResTy = Context.DependentTy;
3537 else {
3538 // Pre-defined identifiers are of type char[x], where x is the length of
3539 // the string.
3540 bool ForceElaboratedPrinting =
3541 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3542 auto Str =
3543 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3544 unsigned Length = Str.length();
3545
3546 llvm::APInt LengthI(32, Length + 1);
3549 ResTy =
3550 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3551 SmallString<32> RawChars;
3552 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3553 Str, RawChars);
3554 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3556 /*IndexTypeQuals*/ 0);
3558 /*Pascal*/ false, ResTy, Loc);
3559 } else {
3560 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3561 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3563 /*IndexTypeQuals*/ 0);
3565 /*Pascal*/ false, ResTy, Loc);
3566 }
3567 }
3568
3569 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3570 SL);
3571}
3572
3576
3578 SmallString<16> CharBuffer;
3579 bool Invalid = false;
3580 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3581 if (Invalid)
3582 return ExprError();
3583
3584 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3585 PP, Tok.getKind());
3586 if (Literal.hadError())
3587 return ExprError();
3588
3589 QualType Ty;
3590 if (Literal.isWide())
3591 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3592 else if (Literal.isUTF8() && getLangOpts().C23)
3593 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3594 else if (Literal.isUTF8() && getLangOpts().Char8)
3595 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3596 else if (Literal.isUTF16())
3597 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3598 else if (Literal.isUTF32())
3599 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3600 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3601 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3602 else
3603 Ty = Context.CharTy; // 'x' -> char in C++;
3604 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3605
3607 if (Literal.isWide())
3609 else if (Literal.isUTF16())
3611 else if (Literal.isUTF32())
3613 else if (Literal.isUTF8())
3615
3616 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3617 Tok.getLocation());
3618
3619 if (Literal.getUDSuffix().empty())
3620 return Lit;
3621
3622 // We're building a user-defined literal.
3623 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3624 SourceLocation UDSuffixLoc =
3625 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3626
3627 // Make sure we're allowed user-defined literals here.
3628 if (!UDLScope)
3629 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3630
3631 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3632 // operator "" X (ch)
3633 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3634 Lit, Tok.getLocation());
3635}
3636
3638 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3640 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3641 Context.IntTy, Loc);
3642}
3643
3645 QualType Ty, SourceLocation Loc) {
3646 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3647
3648 using llvm::APFloat;
3649 APFloat Val(Format);
3650
3651 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3652 if (RM == llvm::RoundingMode::Dynamic)
3653 RM = llvm::RoundingMode::NearestTiesToEven;
3654 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3655
3656 // Overflow is always an error, but underflow is only an error if
3657 // we underflowed to zero (APFloat reports denormals as underflow).
3658 if ((result & APFloat::opOverflow) ||
3659 ((result & APFloat::opUnderflow) && Val.isZero())) {
3660 unsigned diagnostic;
3661 SmallString<20> buffer;
3662 if (result & APFloat::opOverflow) {
3663 diagnostic = diag::warn_float_overflow;
3664 APFloat::getLargest(Format).toString(buffer);
3665 } else {
3666 diagnostic = diag::warn_float_underflow;
3667 APFloat::getSmallest(Format).toString(buffer);
3668 }
3669
3670 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3671 }
3672
3673 bool isExact = (result == APFloat::opOK);
3674 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3675}
3676
3677bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3678 assert(E && "Invalid expression");
3679
3680 if (E->isValueDependent())
3681 return false;
3682
3683 QualType QT = E->getType();
3684 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3685 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3686 return true;
3687 }
3688
3689 llvm::APSInt ValueAPS;
3691
3692 if (R.isInvalid())
3693 return true;
3694
3695 // GCC allows the value of unroll count to be 0.
3696 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3697 // "The values of 0 and 1 block any unrolling of the loop."
3698 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3699 // '#pragma unroll' cases.
3700 bool ValueIsPositive =
3701 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3702 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3703 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3704 << toString(ValueAPS, 10) << ValueIsPositive;
3705 return true;
3706 }
3707
3708 return false;
3709}
3710
3712 // Fast path for a single digit (which is quite common). A single digit
3713 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3714 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3715 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3716 return ActOnIntegerConstant(Tok.getLocation(), Val);
3717 }
3718
3719 SmallString<128> SpellingBuffer;
3720 // NumericLiteralParser wants to overread by one character. Add padding to
3721 // the buffer in case the token is copied to the buffer. If getSpelling()
3722 // returns a StringRef to the memory buffer, it should have a null char at
3723 // the EOF, so it is also safe.
3724 SpellingBuffer.resize(Tok.getLength() + 1);
3725
3726 // Get the spelling of the token, which eliminates trigraphs, etc.
3727 bool Invalid = false;
3728 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3729 if (Invalid)
3730 return ExprError();
3731
3732 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3733 PP.getSourceManager(), PP.getLangOpts(),
3734 PP.getTargetInfo(), PP.getDiagnostics());
3735 if (Literal.hadError)
3736 return ExprError();
3737
3738 if (Literal.hasUDSuffix()) {
3739 // We're building a user-defined literal.
3740 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3741 SourceLocation UDSuffixLoc =
3742 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3743
3744 // Make sure we're allowed user-defined literals here.
3745 if (!UDLScope)
3746 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3747
3748 QualType CookedTy;
3749 if (Literal.isFloatingLiteral()) {
3750 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3751 // long double, the literal is treated as a call of the form
3752 // operator "" X (f L)
3753 CookedTy = Context.LongDoubleTy;
3754 } else {
3755 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3756 // unsigned long long, the literal is treated as a call of the form
3757 // operator "" X (n ULL)
3758 CookedTy = Context.UnsignedLongLongTy;
3759 }
3760
3761 DeclarationName OpName =
3762 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3763 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3764 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3765
3766 SourceLocation TokLoc = Tok.getLocation();
3767
3768 // Perform literal operator lookup to determine if we're building a raw
3769 // literal or a cooked one.
3770 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3771 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3772 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3773 /*AllowStringTemplatePack*/ false,
3774 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3776 // Lookup failure for imaginary constants isn't fatal, there's still the
3777 // GNU extension producing _Complex types.
3778 break;
3779 case LOLR_Error:
3780 return ExprError();
3781 case LOLR_Cooked: {
3782 Expr *Lit;
3783 if (Literal.isFloatingLiteral()) {
3784 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3785 } else {
3786 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3787 if (Literal.GetIntegerValue(ResultVal))
3788 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3789 << /* Unsigned */ 1;
3790 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3791 Tok.getLocation());
3792 }
3793 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3794 }
3795
3796 case LOLR_Raw: {
3797 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3798 // literal is treated as a call of the form
3799 // operator "" X ("n")
3800 unsigned Length = Literal.getUDSuffixOffset();
3801 QualType StrTy = Context.getConstantArrayType(
3802 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3803 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3804 Expr *Lit =
3805 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3807 /*Pascal*/ false, StrTy, TokLoc);
3808 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3809 }
3810
3811 case LOLR_Template: {
3812 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3813 // template), L is treated as a call fo the form
3814 // operator "" X <'c1', 'c2', ... 'ck'>()
3815 // where n is the source character sequence c1 c2 ... ck.
3816 TemplateArgumentListInfo ExplicitArgs;
3817 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3818 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3819 llvm::APSInt Value(CharBits, CharIsUnsigned);
3820 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3821 Value = TokSpelling[I];
3822 TemplateArgument Arg(Context, Value, Context.CharTy);
3824 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3825 }
3826 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
3827 }
3829 llvm_unreachable("unexpected literal operator lookup result");
3830 }
3831 }
3832
3833 Expr *Res;
3834
3835 if (Literal.isFixedPointLiteral()) {
3836 QualType Ty;
3837
3838 if (Literal.isAccum) {
3839 if (Literal.isHalf) {
3840 Ty = Context.ShortAccumTy;
3841 } else if (Literal.isLong) {
3842 Ty = Context.LongAccumTy;
3843 } else {
3844 Ty = Context.AccumTy;
3845 }
3846 } else if (Literal.isFract) {
3847 if (Literal.isHalf) {
3848 Ty = Context.ShortFractTy;
3849 } else if (Literal.isLong) {
3850 Ty = Context.LongFractTy;
3851 } else {
3852 Ty = Context.FractTy;
3853 }
3854 }
3855
3856 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3857
3858 bool isSigned = !Literal.isUnsigned;
3859 unsigned scale = Context.getFixedPointScale(Ty);
3860 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3861
3862 llvm::APInt Val(bit_width, 0, isSigned);
3863 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3864 bool ValIsZero = Val.isZero() && !Overflowed;
3865
3866 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3867 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3868 // Clause 6.4.4 - The value of a constant shall be in the range of
3869 // representable values for its type, with exception for constants of a
3870 // fract type with a value of exactly 1; such a constant shall denote
3871 // the maximal value for the type.
3872 --Val;
3873 else if (Val.ugt(MaxVal) || Overflowed)
3874 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3875
3877 Tok.getLocation(), scale);
3878 } else if (Literal.isFloatingLiteral()) {
3879 QualType Ty;
3880 if (Literal.isHalf){
3881 if (getLangOpts().HLSL ||
3882 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3883 Ty = Context.HalfTy;
3884 else {
3885 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3886 return ExprError();
3887 }
3888 } else if (Literal.isFloat)
3889 Ty = Context.FloatTy;
3890 else if (Literal.isLong)
3891 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
3892 else if (Literal.isFloat16)
3893 Ty = Context.Float16Ty;
3894 else if (Literal.isFloat128)
3895 Ty = Context.Float128Ty;
3896 else if (getLangOpts().HLSL)
3897 Ty = Context.FloatTy;
3898 else
3899 Ty = Context.DoubleTy;
3900
3901 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3902
3903 if (Ty == Context.DoubleTy) {
3904 if (getLangOpts().SinglePrecisionConstants) {
3905 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3906 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3907 }
3908 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3909 "cl_khr_fp64", getLangOpts())) {
3910 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3911 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3913 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3914 }
3915 }
3916 } else if (!Literal.isIntegerLiteral()) {
3917 return ExprError();
3918 } else {
3919 QualType Ty;
3920
3921 // 'z/uz' literals are a C++23 feature.
3922 if (Literal.isSizeT)
3923 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
3925 ? diag::warn_cxx20_compat_size_t_suffix
3926 : diag::ext_cxx23_size_t_suffix
3927 : diag::err_cxx23_size_t_suffix);
3928
3929 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
3930 // but we do not currently support the suffix in C++ mode because it's not
3931 // entirely clear whether WG21 will prefer this suffix to return a library
3932 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
3933 // literals are a C++ extension.
3934 if (Literal.isBitInt)
3935 PP.Diag(Tok.getLocation(),
3936 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
3937 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
3938 : diag::ext_c23_bitint_suffix);
3939
3940 // Get the value in the widest-possible width. What is "widest" depends on
3941 // whether the literal is a bit-precise integer or not. For a bit-precise
3942 // integer type, try to scan the source to determine how many bits are
3943 // needed to represent the value. This may seem a bit expensive, but trying
3944 // to get the integer value from an overly-wide APInt is *extremely*
3945 // expensive, so the naive approach of assuming
3946 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3947 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
3948 if (Literal.isBitInt)
3949 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
3950 Literal.getLiteralDigits(), Literal.getRadix());
3951 if (Literal.MicrosoftInteger) {
3952 if (Literal.MicrosoftInteger == 128 &&
3953 !Context.getTargetInfo().hasInt128Type())
3954 PP.Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3955 << Literal.isUnsigned;
3956 BitsNeeded = Literal.MicrosoftInteger;
3957 }
3958
3959 llvm::APInt ResultVal(BitsNeeded, 0);
3960
3961 if (Literal.GetIntegerValue(ResultVal)) {
3962 // If this value didn't fit into uintmax_t, error and force to ull.
3963 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3964 << /* Unsigned */ 1;
3965 Ty = Context.UnsignedLongLongTy;
3966 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3967 "long long is not intmax_t?");
3968 } else {
3969 // If this value fits into a ULL, try to figure out what else it fits into
3970 // according to the rules of C99 6.4.4.1p5.
3971
3972 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3973 // be an unsigned int.
3974 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3975
3976 // HLSL doesn't really have `long` or `long long`. We support the `ll`
3977 // suffix for portability of code with C++, but both `l` and `ll` are
3978 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
3979 // same.
3980 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
3981 Literal.isLong = true;
3982 Literal.isLongLong = false;
3983 }
3984
3985 // Check from smallest to largest, picking the smallest type we can.
3986 unsigned Width = 0;
3987
3988 // Microsoft specific integer suffixes are explicitly sized.
3989 if (Literal.MicrosoftInteger) {
3990 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3991 Width = 8;
3992 Ty = Context.CharTy;
3993 } else {
3994 Width = Literal.MicrosoftInteger;
3995 Ty = Context.getIntTypeForBitwidth(Width,
3996 /*Signed=*/!Literal.isUnsigned);
3997 }
3998 }
3999
4000 // Bit-precise integer literals are automagically-sized based on the
4001 // width required by the literal.
4002 if (Literal.isBitInt) {
4003 // The signed version has one more bit for the sign value. There are no
4004 // zero-width bit-precise integers, even if the literal value is 0.
4005 Width = std::max(ResultVal.getActiveBits(), 1u) +
4006 (Literal.isUnsigned ? 0u : 1u);
4007
4008 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4009 // and reset the type to the largest supported width.
4010 unsigned int MaxBitIntWidth =
4011 Context.getTargetInfo().getMaxBitIntWidth();
4012 if (Width > MaxBitIntWidth) {
4013 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4014 << Literal.isUnsigned;
4015 Width = MaxBitIntWidth;
4016 }
4017
4018 // Reset the result value to the smaller APInt and select the correct
4019 // type to be used. Note, we zext even for signed values because the
4020 // literal itself is always an unsigned value (a preceeding - is a
4021 // unary operator, not part of the literal).
4022 ResultVal = ResultVal.zextOrTrunc(Width);
4023 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4024 }
4025
4026 // Check C++23 size_t literals.
4027 if (Literal.isSizeT) {
4028 assert(!Literal.MicrosoftInteger &&
4029 "size_t literals can't be Microsoft literals");
4030 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4031 Context.getTargetInfo().getSizeType());
4032
4033 // Does it fit in size_t?
4034 if (ResultVal.isIntN(SizeTSize)) {
4035 // Does it fit in ssize_t?
4036 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4037 Ty = Context.getSignedSizeType();
4038 else if (AllowUnsigned)
4039 Ty = Context.getSizeType();
4040 Width = SizeTSize;
4041 }
4042 }
4043
4044 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4045 !Literal.isSizeT) {
4046 // Are int/unsigned possibilities?
4047 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4048
4049 // Does it fit in a unsigned int?
4050 if (ResultVal.isIntN(IntSize)) {
4051 // Does it fit in a signed int?
4052 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4053 Ty = Context.IntTy;
4054 else if (AllowUnsigned)
4055 Ty = Context.UnsignedIntTy;
4056 Width = IntSize;
4057 }
4058 }
4059
4060 // Are long/unsigned long possibilities?
4061 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4062 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4063
4064 // Does it fit in a unsigned long?
4065 if (ResultVal.isIntN(LongSize)) {
4066 // Does it fit in a signed long?
4067 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4068 Ty = Context.LongTy;
4069 else if (AllowUnsigned)
4070 Ty = Context.UnsignedLongTy;
4071 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4072 // is compatible.
4073 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4074 const unsigned LongLongSize =
4075 Context.getTargetInfo().getLongLongWidth();
4076 Diag(Tok.getLocation(),
4078 ? Literal.isLong
4079 ? diag::warn_old_implicitly_unsigned_long_cxx
4080 : /*C++98 UB*/ diag::
4081 ext_old_implicitly_unsigned_long_cxx
4082 : diag::warn_old_implicitly_unsigned_long)
4083 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4084 : /*will be ill-formed*/ 1);
4085 Ty = Context.UnsignedLongTy;
4086 }
4087 Width = LongSize;
4088 }
4089 }
4090
4091 // Check long long if needed.
4092 if (Ty.isNull() && !Literal.isSizeT) {
4093 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4094
4095 // Does it fit in a unsigned long long?
4096 if (ResultVal.isIntN(LongLongSize)) {
4097 // Does it fit in a signed long long?
4098 // To be compatible with MSVC, hex integer literals ending with the
4099 // LL or i64 suffix are always signed in Microsoft mode.
4100 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4101 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4102 Ty = Context.LongLongTy;
4103 else if (AllowUnsigned)
4104 Ty = Context.UnsignedLongLongTy;
4105 Width = LongLongSize;
4106
4107 // 'long long' is a C99 or C++11 feature, whether the literal
4108 // explicitly specified 'long long' or we needed the extra width.
4109 if (getLangOpts().CPlusPlus)
4110 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4111 ? diag::warn_cxx98_compat_longlong
4112 : diag::ext_cxx11_longlong);
4113 else if (!getLangOpts().C99)
4114 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4115 }
4116 }
4117
4118 // If we still couldn't decide a type, we either have 'size_t' literal
4119 // that is out of range, or a decimal literal that does not fit in a
4120 // signed long long and has no U suffix.
4121 if (Ty.isNull()) {
4122 if (Literal.isSizeT)
4123 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4124 << Literal.isUnsigned;
4125 else
4126 Diag(Tok.getLocation(),
4127 diag::ext_integer_literal_too_large_for_signed);
4128 Ty = Context.UnsignedLongLongTy;
4129 Width = Context.getTargetInfo().getLongLongWidth();
4130 }
4131
4132 if (ResultVal.getBitWidth() != Width)
4133 ResultVal = ResultVal.trunc(Width);
4134 }
4135 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4136 }
4137
4138 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4139 if (Literal.isImaginary) {
4140 Res = new (Context) ImaginaryLiteral(Res,
4141 Context.getComplexType(Res->getType()));
4142
4143 // In C++, this is a GNU extension. In C, it's a C2y extension.
4144 unsigned DiagId;
4145 if (getLangOpts().CPlusPlus)
4146 DiagId = diag::ext_gnu_imaginary_constant;
4147 else if (getLangOpts().C2y)
4148 DiagId = diag::warn_c23_compat_imaginary_constant;
4149 else
4150 DiagId = diag::ext_c2y_imaginary_constant;
4151 Diag(Tok.getLocation(), DiagId);
4152 }
4153 return Res;
4154}
4155
4157 assert(E && "ActOnParenExpr() missing expr");
4158 QualType ExprTy = E->getType();
4159 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4160 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4161 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4162 return new (Context) ParenExpr(L, R, E);
4163}
4164
4166 SourceLocation Loc,
4167 SourceRange ArgRange) {
4168 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4169 // scalar or vector data type argument..."
4170 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4171 // type (C99 6.2.5p18) or void.
4172 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4173 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4174 << T << ArgRange;
4175 return true;
4176 }
4177
4178 assert((T->isVoidType() || !T->isIncompleteType()) &&
4179 "Scalar types should always be complete");
4180 return false;
4181}
4182
4184 SourceLocation Loc,
4185 SourceRange ArgRange) {
4186 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4187 if (!T->isVectorType() && !T->isSizelessVectorType())
4188 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4189 << ""
4190 << "__builtin_vectorelements" << T << ArgRange;
4191
4192 return false;
4193}
4194
4196 SourceLocation Loc,
4197 SourceRange ArgRange) {
4198 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4199 return true;
4200
4201 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4202 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4203 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4204 return true;
4205 }
4206
4207 return false;
4208}
4209
4211 SourceLocation Loc,
4212 SourceRange ArgRange,
4213 UnaryExprOrTypeTrait TraitKind) {
4214 // Invalid types must be hard errors for SFINAE in C++.
4215 if (S.LangOpts.CPlusPlus)
4216 return true;
4217
4218 // C99 6.5.3.4p1:
4219 if (T->isFunctionType() &&
4220 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4221 TraitKind == UETT_PreferredAlignOf)) {
4222 // sizeof(function)/alignof(function) is allowed as an extension.
4223 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4224 << getTraitSpelling(TraitKind) << ArgRange;
4225 return false;
4226 }
4227
4228 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4229 // this is an error (OpenCL v1.1 s6.3.k)
4230 if (T->isVoidType()) {
4231 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4232 : diag::ext_sizeof_alignof_void_type;
4233 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4234 return false;
4235 }
4236
4237 return true;
4238}
4239
4241 SourceLocation Loc,
4242 SourceRange ArgRange,
4243 UnaryExprOrTypeTrait TraitKind) {
4244 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4245 // runtime doesn't allow it.
4246 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4247 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4248 << T << (TraitKind == UETT_SizeOf)
4249 << ArgRange;
4250 return true;
4251 }
4252
4253 return false;
4254}
4255
4256/// Check whether E is a pointer from a decayed array type (the decayed
4257/// pointer type is equal to T) and emit a warning if it is.
4259 const Expr *E) {
4260 // Don't warn if the operation changed the type.
4261 if (T != E->getType())
4262 return;
4263
4264 // Now look for array decays.
4265 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4266 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4267 return;
4268
4269 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4270 << ICE->getType()
4271 << ICE->getSubExpr()->getType();
4272}
4273
4275 UnaryExprOrTypeTrait ExprKind) {
4276 QualType ExprTy = E->getType();
4277 assert(!ExprTy->isReferenceType());
4278
4279 bool IsUnevaluatedOperand =
4280 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4281 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4282 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4283 if (IsUnevaluatedOperand) {
4285 if (Result.isInvalid())
4286 return true;
4287 E = Result.get();
4288 }
4289
4290 // The operand for sizeof and alignof is in an unevaluated expression context,
4291 // so side effects could result in unintended consequences.
4292 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4293 // used to build SFINAE gadgets.
4294 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4295 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4297 !E->getType()->isVariableArrayType() &&
4298 E->HasSideEffects(Context, false))
4299 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4300
4301 if (ExprKind == UETT_VecStep)
4302 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4303 E->getSourceRange());
4304
4305 if (ExprKind == UETT_VectorElements)
4306 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4307 E->getSourceRange());
4308
4309 // Explicitly list some types as extensions.
4310 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4311 E->getSourceRange(), ExprKind))
4312 return false;
4313
4314 // WebAssembly tables are always illegal operands to unary expressions and
4315 // type traits.
4316 if (Context.getTargetInfo().getTriple().isWasm() &&
4318 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4319 << getTraitSpelling(ExprKind);
4320 return true;
4321 }
4322
4323 // 'alignof' applied to an expression only requires the base element type of
4324 // the expression to be complete. 'sizeof' requires the expression's type to
4325 // be complete (and will attempt to complete it if it's an array of unknown
4326 // bound).
4327 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4329 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4330 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4331 getTraitSpelling(ExprKind), E->getSourceRange()))
4332 return true;
4333 } else {
4335 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4336 getTraitSpelling(ExprKind), E->getSourceRange()))
4337 return true;
4338 }
4339
4340 // Completing the expression's type may have changed it.
4341 ExprTy = E->getType();
4342 assert(!ExprTy->isReferenceType());
4343
4344 if (ExprTy->isFunctionType()) {
4345 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4346 << getTraitSpelling(ExprKind) << E->getSourceRange();
4347 return true;
4348 }
4349
4350 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4351 E->getSourceRange(), ExprKind))
4352 return true;
4353
4354 if (ExprKind == UETT_CountOf) {
4355 // The type has to be an array type. We already checked for incomplete
4356 // types above.
4357 QualType ExprType = E->IgnoreParens()->getType();
4358 if (!ExprType->isArrayType()) {
4359 Diag(E->getExprLoc(), diag::err_countof_arg_not_array_type) << ExprType;
4360 return true;
4361 }
4362 // FIXME: warn on _Countof on an array parameter. Not warning on it
4363 // currently because there are papers in WG14 about array types which do
4364 // not decay that could impact this behavior, so we want to see if anything
4365 // changes here before coming up with a warning group for _Countof-related
4366 // diagnostics.
4367 }
4368
4369 if (ExprKind == UETT_SizeOf) {
4370 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4371 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4372 QualType OType = PVD->getOriginalType();
4373 QualType Type = PVD->getType();
4374 if (Type->isPointerType() && OType->isArrayType()) {
4375 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4376 << Type << OType;
4377 Diag(PVD->getLocation(), diag::note_declared_at);
4378 }
4379 }
4380 }
4381
4382 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4383 // decays into a pointer and returns an unintended result. This is most
4384 // likely a typo for "sizeof(array) op x".
4385 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4386 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4387 BO->getLHS());
4388 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4389 BO->getRHS());
4390 }
4391 }
4392
4393 return false;
4394}
4395
4396static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4397 // Cannot know anything else if the expression is dependent.
4398 if (E->isTypeDependent())
4399 return false;
4400
4401 if (E->getObjectKind() == OK_BitField) {
4402 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4403 << 1 << E->getSourceRange();
4404 return true;
4405 }
4406
4407 ValueDecl *D = nullptr;
4408 Expr *Inner = E->IgnoreParens();
4409 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4410 D = DRE->getDecl();
4411 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4412 D = ME->getMemberDecl();
4413 }
4414
4415 // If it's a field, require the containing struct to have a
4416 // complete definition so that we can compute the layout.
4417 //
4418 // This can happen in C++11 onwards, either by naming the member
4419 // in a way that is not transformed into a member access expression
4420 // (in an unevaluated operand, for instance), or by naming the member
4421 // in a trailing-return-type.
4422 //
4423 // For the record, since __alignof__ on expressions is a GCC
4424 // extension, GCC seems to permit this but always gives the
4425 // nonsensical answer 0.
4426 //
4427 // We don't really need the layout here --- we could instead just
4428 // directly check for all the appropriate alignment-lowing
4429 // attributes --- but that would require duplicating a lot of
4430 // logic that just isn't worth duplicating for such a marginal
4431 // use-case.
4432 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4433 // Fast path this check, since we at least know the record has a
4434 // definition if we can find a member of it.
4435 if (!FD->getParent()->isCompleteDefinition()) {
4436 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4437 << E->getSourceRange();
4438 return true;
4439 }
4440
4441 // Otherwise, if it's a field, and the field doesn't have
4442 // reference type, then it must have a complete type (or be a
4443 // flexible array member, which we explicitly want to
4444 // white-list anyway), which makes the following checks trivial.
4445 if (!FD->getType()->isReferenceType())
4446 return false;
4447 }
4448
4449 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4450}
4451
4453 E = E->IgnoreParens();
4454
4455 // Cannot know anything else if the expression is dependent.
4456 if (E->isTypeDependent())
4457 return false;
4458
4459 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4460}
4461
4463 CapturingScopeInfo *CSI) {
4464 assert(T->isVariablyModifiedType());
4465 assert(CSI != nullptr);
4466
4467 // We're going to walk down into the type and look for VLA expressions.
4468 do {
4469 const Type *Ty = T.getTypePtr();
4470 switch (Ty->getTypeClass()) {
4471#define TYPE(Class, Base)
4472#define ABSTRACT_TYPE(Class, Base)
4473#define NON_CANONICAL_TYPE(Class, Base)
4474#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4475#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4476#include "clang/AST/TypeNodes.inc"
4477 T = QualType();
4478 break;
4479 // These types are never variably-modified.
4480 case Type::Builtin:
4481 case Type::Complex:
4482 case Type::Vector:
4483 case Type::ExtVector:
4484 case Type::ConstantMatrix:
4485 case Type::Record:
4486 case Type::Enum:
4487 case Type::TemplateSpecialization:
4488 case Type::ObjCObject:
4489 case Type::ObjCInterface:
4490 case Type::ObjCObjectPointer:
4491 case Type::ObjCTypeParam:
4492 case Type::Pipe:
4493 case Type::BitInt:
4494 case Type::HLSLInlineSpirv:
4495 llvm_unreachable("type class is never variably-modified!");
4496 case Type::Adjusted:
4497 T = cast<AdjustedType>(Ty)->getOriginalType();
4498 break;
4499 case Type::Decayed:
4500 T = cast<DecayedType>(Ty)->getPointeeType();
4501 break;
4502 case Type::ArrayParameter:
4503 T = cast<ArrayParameterType>(Ty)->getElementType();
4504 break;
4505 case Type::Pointer:
4506 T = cast<PointerType>(Ty)->getPointeeType();
4507 break;
4508 case Type::BlockPointer:
4509 T = cast<BlockPointerType>(Ty)->getPointeeType();
4510 break;
4511 case Type::LValueReference:
4512 case Type::RValueReference:
4513 T = cast<ReferenceType>(Ty)->getPointeeType();
4514 break;
4515 case Type::MemberPointer:
4516 T = cast<MemberPointerType>(Ty)->getPointeeType();
4517 break;
4518 case Type::ConstantArray:
4519 case Type::IncompleteArray:
4520 // Losing element qualification here is fine.
4521 T = cast<ArrayType>(Ty)->getElementType();
4522 break;
4523 case Type::VariableArray: {
4524 // Losing element qualification here is fine.
4526
4527 // Unknown size indication requires no size computation.
4528 // Otherwise, evaluate and record it.
4529 auto Size = VAT->getSizeExpr();
4530 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4532 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4533
4534 T = VAT->getElementType();
4535 break;
4536 }
4537 case Type::FunctionProto:
4538 case Type::FunctionNoProto:
4539 T = cast<FunctionType>(Ty)->getReturnType();
4540 break;
4541 case Type::Paren:
4542 case Type::TypeOf:
4543 case Type::UnaryTransform:
4544 case Type::Attributed:
4545 case Type::BTFTagAttributed:
4546 case Type::HLSLAttributedResource:
4547 case Type::SubstTemplateTypeParm:
4548 case Type::MacroQualified:
4549 case Type::CountAttributed:
4550 // Keep walking after single level desugaring.
4551 T = T.getSingleStepDesugaredType(Context);
4552 break;
4553 case Type::Typedef:
4554 T = cast<TypedefType>(Ty)->desugar();
4555 break;
4556 case Type::Decltype:
4557 T = cast<DecltypeType>(Ty)->desugar();
4558 break;
4559 case Type::PackIndexing:
4560 T = cast<PackIndexingType>(Ty)->desugar();
4561 break;
4562 case Type::Using:
4563 T = cast<UsingType>(Ty)->desugar();
4564 break;
4565 case Type::Auto:
4566 case Type::DeducedTemplateSpecialization:
4567 T = cast<DeducedType>(Ty)->getDeducedType();
4568 break;
4569 case Type::TypeOfExpr:
4570 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4571 break;
4572 case Type::Atomic:
4573 T = cast<AtomicType>(Ty)->getValueType();
4574 break;
4575 case Type::PredefinedSugar:
4576 T = cast<PredefinedSugarType>(Ty)->desugar();
4577 break;
4578 }
4579 } while (!T.isNull() && T->isVariablyModifiedType());
4580}
4581
4583 SourceLocation OpLoc,
4584 SourceRange ExprRange,
4585 UnaryExprOrTypeTrait ExprKind,
4586 StringRef KWName) {
4587 if (ExprType->isDependentType())
4588 return false;
4589
4590 // C++ [expr.sizeof]p2:
4591 // When applied to a reference or a reference type, the result
4592 // is the size of the referenced type.
4593 // C++11 [expr.alignof]p3:
4594 // When alignof is applied to a reference type, the result
4595 // shall be the alignment of the referenced type.
4596 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4597 ExprType = Ref->getPointeeType();
4598
4599 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4600 // When alignof or _Alignof is applied to an array type, the result
4601 // is the alignment of the element type.
4602 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4603 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4604 // If the trait is 'alignof' in C before C2y, the ability to apply the
4605 // trait to an incomplete array is an extension.
4606 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4607 ExprType->isIncompleteArrayType())
4608 Diag(OpLoc, getLangOpts().C2y
4609 ? diag::warn_c2y_compat_alignof_incomplete_array
4610 : diag::ext_c2y_alignof_incomplete_array);
4611 ExprType = Context.getBaseElementType(ExprType);
4612 }
4613
4614 if (ExprKind == UETT_VecStep)
4615 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4616
4617 if (ExprKind == UETT_VectorElements)
4618 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4619 ExprRange);
4620
4621 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4622 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4623 ExprRange);
4624
4625 // Explicitly list some types as extensions.
4626 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4627 ExprKind))
4628 return false;
4629
4631 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4632 KWName, ExprRange))
4633 return true;
4634
4635 if (ExprType->isFunctionType()) {
4636 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4637 return true;
4638 }
4639
4640 if (ExprKind == UETT_CountOf) {
4641 // The type has to be an array type. We already checked for incomplete
4642 // types above.
4643 if (!ExprType->isArrayType()) {
4644 Diag(OpLoc, diag::err_countof_arg_not_array_type) << ExprType;
4645 return true;
4646 }
4647 }
4648
4649 // WebAssembly tables are always illegal operands to unary expressions and
4650 // type traits.
4651 if (Context.getTargetInfo().getTriple().isWasm() &&
4652 ExprType->isWebAssemblyTableType()) {
4653 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4654 << getTraitSpelling(ExprKind);
4655 return true;
4656 }
4657
4658 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4659 ExprKind))
4660 return true;
4661
4662 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4663 if (auto *TT = ExprType->getAs<TypedefType>()) {
4664 for (auto I = FunctionScopes.rbegin(),
4665 E = std::prev(FunctionScopes.rend());
4666 I != E; ++I) {
4667 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4668 if (CSI == nullptr)
4669 break;
4670 DeclContext *DC = nullptr;
4671 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4672 DC = LSI->CallOperator;
4673 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4674 DC = CRSI->TheCapturedDecl;
4675 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4676 DC = BSI->TheDecl;
4677 if (DC) {
4678 if (DC->containsDecl(TT->getDecl()))
4679 break;
4680 captureVariablyModifiedType(Context, ExprType, CSI);
4681 }
4682 }
4683 }
4684 }
4685
4686 return false;
4687}
4688
4690 SourceLocation OpLoc,
4691 UnaryExprOrTypeTrait ExprKind,
4692 SourceRange R) {
4693 if (!TInfo)
4694 return ExprError();
4695
4696 QualType T = TInfo->getType();
4697
4698 if (!T->isDependentType() &&
4699 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4700 getTraitSpelling(ExprKind)))
4701 return ExprError();
4702
4703 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4704 // properly deal with VLAs in nested calls of sizeof and typeof.
4705 if (currentEvaluationContext().isUnevaluated() &&
4706 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4707 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4708 TInfo->getType()->isVariablyModifiedType())
4709 TInfo = TransformToPotentiallyEvaluated(TInfo);
4710
4711 // It's possible that the transformation above failed.
4712 if (!TInfo)
4713 return ExprError();
4714
4715 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4716 return new (Context) UnaryExprOrTypeTraitExpr(
4717 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4718}
4719
4722 UnaryExprOrTypeTrait ExprKind) {
4724 if (PE.isInvalid())
4725 return ExprError();
4726
4727 E = PE.get();
4728
4729 // Verify that the operand is valid.
4730 bool isInvalid = false;
4731 if (E->isTypeDependent()) {
4732 // Delay type-checking for type-dependent expressions.
4733 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4734 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4735 } else if (ExprKind == UETT_VecStep) {
4737 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4738 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4739 isInvalid = true;
4740 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4741 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4742 isInvalid = true;
4743 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4744 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4746 }
4747
4748 if (isInvalid)
4749 return ExprError();
4750
4751 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4752 E->getType()->isVariableArrayType()) {
4754 if (PE.isInvalid()) return ExprError();
4755 E = PE.get();
4756 }
4757
4758 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4759 return new (Context) UnaryExprOrTypeTraitExpr(
4760 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4761}
4762
4765 UnaryExprOrTypeTrait ExprKind, bool IsType,
4766 void *TyOrEx, SourceRange ArgRange) {
4767 // If error parsing type, ignore.
4768 if (!TyOrEx) return ExprError();
4769
4770 if (IsType) {
4771 TypeSourceInfo *TInfo;
4772 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4773 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4774 }
4775
4776 Expr *ArgEx = (Expr *)TyOrEx;
4777 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4778 return Result;
4779}
4780
4782 SourceLocation OpLoc, SourceRange R) {
4783 if (!TInfo)
4784 return true;
4785 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4786 UETT_AlignOf, KWName);
4787}
4788
4790 SourceLocation OpLoc, SourceRange R) {
4791 TypeSourceInfo *TInfo;
4793 &TInfo);
4794 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4795}
4796
4798 bool IsReal) {
4799 if (V.get()->isTypeDependent())
4800 return S.Context.DependentTy;
4801
4802 // _Real and _Imag are only l-values for normal l-values.
4803 if (V.get()->getObjectKind() != OK_Ordinary) {
4804 V = S.DefaultLvalueConversion(V.get());
4805 if (V.isInvalid())
4806 return QualType();
4807 }
4808
4809 // These operators return the element type of a complex type.
4810 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4811 return CT->getElementType();
4812
4813 // Otherwise they pass through real integer and floating point types here.
4814 if (V.get()->getType()->isArithmeticType())
4815 return V.get()->getType();
4816
4817 // Test for placeholders.
4818 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4819 if (PR.isInvalid()) return QualType();
4820 if (PR.get() != V.get()) {
4821 V = PR;
4822 return CheckRealImagOperand(S, V, Loc, IsReal);
4823 }
4824
4825 // Reject anything else.
4826 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4827 << (IsReal ? "__real" : "__imag");
4828 return QualType();
4829}
4830
4831
4832
4835 tok::TokenKind Kind, Expr *Input) {
4837 switch (Kind) {
4838 default: llvm_unreachable("Unknown unary op!");
4839 case tok::plusplus: Opc = UO_PostInc; break;
4840 case tok::minusminus: Opc = UO_PostDec; break;
4841 }
4842
4843 // Since this might is a postfix expression, get rid of ParenListExprs.
4845 if (Result.isInvalid()) return ExprError();
4846 Input = Result.get();
4847
4848 return BuildUnaryOp(S, OpLoc, Opc, Input);
4849}
4850
4851/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4852///
4853/// \return true on error
4855 SourceLocation opLoc,
4856 Expr *op) {
4857 assert(op->getType()->isObjCObjectPointerType());
4859 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4860 return false;
4861
4862 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4864 << op->getSourceRange();
4865 return true;
4866}
4867
4869 auto *BaseNoParens = Base->IgnoreParens();
4870 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4871 return MSProp->getPropertyDecl()->getType()->isArrayType();
4872 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4873}
4874
4875// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4876// Typically this is DependentTy, but can sometimes be more precise.
4877//
4878// There are cases when we could determine a non-dependent type:
4879// - LHS and RHS may have non-dependent types despite being type-dependent
4880// (e.g. unbounded array static members of the current instantiation)
4881// - one may be a dependent-sized array with known element type
4882// - one may be a dependent-typed valid index (enum in current instantiation)
4883//
4884// We *always* return a dependent type, in such cases it is DependentTy.
4885// This avoids creating type-dependent expressions with non-dependent types.
4886// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4888 const ASTContext &Ctx) {
4889 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4890 QualType LTy = LHS->getType(), RTy = RHS->getType();
4891 QualType Result = Ctx.DependentTy;
4892 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4893 if (const PointerType *PT = LTy->getAs<PointerType>())
4894 Result = PT->getPointeeType();
4895 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4896 Result = AT->getElementType();
4897 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4898 if (const PointerType *PT = RTy->getAs<PointerType>())
4899 Result = PT->getPointeeType();
4900 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4901 Result = AT->getElementType();
4902 }
4903 // Ensure we return a dependent type.
4904 return Result->isDependentType() ? Result : Ctx.DependentTy;
4905}
4906
4908 SourceLocation lbLoc,
4909 MultiExprArg ArgExprs,
4910 SourceLocation rbLoc) {
4911
4912 if (base && !base->getType().isNull() &&
4913 base->hasPlaceholderType(BuiltinType::ArraySection)) {
4914 auto *AS = cast<ArraySectionExpr>(base);
4915 if (AS->isOMPArraySection())
4917 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
4918 /*Length*/ nullptr,
4919 /*Stride=*/nullptr, rbLoc);
4920
4921 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
4922 SourceLocation(), /*Length*/ nullptr,
4923 rbLoc);
4924 }
4925
4926 // Since this might be a postfix expression, get rid of ParenListExprs.
4927 if (isa<ParenListExpr>(base)) {
4929 if (result.isInvalid())
4930 return ExprError();
4931 base = result.get();
4932 }
4933
4934 // Check if base and idx form a MatrixSubscriptExpr.
4935 //
4936 // Helper to check for comma expressions, which are not allowed as indices for
4937 // matrix subscript expressions.
4938 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4939 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4940 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4941 << SourceRange(base->getBeginLoc(), rbLoc);
4942 return true;
4943 }
4944 return false;
4945 };
4946 // The matrix subscript operator ([][])is considered a single operator.
4947 // Separating the index expressions by parenthesis is not allowed.
4948 if (base && !base->getType().isNull() &&
4949 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4950 !isa<MatrixSubscriptExpr>(base)) {
4951 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4952 << SourceRange(base->getBeginLoc(), rbLoc);
4953 return ExprError();
4954 }
4955 // If the base is a MatrixSubscriptExpr, try to create a new
4956 // MatrixSubscriptExpr.
4957 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4958 if (matSubscriptE) {
4959 assert(ArgExprs.size() == 1);
4960 if (CheckAndReportCommaError(ArgExprs.front()))
4961 return ExprError();
4962
4963 assert(matSubscriptE->isIncomplete() &&
4964 "base has to be an incomplete matrix subscript");
4965 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4966 matSubscriptE->getRowIdx(),
4967 ArgExprs.front(), rbLoc);
4968 }
4969 if (base->getType()->isWebAssemblyTableType()) {
4970 Diag(base->getExprLoc(), diag::err_wasm_table_art)
4971 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
4972 return ExprError();
4973 }
4974
4975 CheckInvalidBuiltinCountedByRef(base,
4977
4978 // Handle any non-overload placeholder types in the base and index
4979 // expressions. We can't handle overloads here because the other
4980 // operand might be an overloadable type, in which case the overload
4981 // resolution for the operator overload should get the first crack
4982 // at the overload.
4983 bool IsMSPropertySubscript = false;
4984 if (base->getType()->isNonOverloadPlaceholderType()) {
4985 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4986 if (!IsMSPropertySubscript) {
4987 ExprResult result = CheckPlaceholderExpr(base);
4988 if (result.isInvalid())
4989 return ExprError();
4990 base = result.get();
4991 }
4992 }
4993
4994 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4995 if (base->getType()->isMatrixType()) {
4996 assert(ArgExprs.size() == 1);
4997 if (CheckAndReportCommaError(ArgExprs.front()))
4998 return ExprError();
4999
5000 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5001 rbLoc);
5002 }
5003
5004 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5005 Expr *idx = ArgExprs[0];
5006 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5008 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5009 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5010 << SourceRange(base->getBeginLoc(), rbLoc);
5011 }
5012 }
5013
5014 if (ArgExprs.size() == 1 &&
5015 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5016 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5017 if (result.isInvalid())
5018 return ExprError();
5019 ArgExprs[0] = result.get();
5020 } else {
5021 if (CheckArgsForPlaceholders(ArgExprs))
5022 return ExprError();
5023 }
5024
5025 // Build an unanalyzed expression if either operand is type-dependent.
5026 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5027 (base->isTypeDependent() ||
5029 !isa<PackExpansionExpr>(ArgExprs[0])) {
5030 return new (Context) ArraySubscriptExpr(
5031 base, ArgExprs.front(),
5032 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5033 VK_LValue, OK_Ordinary, rbLoc);
5034 }
5035
5036 // MSDN, property (C++)
5037 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5038 // This attribute can also be used in the declaration of an empty array in a
5039 // class or structure definition. For example:
5040 // __declspec(property(get=GetX, put=PutX)) int x[];
5041 // The above statement indicates that x[] can be used with one or more array
5042 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5043 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5044 if (IsMSPropertySubscript) {
5045 assert(ArgExprs.size() == 1);
5046 // Build MS property subscript expression if base is MS property reference
5047 // or MS property subscript.
5048 return new (Context)
5049 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5050 VK_LValue, OK_Ordinary, rbLoc);
5051 }
5052
5053 // Use C++ overloaded-operator rules if either operand has record
5054 // type. The spec says to do this if either type is *overloadable*,
5055 // but enum types can't declare subscript operators or conversion
5056 // operators, so there's nothing interesting for overload resolution
5057 // to do if there aren't any record types involved.
5058 //
5059 // ObjC pointers have their own subscripting logic that is not tied
5060 // to overload resolution and so should not take this path.
5062 ((base->getType()->isRecordType() ||
5063 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5064 ArgExprs[0]->getType()->isRecordType())))) {
5065 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5066 }
5067
5068 ExprResult Res =
5069 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5070
5071 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5072 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5073
5074 return Res;
5075}
5076
5079 InitializationKind Kind =
5081 InitializationSequence InitSeq(*this, Entity, Kind, E);
5082 return InitSeq.Perform(*this, Entity, Kind, E);
5083}
5084
5086 Expr *ColumnIdx,
5087 SourceLocation RBLoc) {
5089 if (BaseR.isInvalid())
5090 return BaseR;
5091 Base = BaseR.get();
5092
5093 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5094 if (RowR.isInvalid())
5095 return RowR;
5096 RowIdx = RowR.get();
5097
5098 if (!ColumnIdx)
5099 return new (Context) MatrixSubscriptExpr(
5100 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5101
5102 // Build an unanalyzed expression if any of the operands is type-dependent.
5103 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5104 ColumnIdx->isTypeDependent())
5105 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5106 Context.DependentTy, RBLoc);
5107
5108 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5109 if (ColumnR.isInvalid())
5110 return ColumnR;
5111 ColumnIdx = ColumnR.get();
5112
5113 // Check that IndexExpr is an integer expression. If it is a constant
5114 // expression, check that it is less than Dim (= the number of elements in the
5115 // corresponding dimension).
5116 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5117 bool IsColumnIdx) -> Expr * {
5118 if (!IndexExpr->getType()->isIntegerType() &&
5119 !IndexExpr->isTypeDependent()) {
5120 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5121 << IsColumnIdx;
5122 return nullptr;
5123 }
5124
5125 if (std::optional<llvm::APSInt> Idx =
5126 IndexExpr->getIntegerConstantExpr(Context)) {
5127 if ((*Idx < 0 || *Idx >= Dim)) {
5128 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5129 << IsColumnIdx << Dim;
5130 return nullptr;
5131 }
5132 }
5133
5134 ExprResult ConvExpr = IndexExpr;
5135 assert(!ConvExpr.isInvalid() &&
5136 "should be able to convert any integer type to size type");
5137 return ConvExpr.get();
5138 };
5139
5140 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5141 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5142 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5143 if (!RowIdx || !ColumnIdx)
5144 return ExprError();
5145
5146 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5147 MTy->getElementType(), RBLoc);
5148}
5149
5150void Sema::CheckAddressOfNoDeref(const Expr *E) {
5151 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5152 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5153
5154 // For expressions like `&(*s).b`, the base is recorded and what should be
5155 // checked.
5156 const MemberExpr *Member = nullptr;
5157 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5158 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5159
5160 LastRecord.PossibleDerefs.erase(StrippedExpr);
5161}
5162
5163void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5165 return;
5166
5167 QualType ResultTy = E->getType();
5168 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5169
5170 // Bail if the element is an array since it is not memory access.
5171 if (isa<ArrayType>(ResultTy))
5172 return;
5173
5174 if (ResultTy->hasAttr(attr::NoDeref)) {
5175 LastRecord.PossibleDerefs.insert(E);
5176 return;
5177 }
5178
5179 // Check if the base type is a pointer to a member access of a struct
5180 // marked with noderef.
5181 const Expr *Base = E->getBase();
5182 QualType BaseTy = Base->getType();
5183 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5184 // Not a pointer access
5185 return;
5186
5187 const MemberExpr *Member = nullptr;
5188 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5189 Member->isArrow())
5190 Base = Member->getBase();
5191
5192 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5193 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5194 LastRecord.PossibleDerefs.insert(E);
5195 }
5196}
5197
5200 Expr *Idx, SourceLocation RLoc) {
5201 Expr *LHSExp = Base;
5202 Expr *RHSExp = Idx;
5203
5206
5207 // Per C++ core issue 1213, the result is an xvalue if either operand is
5208 // a non-lvalue array, and an lvalue otherwise.
5209 if (getLangOpts().CPlusPlus11) {
5210 for (auto *Op : {LHSExp, RHSExp}) {
5211 Op = Op->IgnoreImplicit();
5212 if (Op->getType()->isArrayType() && !Op->isLValue())
5213 VK = VK_XValue;
5214 }
5215 }
5216
5217 // Perform default conversions.
5218 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5220 if (Result.isInvalid())
5221 return ExprError();
5222 LHSExp = Result.get();
5223 }
5225 if (Result.isInvalid())
5226 return ExprError();
5227 RHSExp = Result.get();
5228
5229 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5230
5231 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5232 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5233 // in the subscript position. As a result, we need to derive the array base
5234 // and index from the expression types.
5235 Expr *BaseExpr, *IndexExpr;
5236 QualType ResultType;
5237 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5238 BaseExpr = LHSExp;
5239 IndexExpr = RHSExp;
5240 ResultType =
5242 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5243 BaseExpr = LHSExp;
5244 IndexExpr = RHSExp;
5245 ResultType = PTy->getPointeeType();
5246 } else if (const ObjCObjectPointerType *PTy =
5247 LHSTy->getAs<ObjCObjectPointerType>()) {
5248 BaseExpr = LHSExp;
5249 IndexExpr = RHSExp;
5250
5251 // Use custom logic if this should be the pseudo-object subscript
5252 // expression.
5253 if (!LangOpts.isSubscriptPointerArithmetic())
5254 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5255 nullptr, nullptr);
5256
5257 ResultType = PTy->getPointeeType();
5258 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5259 // Handle the uncommon case of "123[Ptr]".
5260 BaseExpr = RHSExp;
5261 IndexExpr = LHSExp;
5262 ResultType = PTy->getPointeeType();
5263 } else if (const ObjCObjectPointerType *PTy =
5264 RHSTy->getAs<ObjCObjectPointerType>()) {
5265 // Handle the uncommon case of "123[Ptr]".
5266 BaseExpr = RHSExp;
5267 IndexExpr = LHSExp;
5268 ResultType = PTy->getPointeeType();
5269 if (!LangOpts.isSubscriptPointerArithmetic()) {
5270 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5271 << ResultType << BaseExpr->getSourceRange();
5272 return ExprError();
5273 }
5274 } else if (LHSTy->isSubscriptableVectorType()) {
5275 if (LHSTy->isBuiltinType() &&
5276 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5277 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5278 if (BTy->isSVEBool())
5279 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5280 << LHSExp->getSourceRange()
5281 << RHSExp->getSourceRange());
5282 ResultType = BTy->getSveEltType(Context);
5283 } else {
5284 const VectorType *VTy = LHSTy->getAs<VectorType>();
5285 ResultType = VTy->getElementType();
5286 }
5287 BaseExpr = LHSExp; // vectors: V[123]
5288 IndexExpr = RHSExp;
5289 // We apply C++ DR1213 to vector subscripting too.
5290 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5291 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5292 if (Materialized.isInvalid())
5293 return ExprError();
5294 LHSExp = Materialized.get();
5295 }
5296 VK = LHSExp->getValueKind();
5297 if (VK != VK_PRValue)
5298 OK = OK_VectorComponent;
5299
5300 QualType BaseType = BaseExpr->getType();
5301 Qualifiers BaseQuals = BaseType.getQualifiers();
5302 Qualifiers MemberQuals = ResultType.getQualifiers();
5303 Qualifiers Combined = BaseQuals + MemberQuals;
5304 if (Combined != MemberQuals)
5305 ResultType = Context.getQualifiedType(ResultType, Combined);
5306 } else if (LHSTy->isArrayType()) {
5307 // If we see an array that wasn't promoted by
5308 // DefaultFunctionArrayLvalueConversion, it must be an array that
5309 // wasn't promoted because of the C90 rule that doesn't
5310 // allow promoting non-lvalue arrays. Warn, then
5311 // force the promotion here.
5312 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5313 << LHSExp->getSourceRange();
5314 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5315 CK_ArrayToPointerDecay).get();
5316 LHSTy = LHSExp->getType();
5317
5318 BaseExpr = LHSExp;
5319 IndexExpr = RHSExp;
5320 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5321 } else if (RHSTy->isArrayType()) {
5322 // Same as previous, except for 123[f().a] case
5323 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5324 << RHSExp->getSourceRange();
5325 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5326 CK_ArrayToPointerDecay).get();
5327 RHSTy = RHSExp->getType();
5328
5329 BaseExpr = RHSExp;
5330 IndexExpr = LHSExp;
5331 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5332 } else {
5333 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5334 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5335 }
5336 // C99 6.5.2.1p1
5337 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5338 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5339 << IndexExpr->getSourceRange());
5340
5341 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5342 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5343 !IndexExpr->isTypeDependent()) {
5344 std::optional<llvm::APSInt> IntegerContantExpr =
5346 if (!IntegerContantExpr.has_value() ||
5347 IntegerContantExpr.value().isNegative())
5348 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5349 }
5350
5351 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5352 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5353 // type. Note that Functions are not objects, and that (in C99 parlance)
5354 // incomplete types are not object types.
5355 if (ResultType->isFunctionType()) {
5356 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5357 << ResultType << BaseExpr->getSourceRange();
5358 return ExprError();
5359 }
5360
5361 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5362 // GNU extension: subscripting on pointer to void
5363 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5364 << BaseExpr->getSourceRange();
5365
5366 // C forbids expressions of unqualified void type from being l-values.
5367 // See IsCForbiddenLValueType.
5368 if (!ResultType.hasQualifiers())
5369 VK = VK_PRValue;
5370 } else if (!ResultType->isDependentType() &&
5371 !ResultType.isWebAssemblyReferenceType() &&
5373 LLoc, ResultType,
5374 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5375 return ExprError();
5376
5377 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5378 !ResultType.isCForbiddenLValueType());
5379
5381 FunctionScopes.size() > 1) {
5382 if (auto *TT =
5383 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5384 for (auto I = FunctionScopes.rbegin(),
5385 E = std::prev(FunctionScopes.rend());
5386 I != E; ++I) {
5387 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5388 if (CSI == nullptr)
5389 break;
5390 DeclContext *DC = nullptr;
5391 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5392 DC = LSI->CallOperator;
5393 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5394 DC = CRSI->TheCapturedDecl;
5395 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5396 DC = BSI->TheDecl;
5397 if (DC) {
5398 if (DC->containsDecl(TT->getDecl()))
5399 break;
5401 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5402 }
5403 }
5404 }
5405 }
5406
5407 return new (Context)
5408 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5409}
5410
5412 ParmVarDecl *Param, Expr *RewrittenInit,
5413 bool SkipImmediateInvocations) {
5414 if (Param->hasUnparsedDefaultArg()) {
5415 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5416 // If we've already cleared out the location for the default argument,
5417 // that means we're parsing it right now.
5418 if (!UnparsedDefaultArgLocs.count(Param)) {
5419 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5420 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5421 Param->setInvalidDecl();
5422 return true;
5423 }
5424
5425 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5426 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5428 diag::note_default_argument_declared_here);
5429 return true;
5430 }
5431
5432 if (Param->hasUninstantiatedDefaultArg()) {
5433 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5434 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5435 return true;
5436 }
5437
5438 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5439 assert(Init && "default argument but no initializer?");
5440
5441 // If the default expression creates temporaries, we need to
5442 // push them to the current stack of expression temporaries so they'll
5443 // be properly destroyed.
5444 // FIXME: We should really be rebuilding the default argument with new
5445 // bound temporaries; see the comment in PR5810.
5446 // We don't need to do that with block decls, though, because
5447 // blocks in default argument expression can never capture anything.
5448 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5449 // Set the "needs cleanups" bit regardless of whether there are
5450 // any explicit objects.
5451 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5452 // Append all the objects to the cleanup list. Right now, this
5453 // should always be a no-op, because blocks in default argument
5454 // expressions should never be able to capture anything.
5455 assert(!InitWithCleanup->getNumObjects() &&
5456 "default argument expression has capturing blocks?");
5457 }
5458 // C++ [expr.const]p15.1:
5459 // An expression or conversion is in an immediate function context if it is
5460 // potentially evaluated and [...] its innermost enclosing non-block scope
5461 // is a function parameter scope of an immediate function.
5463 *this,
5467 Param);
5468 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5469 SkipImmediateInvocations;
5470 runWithSufficientStackSpace(CallLoc, [&] {
5471 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5472 });
5473 return false;
5474}
5475
5480 }
5481
5482 bool HasImmediateCalls = false;
5483
5484 bool VisitCallExpr(CallExpr *E) override {
5485 if (const FunctionDecl *FD = E->getDirectCallee())
5486 HasImmediateCalls |= FD->isImmediateFunction();
5488 }
5489
5491 if (const FunctionDecl *FD = E->getConstructor())
5492 HasImmediateCalls |= FD->isImmediateFunction();
5494 }
5495
5496 // SourceLocExpr are not immediate invocations
5497 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5498 // need to be rebuilt so that they refer to the correct SourceLocation and
5499 // DeclContext.
5501 HasImmediateCalls = true;
5503 }
5504
5505 // A nested lambda might have parameters with immediate invocations
5506 // in their default arguments.
5507 // The compound statement is not visited (as it does not constitute a
5508 // subexpression).
5509 // FIXME: We should consider visiting and transforming captures
5510 // with init expressions.
5511 bool VisitLambdaExpr(LambdaExpr *E) override {
5512 return VisitCXXMethodDecl(E->getCallOperator());
5513 }
5514
5516 return TraverseStmt(E->getExpr());
5517 }
5518
5520 return TraverseStmt(E->getExpr());
5521 }
5522};
5523
5525 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5528
5529 bool AlwaysRebuild() { return true; }
5530
5531 // Lambda can only have immediate invocations in the default
5532 // args of their parameters, which is transformed upon calling the closure.
5533 // The body is not a subexpression, so we have nothing to do.
5534 // FIXME: Immediate calls in capture initializers should be transformed.
5537
5538 // Make sure we don't rebuild the this pointer as it would
5539 // cause it to incorrectly point it to the outermost class
5540 // in the case of nested struct initialization.
5542
5543 // Rewrite to source location to refer to the context in which they are used.
5545 DeclContext *DC = E->getParentContext();
5546 if (DC == SemaRef.CurContext)
5547 return E;
5548
5549 // FIXME: During instantiation, because the rebuild of defaults arguments
5550 // is not always done in the context of the template instantiator,
5551 // we run the risk of producing a dependent source location
5552 // that would never be rebuilt.
5553 // This usually happens during overload resolution, or in contexts
5554 // where the value of the source location does not matter.
5555 // However, we should find a better way to deal with source location
5556 // of function templates.
5557 if (!SemaRef.CurrentInstantiationScope ||
5558 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5559 DC = SemaRef.CurContext;
5560
5561 return getDerived().RebuildSourceLocExpr(
5562 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5563 }
5564};
5565
5567 FunctionDecl *FD, ParmVarDecl *Param,
5568 Expr *Init) {
5569 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5570
5571 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5572 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5573 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5574 InitializationContext =
5576 if (!InitializationContext.has_value())
5577 InitializationContext.emplace(CallLoc, Param, CurContext);
5578
5579 if (!Init && !Param->hasUnparsedDefaultArg()) {
5580 // Mark that we are replacing a default argument first.
5581 // If we are instantiating a template we won't have to
5582 // retransform immediate calls.
5583 // C++ [expr.const]p15.1:
5584 // An expression or conversion is in an immediate function context if it
5585 // is potentially evaluated and [...] its innermost enclosing non-block
5586 // scope is a function parameter scope of an immediate function.
5588 *this,
5592 Param);
5593
5594 if (Param->hasUninstantiatedDefaultArg()) {
5595 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5596 return ExprError();
5597 }
5598 // CWG2631
5599 // An immediate invocation that is not evaluated where it appears is
5600 // evaluated and checked for whether it is a constant expression at the
5601 // point where the enclosing initializer is used in a function call.
5603 if (!NestedDefaultChecking)
5604 V.TraverseDecl(Param);
5605
5606 // Rewrite the call argument that was created from the corresponding
5607 // parameter's default argument.
5608 if (V.HasImmediateCalls ||
5609 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5610 if (V.HasImmediateCalls)
5611 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5612 CallLoc, Param, CurContext};
5613 // Pass down lifetime extending flag, and collect temporaries in
5614 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5618 ExprResult Res;
5619 runWithSufficientStackSpace(CallLoc, [&] {
5620 Res = Immediate.TransformInitializer(Param->getInit(),
5621 /*NotCopy=*/false);
5622 });
5623 if (Res.isInvalid())
5624 return ExprError();
5625 Res = ConvertParamDefaultArgument(Param, Res.get(),
5626 Res.get()->getBeginLoc());
5627 if (Res.isInvalid())
5628 return ExprError();
5629 Init = Res.get();
5630 }
5631 }
5632
5634 CallLoc, FD, Param, Init,
5635 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5636 return ExprError();
5637
5638 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5639 Init, InitializationContext->Context);
5640}
5641
5643 FieldDecl *Field) {
5644 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5645 return Pattern;
5646 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5647 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5649 ClassPattern->lookup(Field->getDeclName());
5650 auto Rng = llvm::make_filter_range(
5651 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5652 if (Rng.empty())
5653 return nullptr;
5654 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5655 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5656 // && "Duplicated instantiation pattern for field decl");
5657 return cast<FieldDecl>(*Rng.begin());
5658}
5659
5661 assert(Field->hasInClassInitializer());
5662
5663 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5664
5665 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5666
5667 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5668 InitializationContext =
5670 if (!InitializationContext.has_value())
5671 InitializationContext.emplace(Loc, Field, CurContext);
5672
5673 Expr *Init = nullptr;
5674
5675 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5676 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5679
5680 if (!Field->getInClassInitializer()) {
5681 // Maybe we haven't instantiated the in-class initializer. Go check the
5682 // pattern FieldDecl to see if it has one.
5683 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5684 FieldDecl *Pattern =
5686 assert(Pattern && "We must have set the Pattern!");
5687 if (!Pattern->hasInClassInitializer() ||
5688 InstantiateInClassInitializer(Loc, Field, Pattern,
5690 Field->setInvalidDecl();
5691 return ExprError();
5692 }
5693 }
5694 }
5695
5696 // CWG2631
5697 // An immediate invocation that is not evaluated where it appears is
5698 // evaluated and checked for whether it is a constant expression at the
5699 // point where the enclosing initializer is used in a [...] a constructor
5700 // definition, or an aggregate initialization.
5702 if (!NestedDefaultChecking)
5703 V.TraverseDecl(Field);
5704
5705 // CWG1815
5706 // Support lifetime extension of temporary created by aggregate
5707 // initialization using a default member initializer. We should rebuild
5708 // the initializer in a lifetime extension context if the initializer
5709 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5710 // extension code recurses into the default initializer and does lifetime
5711 // extension when warranted.
5712 bool ContainsAnyTemporaries =
5713 isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());
5714 if (Field->getInClassInitializer() &&
5715 !Field->getInClassInitializer()->containsErrors() &&
5716 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5717 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5718 CurContext};
5719 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5720 NestedDefaultChecking;
5721 // Pass down lifetime extending flag, and collect temporaries in
5722 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5726 ExprResult Res;
5728 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5729 /*CXXDirectInit=*/false);
5730 });
5731 if (!Res.isInvalid())
5732 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5733 if (Res.isInvalid()) {
5734 Field->setInvalidDecl();
5735 return ExprError();
5736 }
5737 Init = Res.get();
5738 }
5739
5740 if (Field->getInClassInitializer()) {
5741 Expr *E = Init ? Init : Field->getInClassInitializer();
5742 if (!NestedDefaultChecking)
5744 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5745 });
5748 // C++11 [class.base.init]p7:
5749 // The initialization of each base and member constitutes a
5750 // full-expression.
5751 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5752 if (Res.isInvalid()) {
5753 Field->setInvalidDecl();
5754 return ExprError();
5755 }
5756 Init = Res.get();
5757
5758 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5759 Field, InitializationContext->Context,
5760 Init);
5761 }
5762
5763 // DR1351:
5764 // If the brace-or-equal-initializer of a non-static data member
5765 // invokes a defaulted default constructor of its class or of an
5766 // enclosing class in a potentially evaluated subexpression, the
5767 // program is ill-formed.
5768 //
5769 // This resolution is unworkable: the exception specification of the
5770 // default constructor can be needed in an unevaluated context, in
5771 // particular, in the operand of a noexcept-expression, and we can be
5772 // unable to compute an exception specification for an enclosed class.
5773 //
5774 // Any attempt to resolve the exception specification of a defaulted default
5775 // constructor before the initializer is lexically complete will ultimately
5776 // come here at which point we can diagnose it.
5777 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5778 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5779 << OutermostClass << Field;
5780 Diag(Field->getEndLoc(),
5781 diag::note_default_member_initializer_not_yet_parsed);
5782 // Recover by marking the field invalid, unless we're in a SFINAE context.
5783 if (!isSFINAEContext())
5784 Field->setInvalidDecl();
5785 return ExprError();
5786}
5787
5789 const FunctionProtoType *Proto,
5790 Expr *Fn) {
5791 if (Proto && Proto->isVariadic()) {
5792 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5794 else if (Fn && Fn->getType()->isBlockPointerType())
5796 else if (FDecl) {
5797 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5798 if (Method->isInstance())
5800 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5803 }
5805}
5806
5807namespace {
5808class FunctionCallCCC final : public FunctionCallFilterCCC {
5809public:
5810 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5811 unsigned NumArgs, MemberExpr *ME)
5812 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5813 FunctionName(FuncName) {}
5814
5815 bool ValidateCandidate(const TypoCorrection &candidate) override {
5816 if (!candidate.getCorrectionSpecifier() ||
5817 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5818 return false;
5819 }
5820
5822 }
5823
5824 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5825 return std::make_unique<FunctionCallCCC>(*this);
5826 }
5827
5828private:
5829 const IdentifierInfo *const FunctionName;
5830};
5831}
5832
5834 FunctionDecl *FDecl,
5835 ArrayRef<Expr *> Args) {
5836 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5837 DeclarationName FuncName = FDecl->getDeclName();
5838 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5839
5840 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5841 if (TypoCorrection Corrected = S.CorrectTypo(
5843 S.getScopeForContext(S.CurContext), nullptr, CCC,
5845 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5846 if (Corrected.isOverloaded()) {
5849 for (NamedDecl *CD : Corrected) {
5850 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5852 OCS);
5853 }
5854 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5855 case OR_Success:
5856 ND = Best->FoundDecl;
5857 Corrected.setCorrectionDecl(ND);
5858 break;
5859 default:
5860 break;
5861 }
5862 }
5863 ND = ND->getUnderlyingDecl();
5865 return Corrected;
5866 }
5867 }
5868 return TypoCorrection();
5869}
5870
5871// [C++26][[expr.unary.op]/p4
5872// A pointer to member is only formed when an explicit &
5873// is used and its operand is a qualified-id not enclosed in parentheses.
5875 if (!isa<ParenExpr>(Fn))
5876 return false;
5877
5878 Fn = Fn->IgnoreParens();
5879
5880 auto *UO = dyn_cast<UnaryOperator>(Fn);
5881 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
5882 return false;
5883 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
5884 return DRE->hasQualifier();
5885 }
5886 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
5887 return bool(OVL->getQualifier());
5888 return false;
5889}
5890
5891bool
5893 FunctionDecl *FDecl,
5894 const FunctionProtoType *Proto,
5895 ArrayRef<Expr *> Args,
5896 SourceLocation RParenLoc,
5897 bool IsExecConfig) {
5898 // Bail out early if calling a builtin with custom typechecking.
5899 if (FDecl)
5900 if (unsigned ID = FDecl->getBuiltinID())
5901 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
5902 return false;
5903
5904 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5905 // assignment, to the types of the corresponding parameter, ...
5906
5907 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
5908 bool HasExplicitObjectParameter =
5909 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
5910 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
5911 unsigned NumParams = Proto->getNumParams();
5912 bool Invalid = false;
5913 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5914 unsigned FnKind = Fn->getType()->isBlockPointerType()
5915 ? 1 /* block */
5916 : (IsExecConfig ? 3 /* kernel function (exec config) */
5917 : 0 /* function */);
5918
5919 // If too few arguments are available (and we don't have default
5920 // arguments for the remaining parameters), don't make the call.
5921 if (Args.size() < NumParams) {
5922 if (Args.size() < MinArgs) {
5923 TypoCorrection TC;
5924 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5925 unsigned diag_id =
5926 MinArgs == NumParams && !Proto->isVariadic()
5927 ? diag::err_typecheck_call_too_few_args_suggest
5928 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5930 TC, PDiag(diag_id)
5931 << FnKind << MinArgs - ExplicitObjectParameterOffset
5932 << static_cast<unsigned>(Args.size()) -
5933 ExplicitObjectParameterOffset
5934 << HasExplicitObjectParameter << TC.getCorrectionRange());
5935 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
5936 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5937 ->getDeclName())
5938 Diag(RParenLoc,
5939 MinArgs == NumParams && !Proto->isVariadic()
5940 ? diag::err_typecheck_call_too_few_args_one
5941 : diag::err_typecheck_call_too_few_args_at_least_one)
5942 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5943 << HasExplicitObjectParameter << Fn->getSourceRange();
5944 else
5945 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5946 ? diag::err_typecheck_call_too_few_args
5947 : diag::err_typecheck_call_too_few_args_at_least)
5948 << FnKind << MinArgs - ExplicitObjectParameterOffset
5949 << static_cast<unsigned>(Args.size()) -
5950 ExplicitObjectParameterOffset
5951 << HasExplicitObjectParameter << Fn->getSourceRange();
5952
5953 // Emit the location of the prototype.
5954 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5955 Diag(FDecl->getLocation(), diag::note_callee_decl)
5956 << FDecl << FDecl->getParametersSourceRange();
5957
5958 return true;
5959 }
5960 // We reserve space for the default arguments when we create
5961 // the call expression, before calling ConvertArgumentsForCall.
5962 assert((Call->getNumArgs() == NumParams) &&
5963 "We should have reserved space for the default arguments before!");
5964 }
5965
5966 // If too many are passed and not variadic, error on the extras and drop
5967 // them.
5968 if (Args.size() > NumParams) {
5969 if (!Proto->isVariadic()) {
5970 TypoCorrection TC;
5971 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5972 unsigned diag_id =
5973 MinArgs == NumParams && !Proto->isVariadic()
5974 ? diag::err_typecheck_call_too_many_args_suggest
5975 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5977 TC, PDiag(diag_id)
5978 << FnKind << NumParams - ExplicitObjectParameterOffset
5979 << static_cast<unsigned>(Args.size()) -
5980 ExplicitObjectParameterOffset
5981 << HasExplicitObjectParameter << TC.getCorrectionRange());
5982 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
5983 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5984 ->getDeclName())
5985 Diag(Args[NumParams]->getBeginLoc(),
5986 MinArgs == NumParams
5987 ? diag::err_typecheck_call_too_many_args_one
5988 : diag::err_typecheck_call_too_many_args_at_most_one)
5989 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5990 << static_cast<unsigned>(Args.size()) -
5991 ExplicitObjectParameterOffset
5992 << HasExplicitObjectParameter << Fn->getSourceRange()
5993 << SourceRange(Args[NumParams]->getBeginLoc(),
5994 Args.back()->getEndLoc());
5995 else
5996 Diag(Args[NumParams]->getBeginLoc(),
5997 MinArgs == NumParams
5998 ? diag::err_typecheck_call_too_many_args
5999 : diag::err_typecheck_call_too_many_args_at_most)
6000 << FnKind << NumParams - ExplicitObjectParameterOffset
6001 << static_cast<unsigned>(Args.size()) -
6002 ExplicitObjectParameterOffset
6003 << HasExplicitObjectParameter << Fn->getSourceRange()
6004 << SourceRange(Args[NumParams]->getBeginLoc(),
6005 Args.back()->getEndLoc());
6006
6007 // Emit the location of the prototype.
6008 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6009 Diag(FDecl->getLocation(), diag::note_callee_decl)
6010 << FDecl << FDecl->getParametersSourceRange();
6011
6012 // This deletes the extra arguments.
6013 Call->shrinkNumArgs(NumParams);
6014 return true;
6015 }
6016 }
6017 SmallVector<Expr *, 8> AllArgs;
6018 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6019
6020 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
6021 AllArgs, CallType);
6022 if (Invalid)
6023 return true;
6024 unsigned TotalNumArgs = AllArgs.size();
6025 for (unsigned i = 0; i < TotalNumArgs; ++i)
6026 Call->setArg(i, AllArgs[i]);
6027
6028 Call->computeDependence();
6029 return false;
6030}
6031
6033 const FunctionProtoType *Proto,
6034 unsigned FirstParam, ArrayRef<Expr *> Args,
6035 SmallVectorImpl<Expr *> &AllArgs,
6036 VariadicCallType CallType, bool AllowExplicit,
6037 bool IsListInitialization) {
6038 unsigned NumParams = Proto->getNumParams();
6039 bool Invalid = false;
6040 size_t ArgIx = 0;
6041 // Continue to check argument types (even if we have too few/many args).
6042 for (unsigned i = FirstParam; i < NumParams; i++) {
6043 QualType ProtoArgType = Proto->getParamType(i);
6044
6045 Expr *Arg;
6046 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6047 if (ArgIx < Args.size()) {
6048 Arg = Args[ArgIx++];
6049
6050 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6051 diag::err_call_incomplete_argument, Arg))
6052 return true;
6053
6054 // Strip the unbridged-cast placeholder expression off, if applicable.
6055 bool CFAudited = false;
6056 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6057 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6058 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6059 Arg = ObjC().stripARCUnbridgedCast(Arg);
6060 else if (getLangOpts().ObjCAutoRefCount &&
6061 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6062 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6063 CFAudited = true;
6064
6065 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6066 ProtoArgType->isBlockPointerType())
6067 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6068 BE->getBlockDecl()->setDoesNotEscape();
6069 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
6071 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6072 if (ArgExpr.isInvalid())
6073 return true;
6074 Arg = ArgExpr.getAs<Expr>();
6075 }
6076
6077 InitializedEntity Entity =
6079 ProtoArgType)
6081 Context, ProtoArgType, Proto->isParamConsumed(i));
6082
6083 // Remember that parameter belongs to a CF audited API.
6084 if (CFAudited)
6085 Entity.setParameterCFAudited();
6086
6088 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6089 if (ArgE.isInvalid())
6090 return true;
6091
6092 Arg = ArgE.getAs<Expr>();
6093 } else {
6094 assert(Param && "can't use default arguments without a known callee");
6095
6096 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6097 if (ArgExpr.isInvalid())
6098 return true;
6099
6100 Arg = ArgExpr.getAs<Expr>();
6101 }
6102
6103 // Check for array bounds violations for each argument to the call. This
6104 // check only triggers warnings when the argument isn't a more complex Expr
6105 // with its own checking, such as a BinaryOperator.
6106 CheckArrayAccess(Arg);
6107
6108 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6109 CheckStaticArrayArgument(CallLoc, Param, Arg);
6110
6111 AllArgs.push_back(Arg);
6112 }
6113
6114 // If this is a variadic call, handle args passed through "...".
6115 if (CallType != VariadicCallType::DoesNotApply) {
6116 // Assume that extern "C" functions with variadic arguments that
6117 // return __unknown_anytype aren't *really* variadic.
6118 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6119 FDecl->isExternC()) {
6120 for (Expr *A : Args.slice(ArgIx)) {
6121 QualType paramType; // ignored
6122 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6123 Invalid |= arg.isInvalid();
6124 AllArgs.push_back(arg.get());
6125 }
6126
6127 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6128 } else {
6129 for (Expr *A : Args.slice(ArgIx)) {
6130 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6131 Invalid |= Arg.isInvalid();
6132 AllArgs.push_back(Arg.get());
6133 }
6134 }
6135
6136 // Check for array bounds violations.
6137 for (Expr *A : Args.slice(ArgIx))
6138 CheckArrayAccess(A);
6139 }
6140 return Invalid;
6141}
6142
6144 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6145 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6146 TL = DTL.getOriginalLoc();
6147 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6148 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6149 << ATL.getLocalSourceRange();
6150}
6151
6152void
6154 ParmVarDecl *Param,
6155 const Expr *ArgExpr) {
6156 // Static array parameters are not supported in C++.
6157 if (!Param || getLangOpts().CPlusPlus)
6158 return;
6159
6160 QualType OrigTy = Param->getOriginalType();
6161
6162 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6163 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6164 return;
6165
6166 if (ArgExpr->isNullPointerConstant(Context,
6168 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6169 DiagnoseCalleeStaticArrayParam(*this, Param);
6170 return;
6171 }
6172
6173 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6174 if (!CAT)
6175 return;
6176
6177 const ConstantArrayType *ArgCAT =
6178 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6179 if (!ArgCAT)
6180 return;
6181
6182 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6183 ArgCAT->getElementType())) {
6184 if (ArgCAT->getSize().ult(CAT->getSize())) {
6185 Diag(CallLoc, diag::warn_static_array_too_small)
6186 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6187 << (unsigned)CAT->getZExtSize() << 0;
6188 DiagnoseCalleeStaticArrayParam(*this, Param);
6189 }
6190 return;
6191 }
6192
6193 std::optional<CharUnits> ArgSize =
6195 std::optional<CharUnits> ParmSize =
6197 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6198 Diag(CallLoc, diag::warn_static_array_too_small)
6199 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6200 << (unsigned)ParmSize->getQuantity() << 1;
6201 DiagnoseCalleeStaticArrayParam(*this, Param);
6202 }
6203}
6204
6205/// Given a function expression of unknown-any type, try to rebuild it
6206/// to have a function type.
6208
6209/// Is the given type a placeholder that we need to lower out
6210/// immediately during argument processing?
6212 // Placeholders are never sugared.
6213 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6214 if (!placeholder) return false;
6215
6216 switch (placeholder->getKind()) {
6217 // Ignore all the non-placeholder types.
6218#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6219 case BuiltinType::Id:
6220#include "clang/Basic/OpenCLImageTypes.def"
6221#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6222 case BuiltinType::Id:
6223#include "clang/Basic/OpenCLExtensionTypes.def"
6224 // In practice we'll never use this, since all SVE types are sugared
6225 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6226#define SVE_TYPE(Name, Id, SingletonId) \
6227 case BuiltinType::Id:
6228#include "clang/Basic/AArch64ACLETypes.def"
6229#define PPC_VECTOR_TYPE(Name, Id, Size) \
6230 case BuiltinType::Id:
6231#include "clang/Basic/PPCTypes.def"
6232#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6233#include "clang/Basic/RISCVVTypes.def"
6234#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6235#include "clang/Basic/WebAssemblyReferenceTypes.def"
6236#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6237#include "clang/Basic/AMDGPUTypes.def"
6238#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6239#include "clang/Basic/HLSLIntangibleTypes.def"
6240#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6241#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6242#include "clang/AST/BuiltinTypes.def"
6243 return false;
6244
6245 case BuiltinType::UnresolvedTemplate:
6246 // We cannot lower out overload sets; they might validly be resolved
6247 // by the call machinery.
6248 case BuiltinType::Overload:
6249 return false;
6250
6251 // Unbridged casts in ARC can be handled in some call positions and
6252 // should be left in place.
6253 case BuiltinType::ARCUnbridgedCast:
6254 return false;
6255
6256 // Pseudo-objects should be converted as soon as possible.
6257 case BuiltinType::PseudoObject:
6258 return true;
6259
6260 // The debugger mode could theoretically but currently does not try
6261 // to resolve unknown-typed arguments based on known parameter types.
6262 case BuiltinType::UnknownAny:
6263 return true;
6264
6265 // These are always invalid as call arguments and should be reported.
6266 case BuiltinType::BoundMember:
6267 case BuiltinType::BuiltinFn:
6268 case BuiltinType::IncompleteMatrixIdx:
6269 case BuiltinType::ArraySection:
6270 case BuiltinType::OMPArrayShaping:
6271 case BuiltinType::OMPIterator:
6272 return true;
6273
6274 }
6275 llvm_unreachable("bad builtin type kind");
6276}
6277
6279 // Apply this processing to all the arguments at once instead of
6280 // dying at the first failure.
6281 bool hasInvalid = false;
6282 for (size_t i = 0, e = args.size(); i != e; i++) {
6283 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6284 ExprResult result = CheckPlaceholderExpr(args[i]);
6285 if (result.isInvalid()) hasInvalid = true;
6286 else args[i] = result.get();
6287 }
6288 }
6289 return hasInvalid;
6290}
6291
6292/// If a builtin function has a pointer argument with no explicit address
6293/// space, then it should be able to accept a pointer to any address
6294/// space as input. In order to do this, we need to replace the
6295/// standard builtin declaration with one that uses the same address space
6296/// as the call.
6297///
6298/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6299/// it does not contain any pointer arguments without
6300/// an address space qualifer. Otherwise the rewritten
6301/// FunctionDecl is returned.
6302/// TODO: Handle pointer return types.
6304 FunctionDecl *FDecl,
6305 MultiExprArg ArgExprs) {
6306
6307 QualType DeclType = FDecl->getType();
6308 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6309
6310 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6311 ArgExprs.size() < FT->getNumParams())
6312 return nullptr;
6313
6314 bool NeedsNewDecl = false;
6315 unsigned i = 0;
6316 SmallVector<QualType, 8> OverloadParams;
6317
6318 {
6319 // The lvalue conversions in this loop are only for type resolution and
6320 // don't actually occur.
6323 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6324
6325 for (QualType ParamType : FT->param_types()) {
6326
6327 // Convert array arguments to pointer to simplify type lookup.
6328 ExprResult ArgRes =
6330 if (ArgRes.isInvalid())
6331 return nullptr;
6332 Expr *Arg = ArgRes.get();
6333 QualType ArgType = Arg->getType();
6334 if (!ParamType->isPointerType() ||
6335 ParamType->getPointeeType().hasAddressSpace() ||
6336 !ArgType->isPointerType() ||
6337 !ArgType->getPointeeType().hasAddressSpace() ||
6338 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6339 OverloadParams.push_back(ParamType);
6340 continue;
6341 }
6342
6343 QualType PointeeType = ParamType->getPointeeType();
6344 NeedsNewDecl = true;
6345 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6346
6347 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6348 OverloadParams.push_back(Context.getPointerType(PointeeType));
6349 }
6350 }
6351
6352 if (!NeedsNewDecl)
6353 return nullptr;
6354
6356 EPI.Variadic = FT->isVariadic();
6357 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6358 OverloadParams, EPI);
6359 DeclContext *Parent = FDecl->getParent();
6360 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6361 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6362 FDecl->getIdentifier(), OverloadTy,
6363 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6364 false,
6365 /*hasPrototype=*/true);
6367 FT = cast<FunctionProtoType>(OverloadTy);
6368 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6369 QualType ParamType = FT->getParamType(i);
6370 ParmVarDecl *Parm =
6371 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6372 SourceLocation(), nullptr, ParamType,
6373 /*TInfo=*/nullptr, SC_None, nullptr);
6374 Parm->setScopeInfo(0, i);
6375 Params.push_back(Parm);
6376 }
6377 OverloadDecl->setParams(Params);
6378 // We cannot merge host/device attributes of redeclarations. They have to
6379 // be consistent when created.
6380 if (Sema->LangOpts.CUDA) {
6381 if (FDecl->hasAttr<CUDAHostAttr>())
6382 OverloadDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
6383 if (FDecl->hasAttr<CUDADeviceAttr>())
6384 OverloadDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
6385 }
6386 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6387 return OverloadDecl;
6388}
6389
6390static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6391 FunctionDecl *Callee,
6392 MultiExprArg ArgExprs) {
6393 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6394 // similar attributes) really don't like it when functions are called with an
6395 // invalid number of args.
6396 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6397 /*PartialOverloading=*/false) &&
6398 !Callee->isVariadic())
6399 return;
6400 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6401 return;
6402
6403 if (const EnableIfAttr *Attr =
6404 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6405 S.Diag(Fn->getBeginLoc(),
6406 isa<CXXMethodDecl>(Callee)
6407 ? diag::err_ovl_no_viable_member_function_in_call
6408 : diag::err_ovl_no_viable_function_in_call)
6409 << Callee << Callee->getSourceRange();
6410 S.Diag(Callee->getLocation(),
6411 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6412 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6413 return;
6414 }
6415}
6416
6418 const UnresolvedMemberExpr *const UME, Sema &S) {
6419
6420 const auto GetFunctionLevelDCIfCXXClass =
6421 [](Sema &S) -> const CXXRecordDecl * {
6422 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6423 if (!DC || !DC->getParent())
6424 return nullptr;
6425
6426 // If the call to some member function was made from within a member
6427 // function body 'M' return return 'M's parent.
6428 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6429 return MD->getParent()->getCanonicalDecl();
6430 // else the call was made from within a default member initializer of a
6431 // class, so return the class.
6432 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6433 return RD->getCanonicalDecl();
6434 return nullptr;
6435 };
6436 // If our DeclContext is neither a member function nor a class (in the
6437 // case of a lambda in a default member initializer), we can't have an
6438 // enclosing 'this'.
6439
6440 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6441 if (!CurParentClass)
6442 return false;
6443
6444 // The naming class for implicit member functions call is the class in which
6445 // name lookup starts.
6446 const CXXRecordDecl *const NamingClass =
6448 assert(NamingClass && "Must have naming class even for implicit access");
6449
6450 // If the unresolved member functions were found in a 'naming class' that is
6451 // related (either the same or derived from) to the class that contains the
6452 // member function that itself contained the implicit member access.
6453
6454 return CurParentClass == NamingClass ||
6455 CurParentClass->isDerivedFrom(NamingClass);
6456}
6457
6458static void
6460 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6461
6462 if (!UME)
6463 return;
6464
6465 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6466 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6467 // already been captured, or if this is an implicit member function call (if
6468 // it isn't, an attempt to capture 'this' should already have been made).
6469 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6470 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6471 return;
6472
6473 // Check if the naming class in which the unresolved members were found is
6474 // related (same as or is a base of) to the enclosing class.
6475
6477 return;
6478
6479
6480 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6481 // If the enclosing function is not dependent, then this lambda is
6482 // capture ready, so if we can capture this, do so.
6483 if (!EnclosingFunctionCtx->isDependentContext()) {
6484 // If the current lambda and all enclosing lambdas can capture 'this' -
6485 // then go ahead and capture 'this' (since our unresolved overload set
6486 // contains at least one non-static member function).
6487 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6488 S.CheckCXXThisCapture(CallLoc);
6489 } else if (S.CurContext->isDependentContext()) {
6490 // ... since this is an implicit member reference, that might potentially
6491 // involve a 'this' capture, mark 'this' for potential capture in
6492 // enclosing lambdas.
6493 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6494 CurLSI->addPotentialThisCapture(CallLoc);
6495 }
6496}
6497
6498// Once a call is fully resolved, warn for unqualified calls to specific
6499// C++ standard functions, like move and forward.
6501 const CallExpr *Call) {
6502 // We are only checking unary move and forward so exit early here.
6503 if (Call->getNumArgs() != 1)
6504 return;
6505
6506 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6507 if (!E || isa<UnresolvedLookupExpr>(E))
6508 return;
6509 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6510 if (!DRE || !DRE->getLocation().isValid())
6511 return;
6512
6513 if (DRE->getQualifier())
6514 return;
6515
6516 const FunctionDecl *FD = Call->getDirectCallee();
6517 if (!FD)
6518 return;
6519
6520 // Only warn for some functions deemed more frequent or problematic.
6521 unsigned BuiltinID = FD->getBuiltinID();
6522 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6523 return;
6524
6525 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6527 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6528}
6529
6531 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6532 Expr *ExecConfig) {
6534 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6535 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6536 if (Call.isInvalid())
6537 return Call;
6538
6539 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6540 // language modes.
6541 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6542 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6543 DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id)
6544 << ULE->getName();
6545 }
6546
6547 if (LangOpts.OpenMP)
6548 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6549 ExecConfig);
6550 if (LangOpts.CPlusPlus) {
6551 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6553
6554 // If we previously found that the id-expression of this call refers to a
6555 // consteval function but the call is dependent, we should not treat is an
6556 // an invalid immediate call.
6557 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6558 DRE && Call.get()->isValueDependent()) {
6560 }
6561 }
6562 return Call;
6563}
6564
6565// Any type that could be used to form a callable expression
6566static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6567 QualType T = E->getType();
6568 if (T->isDependentType())
6569 return true;
6570
6571 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6572 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6573 T->isFunctionType() || T->isFunctionReferenceType() ||
6574 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6575 T->isBlockPointerType() || T->isRecordType())
6576 return true;
6577
6580}
6581
6583 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6584 Expr *ExecConfig, bool IsExecConfig,
6585 bool AllowRecovery) {
6586 // Since this might be a postfix expression, get rid of ParenListExprs.
6588 if (Result.isInvalid()) return ExprError();
6589 Fn = Result.get();
6590
6591 if (CheckArgsForPlaceholders(ArgExprs))
6592 return ExprError();
6593
6594 // The result of __builtin_counted_by_ref cannot be used as a function
6595 // argument. It allows leaking and modification of bounds safety information.
6596 for (const Expr *Arg : ArgExprs)
6597 if (CheckInvalidBuiltinCountedByRef(Arg,
6599 return ExprError();
6600
6601 if (getLangOpts().CPlusPlus) {
6602 // If this is a pseudo-destructor expression, build the call immediately.
6604 if (!ArgExprs.empty()) {
6605 // Pseudo-destructor calls should not have any arguments.
6606 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6608 SourceRange(ArgExprs.front()->getBeginLoc(),
6609 ArgExprs.back()->getEndLoc()));
6610 }
6611
6612 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6613 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6614 }
6615 if (Fn->getType() == Context.PseudoObjectTy) {
6616 ExprResult result = CheckPlaceholderExpr(Fn);
6617 if (result.isInvalid()) return ExprError();
6618 Fn = result.get();
6619 }
6620
6621 // Determine whether this is a dependent call inside a C++ template,
6622 // in which case we won't do any semantic analysis now.
6623 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6624 if (ExecConfig) {
6626 cast<CallExpr>(ExecConfig), ArgExprs,
6627 Context.DependentTy, VK_PRValue,
6628 RParenLoc, CurFPFeatureOverrides());
6629 } else {
6630
6632 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6633 Fn->getBeginLoc());
6634
6635 // If the type of the function itself is not dependent
6636 // check that it is a reasonable as a function, as type deduction
6637 // later assume the CallExpr has a sensible TYPE.
6638 if (!MayBeFunctionType(Context, Fn))
6639 return ExprError(
6640 Diag(LParenLoc, diag::err_typecheck_call_not_function)
6641 << Fn->getType() << Fn->getSourceRange());
6642
6643 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6644 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6645 }
6646 }
6647
6648 // Determine whether this is a call to an object (C++ [over.call.object]).
6649 if (Fn->getType()->isRecordType())
6650 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6651 RParenLoc);
6652
6653 if (Fn->getType() == Context.UnknownAnyTy) {
6654 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6655 if (result.isInvalid()) return ExprError();
6656 Fn = result.get();
6657 }
6658
6659 if (Fn->getType() == Context.BoundMemberTy) {
6660 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6661 RParenLoc, ExecConfig, IsExecConfig,
6662 AllowRecovery);
6663 }
6664 }
6665
6666 // Check for overloaded calls. This can happen even in C due to extensions.
6667 if (Fn->getType() == Context.OverloadTy) {
6669
6670 // We aren't supposed to apply this logic if there's an '&' involved.
6673 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6674 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6675 OverloadExpr *ovl = find.Expression;
6676 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6678 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6679 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6680 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6681 RParenLoc, ExecConfig, IsExecConfig,
6682 AllowRecovery);
6683 }
6684 }
6685
6686 // If we're directly calling a function, get the appropriate declaration.
6687 if (Fn->getType() == Context.UnknownAnyTy) {
6688 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6689 if (result.isInvalid()) return ExprError();
6690 Fn = result.get();
6691 }
6692
6693 Expr *NakedFn = Fn->IgnoreParens();
6694
6695 bool CallingNDeclIndirectly = false;
6696 NamedDecl *NDecl = nullptr;
6697 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6698 if (UnOp->getOpcode() == UO_AddrOf) {
6699 CallingNDeclIndirectly = true;
6700 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6701 }
6702 }
6703
6704 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6705 NDecl = DRE->getDecl();
6706
6707 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6708 if (FDecl && FDecl->getBuiltinID()) {
6709 // Rewrite the function decl for this builtin by replacing parameters
6710 // with no explicit address space with the address space of the arguments
6711 // in ArgExprs.
6712 if ((FDecl =
6713 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6714 NDecl = FDecl;
6716 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6717 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6718 nullptr, DRE->isNonOdrUse());
6719 }
6720 }
6721 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6722 NDecl = ME->getMemberDecl();
6723
6724 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6725 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6726 FD, /*Complain=*/true, Fn->getBeginLoc()))
6727 return ExprError();
6728
6729 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6730
6731 // If this expression is a call to a builtin function in HIP device
6732 // compilation, allow a pointer-type argument to default address space to be
6733 // passed as a pointer-type parameter to a non-default address space.
6734 // If Arg is declared in the default address space and Param is declared
6735 // in a non-default address space, perform an implicit address space cast to
6736 // the parameter type.
6737 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6738 FD->getBuiltinID()) {
6739 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6740 ++Idx) {
6741 ParmVarDecl *Param = FD->getParamDecl(Idx);
6742 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6743 !ArgExprs[Idx]->getType()->isPointerType())
6744 continue;
6745
6746 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6747 auto ArgTy = ArgExprs[Idx]->getType();
6748 auto ArgPtTy = ArgTy->getPointeeType();
6749 auto ArgAS = ArgPtTy.getAddressSpace();
6750
6751 // Add address space cast if target address spaces are different
6752 bool NeedImplicitASC =
6753 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6754 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6755 // or from specific AS which has target AS matching that of Param.
6757 if (!NeedImplicitASC)
6758 continue;
6759
6760 // First, ensure that the Arg is an RValue.
6761 if (ArgExprs[Idx]->isGLValue()) {
6762 ArgExprs[Idx] = ImplicitCastExpr::Create(
6763 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6764 nullptr, VK_PRValue, FPOptionsOverride());
6765 }
6766
6767 // Construct a new arg type with address space of Param
6768 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6769 ArgPtQuals.setAddressSpace(ParamAS);
6770 auto NewArgPtTy =
6771 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6772 auto NewArgTy =
6773 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6774 ArgTy.getQualifiers());
6775
6776 // Finally perform an implicit address space cast
6777 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6778 CK_AddressSpaceConversion)
6779 .get();
6780 }
6781 }
6782 }
6783
6784 if (Context.isDependenceAllowed() &&
6785 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6786 assert(!getLangOpts().CPlusPlus);
6787 assert((Fn->containsErrors() ||
6788 llvm::any_of(ArgExprs,
6789 [](clang::Expr *E) { return E->containsErrors(); })) &&
6790 "should only occur in error-recovery path.");
6791 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6792 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6793 }
6794 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6795 ExecConfig, IsExecConfig);
6796}
6797
6799 MultiExprArg CallArgs) {
6800 std::string Name = Context.BuiltinInfo.getName(Id);
6801 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6803 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6804
6805 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6806 assert(BuiltInDecl && "failed to find builtin declaration");
6807
6808 ExprResult DeclRef =
6809 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6810 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6811
6813 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6814
6815 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6816 return Call.get();
6817}
6818
6820 SourceLocation BuiltinLoc,
6821 SourceLocation RParenLoc) {
6822 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6823 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6824}
6825
6827 SourceLocation BuiltinLoc,
6828 SourceLocation RParenLoc) {
6831 QualType SrcTy = E->getType();
6832 if (!SrcTy->isDependentType() &&
6833 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6834 return ExprError(
6835 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6836 << DestTy << SrcTy << E->getSourceRange());
6837 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6838}
6839
6841 SourceLocation BuiltinLoc,
6842 SourceLocation RParenLoc) {
6843 TypeSourceInfo *TInfo;
6844 GetTypeFromParser(ParsedDestTy, &TInfo);
6845 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6846}
6847
6849 SourceLocation LParenLoc,
6850 ArrayRef<Expr *> Args,
6851 SourceLocation RParenLoc, Expr *Config,
6852 bool IsExecConfig, ADLCallKind UsesADL) {
6853 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6854 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6855
6856 // Functions with 'interrupt' attribute cannot be called directly.
6857 if (FDecl) {
6858 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
6859 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6860 return ExprError();
6861 }
6862 if (FDecl->hasAttr<ARMInterruptAttr>()) {
6863 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
6864 return ExprError();
6865 }
6866 }
6867
6868 // X86 interrupt handlers may only call routines with attribute
6869 // no_caller_saved_registers since there is no efficient way to
6870 // save and restore the non-GPR state.
6871 if (auto *Caller = getCurFunctionDecl()) {
6872 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6873 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6874 const TargetInfo &TI = Context.getTargetInfo();
6875 bool HasNonGPRRegisters =
6876 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6877 if (HasNonGPRRegisters &&
6878 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6879 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6880 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6881 if (FDecl)
6882 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6883 }
6884 }
6885 }
6886
6887 // Promote the function operand.
6888 // We special-case function promotion here because we only allow promoting
6889 // builtin functions to function pointers in the callee of a call.
6891 QualType ResultTy;
6892 if (BuiltinID &&
6893 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6894 // Extract the return type from the (builtin) function pointer type.
6895 // FIXME Several builtins still have setType in
6896 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6897 // Builtins.td to ensure they are correct before removing setType calls.
6898 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6899 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6900 ResultTy = FDecl->getCallResultType();
6901 } else {
6903 ResultTy = Context.BoolTy;
6904 }
6905 if (Result.isInvalid())
6906 return ExprError();
6907 Fn = Result.get();
6908
6909 // Check for a valid function type, but only if it is not a builtin which
6910 // requires custom type checking. These will be handled by
6911 // CheckBuiltinFunctionCall below just after creation of the call expression.
6912 const FunctionType *FuncT = nullptr;
6913 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6914 retry:
6915 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6916 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6917 // have type pointer to function".
6918 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6919 if (!FuncT)
6920 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6921 << Fn->getType() << Fn->getSourceRange());
6922 } else if (const BlockPointerType *BPT =
6923 Fn->getType()->getAs<BlockPointerType>()) {
6924 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6925 } else {
6926 // Handle calls to expressions of unknown-any type.
6927 if (Fn->getType() == Context.UnknownAnyTy) {
6928 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6929 if (rewrite.isInvalid())
6930 return ExprError();
6931 Fn = rewrite.get();
6932 goto retry;
6933 }
6934
6935 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6936 << Fn->getType() << Fn->getSourceRange());
6937 }
6938 }
6939
6940 // Get the number of parameters in the function prototype, if any.
6941 // We will allocate space for max(Args.size(), NumParams) arguments
6942 // in the call expression.
6943 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6944 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6945
6946 CallExpr *TheCall;
6947 if (Config) {
6948 assert(UsesADL == ADLCallKind::NotADL &&
6949 "CUDAKernelCallExpr should not use ADL");
6950 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6951 Args, ResultTy, VK_PRValue, RParenLoc,
6952 CurFPFeatureOverrides(), NumParams);
6953 } else {
6954 TheCall =
6955 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6956 CurFPFeatureOverrides(), NumParams, UsesADL);
6957 }
6958
6959 // Bail out early if calling a builtin with custom type checking.
6960 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6961 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6962 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
6963 E = CheckForImmediateInvocation(E, FDecl);
6964 return E;
6965 }
6966
6967 if (getLangOpts().CUDA) {
6968 if (Config) {
6969 // CUDA: Kernel calls must be to global functions
6970 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6971 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6972 << FDecl << Fn->getSourceRange());
6973
6974 // CUDA: Kernel function must have 'void' return type
6975 if (!FuncT->getReturnType()->isVoidType() &&
6976 !FuncT->getReturnType()->getAs<AutoType>() &&
6978 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6979 << Fn->getType() << Fn->getSourceRange());
6980 } else {
6981 // CUDA: Calls to global functions must be configured
6982 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6983 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6984 << FDecl << Fn->getSourceRange());
6985 }
6986 }
6987
6988 // Check for a valid return type
6989 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6990 FDecl))
6991 return ExprError();
6992
6993 // We know the result type of the call, set it.
6994 TheCall->setType(FuncT->getCallResultType(Context));
6996
6997 // WebAssembly tables can't be used as arguments.
6998 if (Context.getTargetInfo().getTriple().isWasm()) {
6999 for (const Expr *Arg : Args) {
7000 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7001 return ExprError(Diag(Arg->getExprLoc(),
7002 diag::err_wasm_table_as_function_parameter));
7003 }
7004 }
7005 }
7006
7007 if (Proto) {
7008 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7009 IsExecConfig))
7010 return ExprError();
7011 } else {
7012 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7013
7014 if (FDecl) {
7015 // Check if we have too few/too many template arguments, based
7016 // on our knowledge of the function definition.
7017 const FunctionDecl *Def = nullptr;
7018 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7019 Proto = Def->getType()->getAs<FunctionProtoType>();
7020 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7021 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7022 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7023 }
7024
7025 // If the function we're calling isn't a function prototype, but we have
7026 // a function prototype from a prior declaratiom, use that prototype.
7027 if (!FDecl->hasPrototype())
7028 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7029 }
7030
7031 // If we still haven't found a prototype to use but there are arguments to
7032 // the call, diagnose this as calling a function without a prototype.
7033 // However, if we found a function declaration, check to see if
7034 // -Wdeprecated-non-prototype was disabled where the function was declared.
7035 // If so, we will silence the diagnostic here on the assumption that this
7036 // interface is intentional and the user knows what they're doing. We will
7037 // also silence the diagnostic if there is a function declaration but it
7038 // was implicitly defined (the user already gets diagnostics about the
7039 // creation of the implicit function declaration, so the additional warning
7040 // is not helpful).
7041 if (!Proto && !Args.empty() &&
7042 (!FDecl || (!FDecl->isImplicit() &&
7043 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7044 FDecl->getLocation()))))
7045 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7046 << (FDecl != nullptr) << FDecl;
7047
7048 // Promote the arguments (C99 6.5.2.2p6).
7049 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7050 Expr *Arg = Args[i];
7051
7052 if (Proto && i < Proto->getNumParams()) {
7054 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7055 ExprResult ArgE =
7057 if (ArgE.isInvalid())
7058 return true;
7059
7060 Arg = ArgE.getAs<Expr>();
7061
7062 } else {
7064
7065 if (ArgE.isInvalid())
7066 return true;
7067
7068 Arg = ArgE.getAs<Expr>();
7069 }
7070
7071 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7072 diag::err_call_incomplete_argument, Arg))
7073 return ExprError();
7074
7075 TheCall->setArg(i, Arg);
7076 }
7077 TheCall->computeDependence();
7078 }
7079
7080 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7081 if (Method->isImplicitObjectMemberFunction())
7082 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7083 << Fn->getSourceRange() << 0);
7084
7085 // Check for sentinels
7086 if (NDecl)
7087 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7088
7089 // Warn for unions passing across security boundary (CMSE).
7090 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7091 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7092 if (const auto *RT =
7093 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7094 if (RT->getDecl()->isOrContainsUnion())
7095 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7096 << 0 << i;
7097 }
7098 }
7099 }
7100
7101 // Do special checking on direct calls to functions.
7102 if (FDecl) {
7103 if (CheckFunctionCall(FDecl, TheCall, Proto))
7104 return ExprError();
7105
7106 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7107
7108 if (BuiltinID)
7109 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7110 } else if (NDecl) {
7111 if (CheckPointerCall(NDecl, TheCall, Proto))
7112 return ExprError();
7113 } else {
7114 if (CheckOtherCall(TheCall, Proto))
7115 return ExprError();
7116 }
7117
7118 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7119}
7120
7123 SourceLocation RParenLoc, Expr *InitExpr) {
7124 assert(Ty && "ActOnCompoundLiteral(): missing type");
7125 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7126
7127 TypeSourceInfo *TInfo;
7128 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7129 if (!TInfo)
7130 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7131
7132 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7133}
7134
7137 SourceLocation RParenLoc, Expr *LiteralExpr) {
7138 QualType literalType = TInfo->getType();
7139
7140 if (literalType->isArrayType()) {
7142 LParenLoc, Context.getBaseElementType(literalType),
7143 diag::err_array_incomplete_or_sizeless_type,
7144 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7145 return ExprError();
7146 if (literalType->isVariableArrayType()) {
7147 // C23 6.7.10p4: An entity of variable length array type shall not be
7148 // initialized except by an empty initializer.
7149 //
7150 // The C extension warnings are issued from ParseBraceInitializer() and
7151 // do not need to be issued here. However, we continue to issue an error
7152 // in the case there are initializers or we are compiling C++. We allow
7153 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7154 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7155 // FIXME: should we allow this construct in C++ when it makes sense to do
7156 // so?
7157 //
7158 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7159 // shall specify an object type or an array of unknown size, but not a
7160 // variable length array type. This seems odd, as it allows 'int a[size] =
7161 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7162 // says, this is what's implemented here for C (except for the extension
7163 // that permits constant foldable size arrays)
7164
7165 auto diagID = LangOpts.CPlusPlus
7166 ? diag::err_variable_object_no_init
7167 : diag::err_compound_literal_with_vla_type;
7168 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7169 diagID))
7170 return ExprError();
7171 }
7172 } else if (!literalType->isDependentType() &&
7173 RequireCompleteType(LParenLoc, literalType,
7174 diag::err_typecheck_decl_incomplete_type,
7175 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7176 return ExprError();
7177
7178 InitializedEntity Entity
7182 SourceRange(LParenLoc, RParenLoc),
7183 /*InitList=*/true);
7184 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7185 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7186 &literalType);
7187 if (Result.isInvalid())
7188 return ExprError();
7189 LiteralExpr = Result.get();
7190
7191 // We treat the compound literal as being at file scope if it's not in a
7192 // function or method body, or within the function's prototype scope. This
7193 // means the following compound literal is not at file scope:
7194 // void func(char *para[(int [1]){ 0 }[0]);
7195 const Scope *S = getCurScope();
7196 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7197 !S->isInCFunctionScope() &&
7198 (!S || !S->isFunctionPrototypeScope());
7199
7200 // In C, compound literals are l-values for some reason.
7201 // For GCC compatibility, in C++, file-scope array compound literals with
7202 // constant initializers are also l-values, and compound literals are
7203 // otherwise prvalues.
7204 //
7205 // (GCC also treats C++ list-initialized file-scope array prvalues with
7206 // constant initializers as l-values, but that's non-conforming, so we don't
7207 // follow it there.)
7208 //
7209 // FIXME: It would be better to handle the lvalue cases as materializing and
7210 // lifetime-extending a temporary object, but our materialized temporaries
7211 // representation only supports lifetime extension from a variable, not "out
7212 // of thin air".
7213 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7214 // is bound to the result of applying array-to-pointer decay to the compound
7215 // literal.
7216 // FIXME: GCC supports compound literals of reference type, which should
7217 // obviously have a value kind derived from the kind of reference involved.
7219 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7220 ? VK_PRValue
7221 : VK_LValue;
7222
7223 // C99 6.5.2.5
7224 // "If the compound literal occurs outside the body of a function, the
7225 // initializer list shall consist of constant expressions."
7226 if (IsFileScope)
7227 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7228 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7229 Expr *Init = ILE->getInit(i);
7230 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7231 !Init->isConstantInitializer(Context, /*IsForRef=*/false)) {
7232 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7233 << Init->getSourceBitField();
7234 return ExprError();
7235 }
7236
7237 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7238 }
7239
7240 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7241 LiteralExpr, IsFileScope);
7242 if (IsFileScope) {
7243 if (!LiteralExpr->isTypeDependent() &&
7244 !LiteralExpr->isValueDependent() &&
7245 !literalType->isDependentType()) // C99 6.5.2.5p3
7246 if (CheckForConstantInitializer(LiteralExpr))
7247 return ExprError();
7248 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7249 literalType.getAddressSpace() != LangAS::Default) {
7250 // Embedded-C extensions to C99 6.5.2.5:
7251 // "If the compound literal occurs inside the body of a function, the
7252 // type name shall not be qualified by an address-space qualifier."
7253 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7254 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7255 return ExprError();
7256 }
7257
7258 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7259 // Compound literals that have automatic storage duration are destroyed at
7260 // the end of the scope in C; in C++, they're just temporaries.
7261
7262 // Emit diagnostics if it is or contains a C union type that is non-trivial
7263 // to destruct.
7268
7269 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7270 if (literalType.isDestructedType()) {
7271 Cleanup.setExprNeedsCleanups(true);
7272 ExprCleanupObjects.push_back(E);
7274 }
7275 }
7276
7279 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7280 E->getInitializer()->getExprLoc());
7281
7282 return MaybeBindToTemporary(E);
7283}
7284
7287 SourceLocation RBraceLoc) {
7288 // Only produce each kind of designated initialization diagnostic once.
7289 SourceLocation FirstDesignator;
7290 bool DiagnosedArrayDesignator = false;
7291 bool DiagnosedNestedDesignator = false;
7292 bool DiagnosedMixedDesignator = false;
7293
7294 // Check that any designated initializers are syntactically valid in the
7295 // current language mode.
7296 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7297 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7298 if (FirstDesignator.isInvalid())
7299 FirstDesignator = DIE->getBeginLoc();
7300
7301 if (!getLangOpts().CPlusPlus)
7302 break;
7303
7304 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7305 DiagnosedNestedDesignator = true;
7306 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7307 << DIE->getDesignatorsSourceRange();
7308 }
7309
7310 for (auto &Desig : DIE->designators()) {
7311 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7312 DiagnosedArrayDesignator = true;
7313 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7314 << Desig.getSourceRange();
7315 }
7316 }
7317
7318 if (!DiagnosedMixedDesignator &&
7319 !isa<DesignatedInitExpr>(InitArgList[0])) {
7320 DiagnosedMixedDesignator = true;
7321 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7322 << DIE->getSourceRange();
7323 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7324 << InitArgList[0]->getSourceRange();
7325 }
7326 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7327 isa<DesignatedInitExpr>(InitArgList[0])) {
7328 DiagnosedMixedDesignator = true;
7329 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7330 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7331 << DIE->getSourceRange();
7332 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7333 << InitArgList[I]->getSourceRange();
7334 }
7335 }
7336
7337 if (FirstDesignator.isValid()) {
7338 // Only diagnose designated initiaization as a C++20 extension if we didn't
7339 // already diagnose use of (non-C++20) C99 designator syntax.
7340 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7341 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7342 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7343 ? diag::warn_cxx17_compat_designated_init
7344 : diag::ext_cxx_designated_init);
7345 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7346 Diag(FirstDesignator, diag::ext_designated_init);
7347 }
7348 }
7349
7350 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7351}
7352
7355 SourceLocation RBraceLoc) {
7356 // Semantic analysis for initializers is done by ActOnDeclarator() and
7357 // CheckInitializer() - it requires knowledge of the object being initialized.
7358
7359 // Immediately handle non-overload placeholders. Overloads can be
7360 // resolved contextually, but everything else here can't.
7361 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7362 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7363 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7364
7365 // Ignore failures; dropping the entire initializer list because
7366 // of one failure would be terrible for indexing/etc.
7367 if (result.isInvalid()) continue;
7368
7369 InitArgList[I] = result.get();
7370 }
7371 }
7372
7373 InitListExpr *E =
7374 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7375 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7376 return E;
7377}
7378
7380 assert(E.get()->getType()->isBlockPointerType());
7381 assert(E.get()->isPRValue());
7382
7383 // Only do this in an r-value context.
7384 if (!getLangOpts().ObjCAutoRefCount) return;
7385
7387 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7388 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7389 Cleanup.setExprNeedsCleanups(true);
7390}
7391
7393 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7394 // Also, callers should have filtered out the invalid cases with
7395 // pointers. Everything else should be possible.
7396
7397 QualType SrcTy = Src.get()->getType();
7398 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7399 return CK_NoOp;
7400
7401 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7403 llvm_unreachable("member pointer type in C");
7404
7405 case Type::STK_CPointer:
7408 switch (DestTy->getScalarTypeKind()) {
7409 case Type::STK_CPointer: {
7410 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7411 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7412 if (SrcAS != DestAS)
7413 return CK_AddressSpaceConversion;
7414 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7415 return CK_NoOp;
7416 return CK_BitCast;
7417 }
7419 return (SrcKind == Type::STK_BlockPointer
7420 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7422 if (SrcKind == Type::STK_ObjCObjectPointer)
7423 return CK_BitCast;
7424 if (SrcKind == Type::STK_CPointer)
7425 return CK_CPointerToObjCPointerCast;
7427 return CK_BlockPointerToObjCPointerCast;
7428 case Type::STK_Bool:
7429 return CK_PointerToBoolean;
7430 case Type::STK_Integral:
7431 return CK_PointerToIntegral;
7432 case Type::STK_Floating:
7437 llvm_unreachable("illegal cast from pointer");
7438 }
7439 llvm_unreachable("Should have returned before this");
7440
7442 switch (DestTy->getScalarTypeKind()) {
7444 return CK_FixedPointCast;
7445 case Type::STK_Bool:
7446 return CK_FixedPointToBoolean;
7447 case Type::STK_Integral:
7448 return CK_FixedPointToIntegral;
7449 case Type::STK_Floating:
7450 return CK_FixedPointToFloating;
7453 Diag(Src.get()->getExprLoc(),
7454 diag::err_unimplemented_conversion_with_fixed_point_type)
7455 << DestTy;
7456 return CK_IntegralCast;
7457 case Type::STK_CPointer:
7461 llvm_unreachable("illegal cast to pointer type");
7462 }
7463 llvm_unreachable("Should have returned before this");
7464
7465 case Type::STK_Bool: // casting from bool is like casting from an integer
7466 case Type::STK_Integral:
7467 switch (DestTy->getScalarTypeKind()) {
7468 case Type::STK_CPointer:
7473 return CK_NullToPointer;
7474 return CK_IntegralToPointer;
7475 case Type::STK_Bool:
7476 return CK_IntegralToBoolean;
7477 case Type::STK_Integral:
7478 return CK_IntegralCast;
7479 case Type::STK_Floating:
7480 return CK_IntegralToFloating;
7482 Src = ImpCastExprToType(Src.get(),
7483 DestTy->castAs<ComplexType>()->getElementType(),
7484 CK_IntegralCast);
7485 return CK_IntegralRealToComplex;
7487 Src = ImpCastExprToType(Src.get(),
7488 DestTy->castAs<ComplexType>()->getElementType(),
7489 CK_IntegralToFloating);
7490 return CK_FloatingRealToComplex;
7492 llvm_unreachable("member pointer type in C");
7494 return CK_IntegralToFixedPoint;
7495 }
7496 llvm_unreachable("Should have returned before this");
7497
7498 case Type::STK_Floating:
7499 switch (DestTy->getScalarTypeKind()) {
7500 case Type::STK_Floating:
7501 return CK_FloatingCast;
7502 case Type::STK_Bool:
7503 return CK_FloatingToBoolean;
7504 case Type::STK_Integral:
7505 return CK_FloatingToIntegral;
7507 Src = ImpCastExprToType(Src.get(),
7508 DestTy->castAs<ComplexType>()->getElementType(),
7509 CK_FloatingCast);
7510 return CK_FloatingRealToComplex;
7512 Src = ImpCastExprToType(Src.get(),
7513 DestTy->castAs<ComplexType>()->getElementType(),
7514 CK_FloatingToIntegral);
7515 return CK_IntegralRealToComplex;
7516 case Type::STK_CPointer:
7519 llvm_unreachable("valid float->pointer cast?");
7521 llvm_unreachable("member pointer type in C");
7523 return CK_FloatingToFixedPoint;
7524 }
7525 llvm_unreachable("Should have returned before this");
7526
7528 switch (DestTy->getScalarTypeKind()) {
7530 return CK_FloatingComplexCast;
7532 return CK_FloatingComplexToIntegralComplex;
7533 case Type::STK_Floating: {
7534 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7535 if (Context.hasSameType(ET, DestTy))
7536 return CK_FloatingComplexToReal;
7537 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7538 return CK_FloatingCast;
7539 }
7540 case Type::STK_Bool:
7541 return CK_FloatingComplexToBoolean;
7542 case Type::STK_Integral:
7543 Src = ImpCastExprToType(Src.get(),
7544 SrcTy->castAs<ComplexType>()->getElementType(),
7545 CK_FloatingComplexToReal);
7546 return CK_FloatingToIntegral;
7547 case Type::STK_CPointer:
7550 llvm_unreachable("valid complex float->pointer cast?");
7552 llvm_unreachable("member pointer type in C");
7554 Diag(Src.get()->getExprLoc(),
7555 diag::err_unimplemented_conversion_with_fixed_point_type)
7556 << SrcTy;
7557 return CK_IntegralCast;
7558 }
7559 llvm_unreachable("Should have returned before this");
7560
7562 switch (DestTy->getScalarTypeKind()) {
7564 return CK_IntegralComplexToFloatingComplex;
7566 return CK_IntegralComplexCast;
7567 case Type::STK_Integral: {
7568 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7569 if (Context.hasSameType(ET, DestTy))
7570 return CK_IntegralComplexToReal;
7571 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7572 return CK_IntegralCast;
7573 }
7574 case Type::STK_Bool:
7575 return CK_IntegralComplexToBoolean;
7576 case Type::STK_Floating:
7577 Src = ImpCastExprToType(Src.get(),
7578 SrcTy->castAs<ComplexType>()->getElementType(),
7579 CK_IntegralComplexToReal);
7580 return CK_IntegralToFloating;
7581 case Type::STK_CPointer:
7584 llvm_unreachable("valid complex int->pointer cast?");
7586 llvm_unreachable("member pointer type in C");
7588 Diag(Src.get()->getExprLoc(),
7589 diag::err_unimplemented_conversion_with_fixed_point_type)
7590 << SrcTy;
7591 return CK_IntegralCast;
7592 }
7593 llvm_unreachable("Should have returned before this");
7594 }
7595
7596 llvm_unreachable("Unhandled scalar cast");
7597}
7598
7599static bool breakDownVectorType(QualType type, uint64_t &len,
7600 QualType &eltType) {
7601 // Vectors are simple.
7602 if (const VectorType *vecType = type->getAs<VectorType>()) {
7603 len = vecType->getNumElements();
7604 eltType = vecType->getElementType();
7605 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7606 return true;
7607 }
7608
7609 // We allow lax conversion to and from non-vector types, but only if
7610 // they're real types (i.e. non-complex, non-pointer scalar types).
7611 if (!type->isRealType()) return false;
7612
7613 len = 1;
7614 eltType = type;
7615 return true;
7616}
7617
7619 assert(srcTy->isVectorType() || destTy->isVectorType());
7620
7621 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7622 if (!FirstType->isSVESizelessBuiltinType())
7623 return false;
7624
7625 const auto *VecTy = SecondType->getAs<VectorType>();
7626 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7627 };
7628
7629 return ValidScalableConversion(srcTy, destTy) ||
7630 ValidScalableConversion(destTy, srcTy);
7631}
7632
7634 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7635 return false;
7636
7637 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7638 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7639
7640 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7641 matSrcType->getNumColumns() == matDestType->getNumColumns();
7642}
7643
7645 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7646
7647 uint64_t SrcLen, DestLen;
7648 QualType SrcEltTy, DestEltTy;
7649 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7650 return false;
7651 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7652 return false;
7653
7654 // ASTContext::getTypeSize will return the size rounded up to a
7655 // power of 2, so instead of using that, we need to use the raw
7656 // element size multiplied by the element count.
7657 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7658 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7659
7660 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7661}
7662
7664 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7665 "expected at least one type to be a vector here");
7666
7667 bool IsSrcTyAltivec =
7668 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7670 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7672 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7674
7675 bool IsDestTyAltivec = DestTy->isVectorType() &&
7676 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7678 (DestTy->castAs<VectorType>()->getVectorKind() ==
7680 (DestTy->castAs<VectorType>()->getVectorKind() ==
7682
7683 return (IsSrcTyAltivec || IsDestTyAltivec);
7684}
7685
7687 assert(destTy->isVectorType() || srcTy->isVectorType());
7688
7689 // Disallow lax conversions between scalars and ExtVectors (these
7690 // conversions are allowed for other vector types because common headers
7691 // depend on them). Most scalar OP ExtVector cases are handled by the
7692 // splat path anyway, which does what we want (convert, not bitcast).
7693 // What this rules out for ExtVectors is crazy things like char4*float.
7694 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7695 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7696
7697 return areVectorTypesSameSize(srcTy, destTy);
7698}
7699
7701 assert(destTy->isVectorType() || srcTy->isVectorType());
7702
7703 switch (Context.getLangOpts().getLaxVectorConversions()) {
7705 return false;
7706
7708 if (!srcTy->isIntegralOrEnumerationType()) {
7709 auto *Vec = srcTy->getAs<VectorType>();
7710 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7711 return false;
7712 }
7713 if (!destTy->isIntegralOrEnumerationType()) {
7714 auto *Vec = destTy->getAs<VectorType>();
7715 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7716 return false;
7717 }
7718 // OK, integer (vector) -> integer (vector) bitcast.
7719 break;
7720
7722 break;
7723 }
7724
7725 return areLaxCompatibleVectorTypes(srcTy, destTy);
7726}
7727
7729 CastKind &Kind) {
7730 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7731 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7732 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7733 << DestTy << SrcTy << R;
7734 }
7735 } else if (SrcTy->isMatrixType()) {
7736 return Diag(R.getBegin(),
7737 diag::err_invalid_conversion_between_matrix_and_type)
7738 << SrcTy << DestTy << R;
7739 } else if (DestTy->isMatrixType()) {
7740 return Diag(R.getBegin(),
7741 diag::err_invalid_conversion_between_matrix_and_type)
7742 << DestTy << SrcTy << R;
7743 }
7744
7745 Kind = CK_MatrixCast;
7746 return false;
7747}
7748
7750 CastKind &Kind) {
7751 assert(VectorTy->isVectorType() && "Not a vector type!");
7752
7753 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7754 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7755 return Diag(R.getBegin(),
7756 Ty->isVectorType() ?
7757 diag::err_invalid_conversion_between_vectors :
7758 diag::err_invalid_conversion_between_vector_and_integer)
7759 << VectorTy << Ty << R;
7760 } else
7761 return Diag(R.getBegin(),
7762 diag::err_invalid_conversion_between_vector_and_scalar)
7763 << VectorTy << Ty << R;
7764
7765 Kind = CK_BitCast;
7766 return false;
7767}
7768
7770 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7771
7772 if (DestElemTy == SplattedExpr->getType())
7773 return SplattedExpr;
7774
7775 assert(DestElemTy->isFloatingType() ||
7776 DestElemTy->isIntegralOrEnumerationType());
7777
7778 CastKind CK;
7779 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7780 // OpenCL requires that we convert `true` boolean expressions to -1, but
7781 // only when splatting vectors.
7782 if (DestElemTy->isFloatingType()) {
7783 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7784 // in two steps: boolean to signed integral, then to floating.
7785 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7786 CK_BooleanToSignedIntegral);
7787 SplattedExpr = CastExprRes.get();
7788 CK = CK_IntegralToFloating;
7789 } else {
7790 CK = CK_BooleanToSignedIntegral;
7791 }
7792 } else {
7793 ExprResult CastExprRes = SplattedExpr;
7794 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7795 if (CastExprRes.isInvalid())
7796 return ExprError();
7797 SplattedExpr = CastExprRes.get();
7798 }
7799 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7800}
7801
7803 Expr *CastExpr, CastKind &Kind) {
7804 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7805
7806 QualType SrcTy = CastExpr->getType();
7807
7808 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7809 // an ExtVectorType.
7810 // In OpenCL, casts between vectors of different types are not allowed.
7811 // (See OpenCL 6.2).
7812 if (SrcTy->isVectorType()) {
7813 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7814 (getLangOpts().OpenCL &&
7815 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7816 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7817 << DestTy << SrcTy << R;
7818 return ExprError();
7819 }
7820 Kind = CK_BitCast;
7821 return CastExpr;
7822 }
7823
7824 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7825 // conversion will take place first from scalar to elt type, and then
7826 // splat from elt type to vector.
7827 if (SrcTy->isPointerType())
7828 return Diag(R.getBegin(),
7829 diag::err_invalid_conversion_between_vector_and_scalar)
7830 << DestTy << SrcTy << R;
7831
7832 Kind = CK_VectorSplat;
7833 return prepareVectorSplat(DestTy, CastExpr);
7834}
7835
7836/// Check that a call to alloc_size function specifies sufficient space for the
7837/// destination type.
7838static void CheckSufficientAllocSize(Sema &S, QualType DestType,
7839 const Expr *E) {
7840 QualType SourceType = E->getType();
7841 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
7842 DestType == SourceType)
7843 return;
7844
7845 const auto *CE = dyn_cast<CallExpr>(E->IgnoreParenCasts());
7846 if (!CE)
7847 return;
7848
7849 // Find the total size allocated by the function call.
7850 if (!CE->getCalleeAllocSizeAttr())
7851 return;
7852 std::optional<llvm::APInt> AllocSize =
7853 CE->evaluateBytesReturnedByAllocSizeCall(S.Context);
7854 // Allocations of size zero are permitted as a special case. They are usually
7855 // done intentionally.
7856 if (!AllocSize || AllocSize->isZero())
7857 return;
7858 auto Size = CharUnits::fromQuantity(AllocSize->getZExtValue());
7859
7860 QualType TargetType = DestType->getPointeeType();
7861 // Find the destination size. As a special case function types have size of
7862 // one byte to match the sizeof operator behavior.
7863 auto LhsSize = TargetType->isFunctionType()
7864 ? CharUnits::One()
7865 : S.Context.getTypeSizeInCharsIfKnown(TargetType);
7866 if (LhsSize && Size < LhsSize)
7867 S.Diag(E->getExprLoc(), diag::warn_alloc_size)
7868 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
7869}
7870
7873 Declarator &D, ParsedType &Ty,
7874 SourceLocation RParenLoc, Expr *CastExpr) {
7875 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7876 "ActOnCastExpr(): missing type or expr");
7877
7879 if (D.isInvalidType())
7880 return ExprError();
7881
7882 if (getLangOpts().CPlusPlus) {
7883 // Check that there are no default arguments (C++ only).
7885 }
7886
7888
7889 QualType castType = castTInfo->getType();
7890 Ty = CreateParsedType(castType, castTInfo);
7891
7892 bool isVectorLiteral = false;
7893
7894 // Check for an altivec or OpenCL literal,
7895 // i.e. all the elements are integer constants.
7896 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7897 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7898 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7899 && castType->isVectorType() && (PE || PLE)) {
7900 if (PLE && PLE->getNumExprs() == 0) {
7901 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7902 return ExprError();
7903 }
7904 if (PE || PLE->getNumExprs() == 1) {
7905 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7906 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7907 isVectorLiteral = true;
7908 }
7909 else
7910 isVectorLiteral = true;
7911 }
7912
7913 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7914 // then handle it as such.
7915 if (isVectorLiteral)
7916 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7917
7918 // If the Expr being casted is a ParenListExpr, handle it specially.
7919 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7920 // sequence of BinOp comma operators.
7923 if (Result.isInvalid()) return ExprError();
7924 CastExpr = Result.get();
7925 }
7926
7927 if (getLangOpts().CPlusPlus && !castType->isVoidType())
7928 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7929
7931
7933
7935
7936 CheckSufficientAllocSize(*this, castType, CastExpr);
7937
7938 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7939}
7940
7942 SourceLocation RParenLoc, Expr *E,
7943 TypeSourceInfo *TInfo) {
7944 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7945 "Expected paren or paren list expression");
7946
7947 Expr **exprs;
7948 unsigned numExprs;
7949 Expr *subExpr;
7950 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7951 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7952 LiteralLParenLoc = PE->getLParenLoc();
7953 LiteralRParenLoc = PE->getRParenLoc();
7954 exprs = PE->getExprs();
7955 numExprs = PE->getNumExprs();
7956 } else { // isa<ParenExpr> by assertion at function entrance
7957 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7958 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7959 subExpr = cast<ParenExpr>(E)->getSubExpr();
7960 exprs = &subExpr;
7961 numExprs = 1;
7962 }
7963
7964 QualType Ty = TInfo->getType();
7965 assert(Ty->isVectorType() && "Expected vector type");
7966
7967 SmallVector<Expr *, 8> initExprs;
7968 const VectorType *VTy = Ty->castAs<VectorType>();
7969 unsigned numElems = VTy->getNumElements();
7970
7971 // '(...)' form of vector initialization in AltiVec: the number of
7972 // initializers must be one or must match the size of the vector.
7973 // If a single value is specified in the initializer then it will be
7974 // replicated to all the components of the vector
7976 VTy->getElementType()))
7977 return ExprError();
7979 // The number of initializers must be one or must match the size of the
7980 // vector. If a single value is specified in the initializer then it will
7981 // be replicated to all the components of the vector
7982 if (numExprs == 1) {
7983 QualType ElemTy = VTy->getElementType();
7984 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7985 if (Literal.isInvalid())
7986 return ExprError();
7987 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7988 PrepareScalarCast(Literal, ElemTy));
7989 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7990 }
7991 else if (numExprs < numElems) {
7992 Diag(E->getExprLoc(),
7993 diag::err_incorrect_number_of_vector_initializers);
7994 return ExprError();
7995 }
7996 else
7997 initExprs.append(exprs, exprs + numExprs);
7998 }
7999 else {
8000 // For OpenCL, when the number of initializers is a single value,
8001 // it will be replicated to all components of the vector.
8003 numExprs == 1) {
8004 QualType ElemTy = VTy->getElementType();
8005 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8006 if (Literal.isInvalid())
8007 return ExprError();
8008 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8009 PrepareScalarCast(Literal, ElemTy));
8010 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8011 }
8012
8013 initExprs.append(exprs, exprs + numExprs);
8014 }
8015 // FIXME: This means that pretty-printing the final AST will produce curly
8016 // braces instead of the original commas.
8017 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8018 initExprs, LiteralRParenLoc);
8019 initE->setType(Ty);
8020 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8021}
8022
8025 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8026 if (!E)
8027 return OrigExpr;
8028
8029 ExprResult Result(E->getExpr(0));
8030
8031 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8032 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8033 E->getExpr(i));
8034
8035 if (Result.isInvalid()) return ExprError();
8036
8037 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8038}
8039
8045
8047 unsigned NumUserSpecifiedExprs,
8048 SourceLocation InitLoc,
8049 SourceLocation LParenLoc,
8050 SourceLocation RParenLoc) {
8051 return CXXParenListInitExpr::Create(Context, Args, T, NumUserSpecifiedExprs,
8052 InitLoc, LParenLoc, RParenLoc);
8053}
8054
8055bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8056 SourceLocation QuestionLoc) {
8057 const Expr *NullExpr = LHSExpr;
8058 const Expr *NonPointerExpr = RHSExpr;
8062
8063 if (NullKind == Expr::NPCK_NotNull) {
8064 NullExpr = RHSExpr;
8065 NonPointerExpr = LHSExpr;
8066 NullKind =
8069 }
8070
8071 if (NullKind == Expr::NPCK_NotNull)
8072 return false;
8073
8074 if (NullKind == Expr::NPCK_ZeroExpression)
8075 return false;
8076
8077 if (NullKind == Expr::NPCK_ZeroLiteral) {
8078 // In this case, check to make sure that we got here from a "NULL"
8079 // string in the source code.
8080 NullExpr = NullExpr->IgnoreParenImpCasts();
8081 SourceLocation loc = NullExpr->getExprLoc();
8082 if (!findMacroSpelling(loc, "NULL"))
8083 return false;
8084 }
8085
8086 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8087 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8088 << NonPointerExpr->getType() << DiagType
8089 << NonPointerExpr->getSourceRange();
8090 return true;
8091}
8092
8093/// Return false if the condition expression is valid, true otherwise.
8094static bool checkCondition(Sema &S, const Expr *Cond,
8095 SourceLocation QuestionLoc) {
8096 QualType CondTy = Cond->getType();
8097
8098 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8099 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8100 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8101 << CondTy << Cond->getSourceRange();
8102 return true;
8103 }
8104
8105 // C99 6.5.15p2
8106 if (CondTy->isScalarType()) return false;
8107
8108 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8109 << CondTy << Cond->getSourceRange();
8110 return true;
8111}
8112
8113/// Return false if the NullExpr can be promoted to PointerTy,
8114/// true otherwise.
8116 QualType PointerTy) {
8117 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8118 !NullExpr.get()->isNullPointerConstant(S.Context,
8120 return true;
8121
8122 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8123 return false;
8124}
8125
8126/// Checks compatibility between two pointers and return the resulting
8127/// type.
8129 ExprResult &RHS,
8130 SourceLocation Loc) {
8131 QualType LHSTy = LHS.get()->getType();
8132 QualType RHSTy = RHS.get()->getType();
8133
8134 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8135 // Two identical pointers types are always compatible.
8136 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8137 }
8138
8139 QualType lhptee, rhptee;
8140
8141 // Get the pointee types.
8142 bool IsBlockPointer = false;
8143 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8144 lhptee = LHSBTy->getPointeeType();
8145 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8146 IsBlockPointer = true;
8147 } else {
8148 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8149 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8150 }
8151
8152 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8153 // differently qualified versions of compatible types, the result type is
8154 // a pointer to an appropriately qualified version of the composite
8155 // type.
8156
8157 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8158 // clause doesn't make sense for our extensions. E.g. address space 2 should
8159 // be incompatible with address space 3: they may live on different devices or
8160 // anything.
8161 Qualifiers lhQual = lhptee.getQualifiers();
8162 Qualifiers rhQual = rhptee.getQualifiers();
8163
8164 LangAS ResultAddrSpace = LangAS::Default;
8165 LangAS LAddrSpace = lhQual.getAddressSpace();
8166 LangAS RAddrSpace = rhQual.getAddressSpace();
8167
8168 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8169 // spaces is disallowed.
8170 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8171 ResultAddrSpace = LAddrSpace;
8172 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8173 ResultAddrSpace = RAddrSpace;
8174 else {
8175 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8176 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8177 << RHS.get()->getSourceRange();
8178 return QualType();
8179 }
8180
8181 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8182 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8183 lhQual.removeCVRQualifiers();
8184 rhQual.removeCVRQualifiers();
8185
8186 if (!lhQual.getPointerAuth().isEquivalent(rhQual.getPointerAuth())) {
8187 S.Diag(Loc, diag::err_typecheck_cond_incompatible_ptrauth)
8188 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8189 << RHS.get()->getSourceRange();
8190 return QualType();
8191 }
8192
8193 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8194 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8195 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8196 // qual types are compatible iff
8197 // * corresponded types are compatible
8198 // * CVR qualifiers are equal
8199 // * address spaces are equal
8200 // Thus for conditional operator we merge CVR and address space unqualified
8201 // pointees and if there is a composite type we return a pointer to it with
8202 // merged qualifiers.
8203 LHSCastKind =
8204 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8205 RHSCastKind =
8206 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8207 lhQual.removeAddressSpace();
8208 rhQual.removeAddressSpace();
8209
8210 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8211 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8212
8213 QualType CompositeTy = S.Context.mergeTypes(
8214 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8215 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8216
8217 if (CompositeTy.isNull()) {
8218 // In this situation, we assume void* type. No especially good
8219 // reason, but this is what gcc does, and we do have to pick
8220 // to get a consistent AST.
8221 QualType incompatTy;
8222 incompatTy = S.Context.getPointerType(
8223 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8224 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8225 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8226
8227 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8228 // for casts between types with incompatible address space qualifiers.
8229 // For the following code the compiler produces casts between global and
8230 // local address spaces of the corresponded innermost pointees:
8231 // local int *global *a;
8232 // global int *global *b;
8233 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8234 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8235 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8236 << RHS.get()->getSourceRange();
8237
8238 return incompatTy;
8239 }
8240
8241 // The pointer types are compatible.
8242 // In case of OpenCL ResultTy should have the address space qualifier
8243 // which is a superset of address spaces of both the 2nd and the 3rd
8244 // operands of the conditional operator.
8245 QualType ResultTy = [&, ResultAddrSpace]() {
8246 if (S.getLangOpts().OpenCL) {
8247 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8248 CompositeQuals.setAddressSpace(ResultAddrSpace);
8249 return S.Context
8250 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8251 .withCVRQualifiers(MergedCVRQual);
8252 }
8253 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8254 }();
8255 if (IsBlockPointer)
8256 ResultTy = S.Context.getBlockPointerType(ResultTy);
8257 else
8258 ResultTy = S.Context.getPointerType(ResultTy);
8259
8260 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8261 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8262 return ResultTy;
8263}
8264
8265/// Return the resulting type when the operands are both block pointers.
8267 ExprResult &LHS,
8268 ExprResult &RHS,
8269 SourceLocation Loc) {
8270 QualType LHSTy = LHS.get()->getType();
8271 QualType RHSTy = RHS.get()->getType();
8272
8273 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8274 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8276 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8277 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8278 return destType;
8279 }
8280 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8281 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8282 << RHS.get()->getSourceRange();
8283 return QualType();
8284 }
8285
8286 // We have 2 block pointer types.
8287 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8288}
8289
8290/// Return the resulting type when the operands are both pointers.
8291static QualType
8293 ExprResult &RHS,
8294 SourceLocation Loc) {
8295 // get the pointer types
8296 QualType LHSTy = LHS.get()->getType();
8297 QualType RHSTy = RHS.get()->getType();
8298
8299 // get the "pointed to" types
8300 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8301 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8302
8303 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8304 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8305 // Figure out necessary qualifiers (C99 6.5.15p6)
8306 QualType destPointee
8307 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8308 QualType destType = S.Context.getPointerType(destPointee);
8309 // Add qualifiers if necessary.
8310 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8311 // Promote to void*.
8312 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8313 return destType;
8314 }
8315 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8316 QualType destPointee
8317 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8318 QualType destType = S.Context.getPointerType(destPointee);
8319 // Add qualifiers if necessary.
8320 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8321 // Promote to void*.
8322 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8323 return destType;
8324 }
8325
8326 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8327}
8328
8329/// Return false if the first expression is not an integer and the second
8330/// expression is not a pointer, true otherwise.
8332 Expr* PointerExpr, SourceLocation Loc,
8333 bool IsIntFirstExpr) {
8334 if (!PointerExpr->getType()->isPointerType() ||
8335 !Int.get()->getType()->isIntegerType())
8336 return false;
8337
8338 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8339 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8340
8341 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8342 << Expr1->getType() << Expr2->getType()
8343 << Expr1->getSourceRange() << Expr2->getSourceRange();
8344 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8345 CK_IntegralToPointer);
8346 return true;
8347}
8348
8349/// Simple conversion between integer and floating point types.
8350///
8351/// Used when handling the OpenCL conditional operator where the
8352/// condition is a vector while the other operands are scalar.
8353///
8354/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8355/// types are either integer or floating type. Between the two
8356/// operands, the type with the higher rank is defined as the "result
8357/// type". The other operand needs to be promoted to the same type. No
8358/// other type promotion is allowed. We cannot use
8359/// UsualArithmeticConversions() for this purpose, since it always
8360/// promotes promotable types.
8362 ExprResult &RHS,
8363 SourceLocation QuestionLoc) {
8365 if (LHS.isInvalid())
8366 return QualType();
8368 if (RHS.isInvalid())
8369 return QualType();
8370
8371 // For conversion purposes, we ignore any qualifiers.
8372 // For example, "const float" and "float" are equivalent.
8373 QualType LHSType =
8375 QualType RHSType =
8377
8378 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8379 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8380 << LHSType << LHS.get()->getSourceRange();
8381 return QualType();
8382 }
8383
8384 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8385 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8386 << RHSType << RHS.get()->getSourceRange();
8387 return QualType();
8388 }
8389
8390 // If both types are identical, no conversion is needed.
8391 if (LHSType == RHSType)
8392 return LHSType;
8393
8394 // Now handle "real" floating types (i.e. float, double, long double).
8395 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8396 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8397 /*IsCompAssign = */ false);
8398
8399 // Finally, we have two differing integer types.
8401 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8402}
8403
8404/// Convert scalar operands to a vector that matches the
8405/// condition in length.
8406///
8407/// Used when handling the OpenCL conditional operator where the
8408/// condition is a vector while the other operands are scalar.
8409///
8410/// We first compute the "result type" for the scalar operands
8411/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8412/// into a vector of that type where the length matches the condition
8413/// vector type. s6.11.6 requires that the element types of the result
8414/// and the condition must have the same number of bits.
8415static QualType
8417 QualType CondTy, SourceLocation QuestionLoc) {
8418 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8419 if (ResTy.isNull()) return QualType();
8420
8421 const VectorType *CV = CondTy->getAs<VectorType>();
8422 assert(CV);
8423
8424 // Determine the vector result type
8425 unsigned NumElements = CV->getNumElements();
8426 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8427
8428 // Ensure that all types have the same number of bits
8430 != S.Context.getTypeSize(ResTy)) {
8431 // Since VectorTy is created internally, it does not pretty print
8432 // with an OpenCL name. Instead, we just print a description.
8433 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8434 SmallString<64> Str;
8435 llvm::raw_svector_ostream OS(Str);
8436 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8437 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8438 << CondTy << OS.str();
8439 return QualType();
8440 }
8441
8442 // Convert operands to the vector result type
8443 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8444 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8445
8446 return VectorTy;
8447}
8448
8449/// Return false if this is a valid OpenCL condition vector
8451 SourceLocation QuestionLoc) {
8452 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8453 // integral type.
8454 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8455 assert(CondTy);
8456 QualType EleTy = CondTy->getElementType();
8457 if (EleTy->isIntegerType()) return false;
8458
8459 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8460 << Cond->getType() << Cond->getSourceRange();
8461 return true;
8462}
8463
8464/// Return false if the vector condition type and the vector
8465/// result type are compatible.
8466///
8467/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8468/// number of elements, and their element types have the same number
8469/// of bits.
8470static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8471 SourceLocation QuestionLoc) {
8472 const VectorType *CV = CondTy->getAs<VectorType>();
8473 const VectorType *RV = VecResTy->getAs<VectorType>();
8474 assert(CV && RV);
8475
8476 if (CV->getNumElements() != RV->getNumElements()) {
8477 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8478 << CondTy << VecResTy;
8479 return true;
8480 }
8481
8482 QualType CVE = CV->getElementType();
8483 QualType RVE = RV->getElementType();
8484
8485 // Boolean vectors are permitted outside of OpenCL mode.
8486 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE) &&
8487 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8488 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8489 << CondTy << VecResTy;
8490 return true;
8491 }
8492
8493 return false;
8494}
8495
8496/// Return the resulting type for the conditional operator in
8497/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8498/// s6.3.i) when the condition is a vector type.
8499static QualType
8501 ExprResult &LHS, ExprResult &RHS,
8502 SourceLocation QuestionLoc) {
8504 if (Cond.isInvalid())
8505 return QualType();
8506 QualType CondTy = Cond.get()->getType();
8507
8508 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8509 return QualType();
8510
8511 // If either operand is a vector then find the vector type of the
8512 // result as specified in OpenCL v1.1 s6.3.i.
8513 if (LHS.get()->getType()->isVectorType() ||
8514 RHS.get()->getType()->isVectorType()) {
8515 bool IsBoolVecLang =
8516 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8517 QualType VecResTy =
8518 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8519 /*isCompAssign*/ false,
8520 /*AllowBothBool*/ true,
8521 /*AllowBoolConversions*/ false,
8522 /*AllowBooleanOperation*/ IsBoolVecLang,
8523 /*ReportInvalid*/ true);
8524 if (VecResTy.isNull())
8525 return QualType();
8526 // The result type must match the condition type as specified in
8527 // OpenCL v1.1 s6.11.6.
8528 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8529 return QualType();
8530 return VecResTy;
8531 }
8532
8533 // Both operands are scalar.
8534 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8535}
8536
8537/// Return true if the Expr is block type
8538static bool checkBlockType(Sema &S, const Expr *E) {
8539 if (E->getType()->isBlockPointerType()) {
8540 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8541 return true;
8542 }
8543
8544 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8545 QualType Ty = CE->getCallee()->getType();
8546 if (Ty->isBlockPointerType()) {
8547 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8548 return true;
8549 }
8550 }
8551 return false;
8552}
8553
8554/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8555/// In that case, LHS = cond.
8556/// C99 6.5.15
8559 ExprObjectKind &OK,
8560 SourceLocation QuestionLoc) {
8561
8562 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8563 if (!LHSResult.isUsable()) return QualType();
8564 LHS = LHSResult;
8565
8566 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8567 if (!RHSResult.isUsable()) return QualType();
8568 RHS = RHSResult;
8569
8570 // C++ is sufficiently different to merit its own checker.
8571 if (getLangOpts().CPlusPlus)
8572 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8573
8574 VK = VK_PRValue;
8575 OK = OK_Ordinary;
8576
8577 if (Context.isDependenceAllowed() &&
8578 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8579 RHS.get()->isTypeDependent())) {
8580 assert(!getLangOpts().CPlusPlus);
8581 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8582 RHS.get()->containsErrors()) &&
8583 "should only occur in error-recovery path.");
8584 return Context.DependentTy;
8585 }
8586
8587 // The OpenCL operator with a vector condition is sufficiently
8588 // different to merit its own checker.
8589 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8590 Cond.get()->getType()->isExtVectorType())
8591 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8592
8593 // First, check the condition.
8595 if (Cond.isInvalid())
8596 return QualType();
8597 if (checkCondition(*this, Cond.get(), QuestionLoc))
8598 return QualType();
8599
8600 // Handle vectors.
8601 if (LHS.get()->getType()->isVectorType() ||
8602 RHS.get()->getType()->isVectorType())
8603 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8604 /*AllowBothBool*/ true,
8605 /*AllowBoolConversions*/ false,
8606 /*AllowBooleanOperation*/ false,
8607 /*ReportInvalid*/ true);
8608
8609 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
8611 if (LHS.isInvalid() || RHS.isInvalid())
8612 return QualType();
8613
8614 // WebAssembly tables are not allowed as conditional LHS or RHS.
8615 QualType LHSTy = LHS.get()->getType();
8616 QualType RHSTy = RHS.get()->getType();
8617 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8618 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8619 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8620 return QualType();
8621 }
8622
8623 // Diagnose attempts to convert between __ibm128, __float128 and long double
8624 // where such conversions currently can't be handled.
8625 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8626 Diag(QuestionLoc,
8627 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8628 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8629 return QualType();
8630 }
8631
8632 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8633 // selection operator (?:).
8634 if (getLangOpts().OpenCL &&
8635 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8636 return QualType();
8637 }
8638
8639 // If both operands have arithmetic type, do the usual arithmetic conversions
8640 // to find a common type: C99 6.5.15p3,5.
8641 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8642 // Disallow invalid arithmetic conversions, such as those between bit-
8643 // precise integers types of different sizes, or between a bit-precise
8644 // integer and another type.
8645 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8646 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8647 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8648 << RHS.get()->getSourceRange();
8649 return QualType();
8650 }
8651
8652 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8653 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8654
8655 return ResTy;
8656 }
8657
8658 // If both operands are the same structure or union type, the result is that
8659 // type.
8660 // FIXME: Type of conditional expression must be complete in C mode.
8661 if (LHSTy->isRecordType() &&
8662 Context.hasSameUnqualifiedType(LHSTy, RHSTy)) // C99 6.5.15p3
8663 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
8664 RHSTy.getUnqualifiedType());
8665
8666 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8667 // The following || allows only one side to be void (a GCC-ism).
8668 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8669 QualType ResTy;
8670 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8671 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8672 } else if (RHSTy->isVoidType()) {
8673 ResTy = RHSTy;
8674 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8675 << RHS.get()->getSourceRange();
8676 } else {
8677 ResTy = LHSTy;
8678 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8679 << LHS.get()->getSourceRange();
8680 }
8681 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8682 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8683 return ResTy;
8684 }
8685
8686 // C23 6.5.15p7:
8687 // ... if both the second and third operands have nullptr_t type, the
8688 // result also has that type.
8689 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8690 return ResTy;
8691
8692 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8693 // the type of the other operand."
8694 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8695 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8696
8697 // All objective-c pointer type analysis is done here.
8698 QualType compositeType =
8699 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8700 if (LHS.isInvalid() || RHS.isInvalid())
8701 return QualType();
8702 if (!compositeType.isNull())
8703 return compositeType;
8704
8705
8706 // Handle block pointer types.
8707 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8708 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8709 QuestionLoc);
8710
8711 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8712 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8713 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8714 QuestionLoc);
8715
8716 // GCC compatibility: soften pointer/integer mismatch. Note that
8717 // null pointers have been filtered out by this point.
8718 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8719 /*IsIntFirstExpr=*/true))
8720 return RHSTy;
8721 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8722 /*IsIntFirstExpr=*/false))
8723 return LHSTy;
8724
8725 // Emit a better diagnostic if one of the expressions is a null pointer
8726 // constant and the other is not a pointer type. In this case, the user most
8727 // likely forgot to take the address of the other expression.
8728 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8729 return QualType();
8730
8731 // Finally, if the LHS and RHS types are canonically the same type, we can
8732 // use the common sugared type.
8733 if (Context.hasSameType(LHSTy, RHSTy))
8734 return Context.getCommonSugaredType(LHSTy, RHSTy);
8735
8736 // Otherwise, the operands are not compatible.
8737 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8738 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8739 << RHS.get()->getSourceRange();
8740 return QualType();
8741}
8742
8743/// SuggestParentheses - Emit a note with a fixit hint that wraps
8744/// ParenRange in parentheses.
8746 const PartialDiagnostic &Note,
8747 SourceRange ParenRange) {
8748 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8749 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8750 EndLoc.isValid()) {
8751 Self.Diag(Loc, Note)
8752 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8753 << FixItHint::CreateInsertion(EndLoc, ")");
8754 } else {
8755 // We can't display the parentheses, so just show the bare note.
8756 Self.Diag(Loc, Note) << ParenRange;
8757 }
8758}
8759
8761 return BinaryOperator::isAdditiveOp(Opc) ||
8763 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8764 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8765 // not any of the logical operators. Bitwise-xor is commonly used as a
8766 // logical-xor because there is no logical-xor operator. The logical
8767 // operators, including uses of xor, have a high false positive rate for
8768 // precedence warnings.
8769}
8770
8771/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8772/// expression, either using a built-in or overloaded operator,
8773/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8774/// expression.
8775static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
8776 const Expr **RHSExprs) {
8777 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8778 E = E->IgnoreImpCasts();
8780 E = E->IgnoreImpCasts();
8781 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8782 E = MTE->getSubExpr();
8783 E = E->IgnoreImpCasts();
8784 }
8785
8786 // Built-in binary operator.
8787 if (const auto *OP = dyn_cast<BinaryOperator>(E);
8788 OP && IsArithmeticOp(OP->getOpcode())) {
8789 *Opcode = OP->getOpcode();
8790 *RHSExprs = OP->getRHS();
8791 return true;
8792 }
8793
8794 // Overloaded operator.
8795 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8796 if (Call->getNumArgs() != 2)
8797 return false;
8798
8799 // Make sure this is really a binary operator that is safe to pass into
8800 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8801 OverloadedOperatorKind OO = Call->getOperator();
8802 if (OO < OO_Plus || OO > OO_Arrow ||
8803 OO == OO_PlusPlus || OO == OO_MinusMinus)
8804 return false;
8805
8807 if (IsArithmeticOp(OpKind)) {
8808 *Opcode = OpKind;
8809 *RHSExprs = Call->getArg(1);
8810 return true;
8811 }
8812 }
8813
8814 return false;
8815}
8816
8817/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8818/// or is a logical expression such as (x==y) which has int type, but is
8819/// commonly interpreted as boolean.
8820static bool ExprLooksBoolean(const Expr *E) {
8821 E = E->IgnoreParenImpCasts();
8822
8823 if (E->getType()->isBooleanType())
8824 return true;
8825 if (const auto *OP = dyn_cast<BinaryOperator>(E))
8826 return OP->isComparisonOp() || OP->isLogicalOp();
8827 if (const auto *OP = dyn_cast<UnaryOperator>(E))
8828 return OP->getOpcode() == UO_LNot;
8829 if (E->getType()->isPointerType())
8830 return true;
8831 // FIXME: What about overloaded operator calls returning "unspecified boolean
8832 // type"s (commonly pointer-to-members)?
8833
8834 return false;
8835}
8836
8837/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8838/// and binary operator are mixed in a way that suggests the programmer assumed
8839/// the conditional operator has higher precedence, for example:
8840/// "int x = a + someBinaryCondition ? 1 : 2".
8842 Expr *Condition, const Expr *LHSExpr,
8843 const Expr *RHSExpr) {
8844 BinaryOperatorKind CondOpcode;
8845 const Expr *CondRHS;
8846
8847 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8848 return;
8849 if (!ExprLooksBoolean(CondRHS))
8850 return;
8851
8852 // The condition is an arithmetic binary expression, with a right-
8853 // hand side that looks boolean, so warn.
8854
8855 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8856 ? diag::warn_precedence_bitwise_conditional
8857 : diag::warn_precedence_conditional;
8858
8859 Self.Diag(OpLoc, DiagID)
8860 << Condition->getSourceRange()
8861 << BinaryOperator::getOpcodeStr(CondOpcode);
8862
8864 Self, OpLoc,
8865 Self.PDiag(diag::note_precedence_silence)
8866 << BinaryOperator::getOpcodeStr(CondOpcode),
8867 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8868
8869 SuggestParentheses(Self, OpLoc,
8870 Self.PDiag(diag::note_precedence_conditional_first),
8871 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8872}
8873
8874/// Compute the nullability of a conditional expression.
8876 QualType LHSTy, QualType RHSTy,
8877 ASTContext &Ctx) {
8878 if (!ResTy->isAnyPointerType())
8879 return ResTy;
8880
8881 auto GetNullability = [](QualType Ty) {
8882 std::optional<NullabilityKind> Kind = Ty->getNullability();
8883 if (Kind) {
8884 // For our purposes, treat _Nullable_result as _Nullable.
8887 return *Kind;
8888 }
8890 };
8891
8892 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8893 NullabilityKind MergedKind;
8894
8895 // Compute nullability of a binary conditional expression.
8896 if (IsBin) {
8897 if (LHSKind == NullabilityKind::NonNull)
8898 MergedKind = NullabilityKind::NonNull;
8899 else
8900 MergedKind = RHSKind;
8901 // Compute nullability of a normal conditional expression.
8902 } else {
8903 if (LHSKind == NullabilityKind::Nullable ||
8904 RHSKind == NullabilityKind::Nullable)
8905 MergedKind = NullabilityKind::Nullable;
8906 else if (LHSKind == NullabilityKind::NonNull)
8907 MergedKind = RHSKind;
8908 else if (RHSKind == NullabilityKind::NonNull)
8909 MergedKind = LHSKind;
8910 else
8911 MergedKind = NullabilityKind::Unspecified;
8912 }
8913
8914 // Return if ResTy already has the correct nullability.
8915 if (GetNullability(ResTy) == MergedKind)
8916 return ResTy;
8917
8918 // Strip all nullability from ResTy.
8919 while (ResTy->getNullability())
8920 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8921
8922 // Create a new AttributedType with the new nullability kind.
8923 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
8924}
8925
8927 SourceLocation ColonLoc,
8928 Expr *CondExpr, Expr *LHSExpr,
8929 Expr *RHSExpr) {
8930 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8931 // was the condition.
8932 OpaqueValueExpr *opaqueValue = nullptr;
8933 Expr *commonExpr = nullptr;
8934 if (!LHSExpr) {
8935 commonExpr = CondExpr;
8936 // Lower out placeholder types first. This is important so that we don't
8937 // try to capture a placeholder. This happens in few cases in C++; such
8938 // as Objective-C++'s dictionary subscripting syntax.
8939 if (commonExpr->hasPlaceholderType()) {
8940 ExprResult result = CheckPlaceholderExpr(commonExpr);
8941 if (!result.isUsable()) return ExprError();
8942 commonExpr = result.get();
8943 }
8944 // We usually want to apply unary conversions *before* saving, except
8945 // in the special case of a C++ l-value conditional.
8946 if (!(getLangOpts().CPlusPlus
8947 && !commonExpr->isTypeDependent()
8948 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8949 && commonExpr->isGLValue()
8950 && commonExpr->isOrdinaryOrBitFieldObject()
8951 && RHSExpr->isOrdinaryOrBitFieldObject()
8952 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8953 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8954 if (commonRes.isInvalid())
8955 return ExprError();
8956 commonExpr = commonRes.get();
8957 }
8958
8959 // If the common expression is a class or array prvalue, materialize it
8960 // so that we can safely refer to it multiple times.
8961 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8962 commonExpr->getType()->isArrayType())) {
8963 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8964 if (MatExpr.isInvalid())
8965 return ExprError();
8966 commonExpr = MatExpr.get();
8967 }
8968
8969 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8970 commonExpr->getType(),
8971 commonExpr->getValueKind(),
8972 commonExpr->getObjectKind(),
8973 commonExpr);
8974 LHSExpr = CondExpr = opaqueValue;
8975 }
8976
8977 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8980 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8981 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8982 VK, OK, QuestionLoc);
8983 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8984 RHS.isInvalid())
8985 return ExprError();
8986
8987 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8988 RHS.get());
8989
8990 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8991
8992 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8993 Context);
8994
8995 if (!commonExpr)
8996 return new (Context)
8997 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8998 RHS.get(), result, VK, OK);
8999
9001 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9002 ColonLoc, result, VK, OK);
9003}
9004
9006 unsigned FromAttributes = 0, ToAttributes = 0;
9007 if (const auto *FromFn =
9008 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9009 FromAttributes =
9010 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9011 if (const auto *ToFn =
9012 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9013 ToAttributes =
9014 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9015
9016 return FromAttributes != ToAttributes;
9017}
9018
9019// checkPointerTypesForAssignment - This is a very tricky routine (despite
9020// being closely modeled after the C99 spec:-). The odd characteristic of this
9021// routine is it effectively iqnores the qualifiers on the top level pointee.
9022// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9023// FIXME: add a couple examples in this comment.
9025 QualType LHSType,
9026 QualType RHSType,
9027 SourceLocation Loc) {
9028 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9029 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9030
9031 // get the "pointed to" type (ignoring qualifiers at the top level)
9032 const Type *lhptee, *rhptee;
9033 Qualifiers lhq, rhq;
9034 std::tie(lhptee, lhq) =
9035 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9036 std::tie(rhptee, rhq) =
9037 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9038
9040
9041 // C99 6.5.16.1p1: This following citation is common to constraints
9042 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9043 // qualifiers of the type *pointed to* by the right;
9044
9045 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9046 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9048 // Ignore lifetime for further calculation.
9049 lhq.removeObjCLifetime();
9050 rhq.removeObjCLifetime();
9051 }
9052
9053 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
9054 // Treat address-space mismatches as fatal.
9055 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
9057
9058 // It's okay to add or remove GC or lifetime qualifiers when converting to
9059 // and from void*.
9062 S.getASTContext()) &&
9063 (lhptee->isVoidType() || rhptee->isVoidType()))
9064 ; // keep old
9065
9066 // Treat lifetime mismatches as fatal.
9067 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9069
9070 // Treat pointer-auth mismatches as fatal.
9071 else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth()))
9073
9074 // For GCC/MS compatibility, other qualifier mismatches are treated
9075 // as still compatible in C.
9076 else
9078 }
9079
9080 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9081 // incomplete type and the other is a pointer to a qualified or unqualified
9082 // version of void...
9083 if (lhptee->isVoidType()) {
9084 if (rhptee->isIncompleteOrObjectType())
9085 return ConvTy;
9086
9087 // As an extension, we allow cast to/from void* to function pointer.
9088 assert(rhptee->isFunctionType());
9090 }
9091
9092 if (rhptee->isVoidType()) {
9093 // In C, void * to another pointer type is compatible, but we want to note
9094 // that there will be an implicit conversion happening here.
9095 if (lhptee->isIncompleteOrObjectType())
9096 return ConvTy == AssignConvertType::Compatible &&
9097 !S.getLangOpts().CPlusPlus
9099 : ConvTy;
9100
9101 // As an extension, we allow cast to/from void* to function pointer.
9102 assert(lhptee->isFunctionType());
9104 }
9105
9106 if (!S.Diags.isIgnored(
9107 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9108 Loc) &&
9109 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9110 !S.TryFunctionConversion(RHSType, LHSType, RHSType))
9112
9113 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9114 // unqualified versions of compatible types, ...
9115 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9116 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9117 // Check if the pointee types are compatible ignoring the sign.
9118 // We explicitly check for char so that we catch "char" vs
9119 // "unsigned char" on systems where "char" is unsigned.
9120 if (lhptee->isCharType())
9121 ltrans = S.Context.UnsignedCharTy;
9122 else if (lhptee->hasSignedIntegerRepresentation())
9123 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9124
9125 if (rhptee->isCharType())
9126 rtrans = S.Context.UnsignedCharTy;
9127 else if (rhptee->hasSignedIntegerRepresentation())
9128 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9129
9130 if (ltrans == rtrans) {
9131 // Types are compatible ignoring the sign. Qualifier incompatibility
9132 // takes priority over sign incompatibility because the sign
9133 // warning can be disabled.
9134 if (!S.IsAssignConvertCompatible(ConvTy))
9135 return ConvTy;
9136
9138 }
9139
9140 // If we are a multi-level pointer, it's possible that our issue is simply
9141 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9142 // the eventual target type is the same and the pointers have the same
9143 // level of indirection, this must be the issue.
9144 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9145 do {
9146 std::tie(lhptee, lhq) =
9147 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9148 std::tie(rhptee, rhq) =
9149 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9150
9151 // Inconsistent address spaces at this point is invalid, even if the
9152 // address spaces would be compatible.
9153 // FIXME: This doesn't catch address space mismatches for pointers of
9154 // different nesting levels, like:
9155 // __local int *** a;
9156 // int ** b = a;
9157 // It's not clear how to actually determine when such pointers are
9158 // invalidly incompatible.
9159 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9160 return AssignConvertType::
9161 IncompatibleNestedPointerAddressSpaceMismatch;
9162
9163 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9164
9165 if (lhptee == rhptee)
9167 }
9168
9169 // General pointer incompatibility takes priority over qualifiers.
9170 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9173 }
9174 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9175 // hasSameType, so we can skip further checks.
9176 const auto *LFT = ltrans->getAs<FunctionType>();
9177 const auto *RFT = rtrans->getAs<FunctionType>();
9178 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9179 // The invocation of IsFunctionConversion below will try to transform rtrans
9180 // to obtain an exact match for ltrans. This should not fail because of
9181 // mismatches in result type and parameter types, they were already checked
9182 // by typesAreCompatible above. So we will recreate rtrans (or where
9183 // appropriate ltrans) using the result type and parameter types from ltrans
9184 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9185 const auto *LFPT = dyn_cast<FunctionProtoType>(LFT);
9186 const auto *RFPT = dyn_cast<FunctionProtoType>(RFT);
9187 if (LFPT && RFPT) {
9188 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9189 LFPT->getParamTypes(),
9190 RFPT->getExtProtoInfo());
9191 } else if (LFPT) {
9193 EPI.ExtInfo = RFT->getExtInfo();
9194 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9195 LFPT->getParamTypes(), EPI);
9196 } else if (RFPT) {
9197 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9198 // all of its ExtProtoInfo. Transform ltrans instead.
9200 EPI.ExtInfo = LFT->getExtInfo();
9201 ltrans = S.Context.getFunctionType(RFPT->getReturnType(),
9202 RFPT->getParamTypes(), EPI);
9203 } else {
9204 rtrans = S.Context.getFunctionNoProtoType(LFT->getReturnType(),
9205 RFT->getExtInfo());
9206 }
9207 if (!S.Context.hasSameUnqualifiedType(rtrans, ltrans) &&
9208 !S.IsFunctionConversion(rtrans, ltrans))
9210 }
9211 return ConvTy;
9212}
9213
9214/// checkBlockPointerTypesForAssignment - This routine determines whether two
9215/// block pointer types are compatible or whether a block and normal pointer
9216/// are compatible. It is more restrict than comparing two function pointer
9217// types.
9219 QualType LHSType,
9220 QualType RHSType) {
9221 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9222 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9223
9224 QualType lhptee, rhptee;
9225
9226 // get the "pointed to" type (ignoring qualifiers at the top level)
9227 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9228 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9229
9230 // In C++, the types have to match exactly.
9231 if (S.getLangOpts().CPlusPlus)
9233
9235
9236 // For blocks we enforce that qualifiers are identical.
9237 Qualifiers LQuals = lhptee.getLocalQualifiers();
9238 Qualifiers RQuals = rhptee.getLocalQualifiers();
9239 if (S.getLangOpts().OpenCL) {
9240 LQuals.removeAddressSpace();
9241 RQuals.removeAddressSpace();
9242 }
9243 if (LQuals != RQuals)
9245
9246 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9247 // assignment.
9248 // The current behavior is similar to C++ lambdas. A block might be
9249 // assigned to a variable iff its return type and parameters are compatible
9250 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9251 // an assignment. Presumably it should behave in way that a function pointer
9252 // assignment does in C, so for each parameter and return type:
9253 // * CVR and address space of LHS should be a superset of CVR and address
9254 // space of RHS.
9255 // * unqualified types should be compatible.
9256 if (S.getLangOpts().OpenCL) {
9258 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9259 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9261 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9263
9264 return ConvTy;
9265}
9266
9267/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9268/// for assignment compatibility.
9270 QualType LHSType,
9271 QualType RHSType) {
9272 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9273 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9274
9275 if (LHSType->isObjCBuiltinType()) {
9276 // Class is not compatible with ObjC object pointers.
9277 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9278 !RHSType->isObjCQualifiedClassType())
9281 }
9282 if (RHSType->isObjCBuiltinType()) {
9283 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9284 !LHSType->isObjCQualifiedClassType())
9287 }
9288 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9289 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9290
9291 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9292 // make an exception for id<P>
9293 !LHSType->isObjCQualifiedIdType())
9295
9296 if (S.Context.typesAreCompatible(LHSType, RHSType))
9298 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9301}
9302
9304 QualType LHSType,
9305 QualType RHSType) {
9306 // Fake up an opaque expression. We don't actually care about what
9307 // cast operations are required, so if CheckAssignmentConstraints
9308 // adds casts to this they'll be wasted, but fortunately that doesn't
9309 // usually happen on valid code.
9310 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9311 ExprResult RHSPtr = &RHSExpr;
9312 CastKind K;
9313
9314 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9315}
9316
9317/// This helper function returns true if QT is a vector type that has element
9318/// type ElementType.
9319static bool isVector(QualType QT, QualType ElementType) {
9320 if (const VectorType *VT = QT->getAs<VectorType>())
9321 return VT->getElementType().getCanonicalType() == ElementType;
9322 return false;
9323}
9324
9325/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9326/// has code to accommodate several GCC extensions when type checking
9327/// pointers. Here are some objectionable examples that GCC considers warnings:
9328///
9329/// int a, *pint;
9330/// short *pshort;
9331/// struct foo *pfoo;
9332///
9333/// pint = pshort; // warning: assignment from incompatible pointer type
9334/// a = pint; // warning: assignment makes integer from pointer without a cast
9335/// pint = a; // warning: assignment makes pointer from integer without a cast
9336/// pint = pfoo; // warning: assignment from incompatible pointer type
9337///
9338/// As a result, the code for dealing with pointers is more complex than the
9339/// C99 spec dictates.
9340///
9341/// Sets 'Kind' for any result kind except Incompatible.
9343 ExprResult &RHS,
9344 CastKind &Kind,
9345 bool ConvertRHS) {
9346 QualType RHSType = RHS.get()->getType();
9347 QualType OrigLHSType = LHSType;
9348
9349 // Get canonical types. We're not formatting these types, just comparing
9350 // them.
9351 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9352 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9353
9354 // Common case: no conversion required.
9355 if (LHSType == RHSType) {
9356 Kind = CK_NoOp;
9358 }
9359
9360 // If the LHS has an __auto_type, there are no additional type constraints
9361 // to be worried about.
9362 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9363 if (AT->isGNUAutoType()) {
9364 Kind = CK_NoOp;
9366 }
9367 }
9368
9369 // If we have an atomic type, try a non-atomic assignment, then just add an
9370 // atomic qualification step.
9371 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9373 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9375 return Result;
9376 if (Kind != CK_NoOp && ConvertRHS)
9377 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9378 Kind = CK_NonAtomicToAtomic;
9379 return Result;
9380 }
9381
9382 // If the left-hand side is a reference type, then we are in a
9383 // (rare!) case where we've allowed the use of references in C,
9384 // e.g., as a parameter type in a built-in function. In this case,
9385 // just make sure that the type referenced is compatible with the
9386 // right-hand side type. The caller is responsible for adjusting
9387 // LHSType so that the resulting expression does not have reference
9388 // type.
9389 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9390 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9391 Kind = CK_LValueBitCast;
9393 }
9395 }
9396
9397 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9398 // of an ExtVector type to the same ExtVector type.
9399 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9400 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9401 // Implicit conversions require the same number of elements.
9402 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9404
9405 if (LHSType->isExtVectorBoolType() &&
9406 RHSExtType->getElementType()->isIntegerType()) {
9407 Kind = CK_IntegralToBoolean;
9409 }
9411 }
9412 if (RHSType->isArithmeticType()) {
9413 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9414 if (ConvertRHS)
9415 RHS = prepareVectorSplat(LHSType, RHS.get());
9416 Kind = CK_VectorSplat;
9418 }
9419 }
9420
9421 // Conversions to or from vector type.
9422 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9423 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9424 // Allow assignments of an AltiVec vector type to an equivalent GCC
9425 // vector type and vice versa
9426 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9427 Kind = CK_BitCast;
9429 }
9430
9431 // If we are allowing lax vector conversions, and LHS and RHS are both
9432 // vectors, the total size only needs to be the same. This is a bitcast;
9433 // no bits are changed but the result type is different.
9434 if (isLaxVectorConversion(RHSType, LHSType)) {
9435 // The default for lax vector conversions with Altivec vectors will
9436 // change, so if we are converting between vector types where
9437 // at least one is an Altivec vector, emit a warning.
9438 if (Context.getTargetInfo().getTriple().isPPC() &&
9439 anyAltivecTypes(RHSType, LHSType) &&
9440 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9441 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9442 << RHSType << LHSType;
9443 Kind = CK_BitCast;
9445 }
9446 }
9447
9448 // When the RHS comes from another lax conversion (e.g. binops between
9449 // scalars and vectors) the result is canonicalized as a vector. When the
9450 // LHS is also a vector, the lax is allowed by the condition above. Handle
9451 // the case where LHS is a scalar.
9452 if (LHSType->isScalarType()) {
9453 const VectorType *VecType = RHSType->getAs<VectorType>();
9454 if (VecType && VecType->getNumElements() == 1 &&
9455 isLaxVectorConversion(RHSType, LHSType)) {
9456 if (Context.getTargetInfo().getTriple().isPPC() &&
9458 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9460 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9461 << RHSType << LHSType;
9462 ExprResult *VecExpr = &RHS;
9463 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9464 Kind = CK_BitCast;
9466 }
9467 }
9468
9469 // Allow assignments between fixed-length and sizeless SVE vectors.
9470 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9471 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9472 if (ARM().areCompatibleSveTypes(LHSType, RHSType) ||
9473 ARM().areLaxCompatibleSveTypes(LHSType, RHSType)) {
9474 Kind = CK_BitCast;
9476 }
9477
9478 // Allow assignments between fixed-length and sizeless RVV vectors.
9479 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9480 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9481 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9482 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9483 Kind = CK_BitCast;
9485 }
9486 }
9487
9489 }
9490
9491 // Diagnose attempts to convert between __ibm128, __float128 and long double
9492 // where such conversions currently can't be handled.
9493 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9495
9496 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9497 // discards the imaginary part.
9498 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9499 !LHSType->getAs<ComplexType>())
9501
9502 // Arithmetic conversions.
9503 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9504 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9505 if (ConvertRHS)
9506 Kind = PrepareScalarCast(RHS, LHSType);
9508 }
9509
9510 // Conversions to normal pointers.
9511 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9512 // U* -> T*
9513 if (isa<PointerType>(RHSType)) {
9514 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9515 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9516 if (AddrSpaceL != AddrSpaceR)
9517 Kind = CK_AddressSpaceConversion;
9518 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9519 Kind = CK_NoOp;
9520 else
9521 Kind = CK_BitCast;
9522 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9523 RHS.get()->getBeginLoc());
9524 }
9525
9526 // int -> T*
9527 if (RHSType->isIntegerType()) {
9528 Kind = CK_IntegralToPointer; // FIXME: null?
9530 }
9531
9532 // C pointers are not compatible with ObjC object pointers,
9533 // with two exceptions:
9534 if (isa<ObjCObjectPointerType>(RHSType)) {
9535 // - conversions to void*
9536 if (LHSPointer->getPointeeType()->isVoidType()) {
9537 Kind = CK_BitCast;
9539 }
9540
9541 // - conversions from 'Class' to the redefinition type
9542 if (RHSType->isObjCClassType() &&
9543 Context.hasSameType(LHSType,
9544 Context.getObjCClassRedefinitionType())) {
9545 Kind = CK_BitCast;
9547 }
9548
9549 Kind = CK_BitCast;
9551 }
9552
9553 // U^ -> void*
9554 if (RHSType->getAs<BlockPointerType>()) {
9555 if (LHSPointer->getPointeeType()->isVoidType()) {
9556 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9557 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9558 ->getPointeeType()
9559 .getAddressSpace();
9560 Kind =
9561 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9563 }
9564 }
9565
9567 }
9568
9569 // Conversions to block pointers.
9570 if (isa<BlockPointerType>(LHSType)) {
9571 // U^ -> T^
9572 if (RHSType->isBlockPointerType()) {
9573 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9574 ->getPointeeType()
9575 .getAddressSpace();
9576 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9577 ->getPointeeType()
9578 .getAddressSpace();
9579 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9580 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9581 }
9582
9583 // int or null -> T^
9584 if (RHSType->isIntegerType()) {
9585 Kind = CK_IntegralToPointer; // FIXME: null
9587 }
9588
9589 // id -> T^
9590 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9591 Kind = CK_AnyPointerToBlockPointerCast;
9593 }
9594
9595 // void* -> T^
9596 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9597 if (RHSPT->getPointeeType()->isVoidType()) {
9598 Kind = CK_AnyPointerToBlockPointerCast;
9600 }
9601
9603 }
9604
9605 // Conversions to Objective-C pointers.
9606 if (isa<ObjCObjectPointerType>(LHSType)) {
9607 // A* -> B*
9608 if (RHSType->isObjCObjectPointerType()) {
9609 Kind = CK_BitCast;
9610 AssignConvertType result =
9611 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9612 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9614 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9616 return result;
9617 }
9618
9619 // int or null -> A*
9620 if (RHSType->isIntegerType()) {
9621 Kind = CK_IntegralToPointer; // FIXME: null
9623 }
9624
9625 // In general, C pointers are not compatible with ObjC object pointers,
9626 // with two exceptions:
9627 if (isa<PointerType>(RHSType)) {
9628 Kind = CK_CPointerToObjCPointerCast;
9629
9630 // - conversions from 'void*'
9631 if (RHSType->isVoidPointerType()) {
9633 }
9634
9635 // - conversions to 'Class' from its redefinition type
9636 if (LHSType->isObjCClassType() &&
9637 Context.hasSameType(RHSType,
9638 Context.getObjCClassRedefinitionType())) {
9640 }
9641
9643 }
9644
9645 // Only under strict condition T^ is compatible with an Objective-C pointer.
9646 if (RHSType->isBlockPointerType() &&
9648 if (ConvertRHS)
9650 Kind = CK_BlockPointerToObjCPointerCast;
9652 }
9653
9655 }
9656
9657 // Conversion to nullptr_t (C23 only)
9658 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9661 // null -> nullptr_t
9662 Kind = CK_NullToPointer;
9664 }
9665
9666 // Conversions from pointers that are not covered by the above.
9667 if (isa<PointerType>(RHSType)) {
9668 // T* -> _Bool
9669 if (LHSType == Context.BoolTy) {
9670 Kind = CK_PointerToBoolean;
9672 }
9673
9674 // T* -> int
9675 if (LHSType->isIntegerType()) {
9676 Kind = CK_PointerToIntegral;
9678 }
9679
9681 }
9682
9683 // Conversions from Objective-C pointers that are not covered by the above.
9684 if (isa<ObjCObjectPointerType>(RHSType)) {
9685 // T* -> _Bool
9686 if (LHSType == Context.BoolTy) {
9687 Kind = CK_PointerToBoolean;
9689 }
9690
9691 // T* -> int
9692 if (LHSType->isIntegerType()) {
9693 Kind = CK_PointerToIntegral;
9695 }
9696
9698 }
9699
9700 // struct A -> struct B
9701 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9702 if (Context.typesAreCompatible(LHSType, RHSType)) {
9703 Kind = CK_NoOp;
9705 }
9706 }
9707
9708 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9709 Kind = CK_IntToOCLSampler;
9711 }
9712
9714}
9715
9716/// Constructs a transparent union from an expression that is
9717/// used to initialize the transparent union.
9719 ExprResult &EResult, QualType UnionType,
9720 FieldDecl *Field) {
9721 // Build an initializer list that designates the appropriate member
9722 // of the transparent union.
9723 Expr *E = EResult.get();
9725 E, SourceLocation());
9726 Initializer->setType(UnionType);
9727 Initializer->setInitializedFieldInUnion(Field);
9728
9729 // Build a compound literal constructing a value of the transparent
9730 // union type from this initializer list.
9731 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9732 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9733 VK_PRValue, Initializer, false);
9734}
9735
9738 ExprResult &RHS) {
9739 QualType RHSType = RHS.get()->getType();
9740
9741 // If the ArgType is a Union type, we want to handle a potential
9742 // transparent_union GCC extension.
9743 const RecordType *UT = ArgType->getAsUnionType();
9744 if (!UT)
9746
9747 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
9748 if (!UD->hasAttr<TransparentUnionAttr>())
9750
9751 // The field to initialize within the transparent union.
9752 FieldDecl *InitField = nullptr;
9753 // It's compatible if the expression matches any of the fields.
9754 for (auto *it : UD->fields()) {
9755 if (it->getType()->isPointerType()) {
9756 // If the transparent union contains a pointer type, we allow:
9757 // 1) void pointer
9758 // 2) null pointer constant
9759 if (RHSType->isPointerType())
9760 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9761 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9762 InitField = it;
9763 break;
9764 }
9765
9768 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9769 CK_NullToPointer);
9770 InitField = it;
9771 break;
9772 }
9773 }
9774
9775 CastKind Kind;
9776 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) ==
9778 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9779 InitField = it;
9780 break;
9781 }
9782 }
9783
9784 if (!InitField)
9786
9787 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9789}
9790
9792 ExprResult &CallerRHS,
9793 bool Diagnose,
9794 bool DiagnoseCFAudited,
9795 bool ConvertRHS) {
9796 // We need to be able to tell the caller whether we diagnosed a problem, if
9797 // they ask us to issue diagnostics.
9798 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9799
9800 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9801 // we can't avoid *all* modifications at the moment, so we need some somewhere
9802 // to put the updated value.
9803 ExprResult LocalRHS = CallerRHS;
9804 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9805
9806 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9807 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9808 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9809 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9810 Diag(RHS.get()->getExprLoc(),
9811 diag::warn_noderef_to_dereferenceable_pointer)
9812 << RHS.get()->getSourceRange();
9813 }
9814 }
9815 }
9816
9817 if (getLangOpts().CPlusPlus) {
9818 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9819 // C++ 5.17p3: If the left operand is not of class type, the
9820 // expression is implicitly converted (C++ 4) to the
9821 // cv-unqualified type of the left operand.
9822 QualType RHSType = RHS.get()->getType();
9823 if (Diagnose) {
9824 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9826 } else {
9829 /*SuppressUserConversions=*/false,
9830 AllowedExplicit::None,
9831 /*InOverloadResolution=*/false,
9832 /*CStyle=*/false,
9833 /*AllowObjCWritebackConversion=*/false);
9834 if (ICS.isFailure())
9836 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9838 }
9839 if (RHS.isInvalid())
9842 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9843 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9845 return result;
9846 }
9847
9848 // FIXME: Currently, we fall through and treat C++ classes like C
9849 // structures.
9850 // FIXME: We also fall through for atomics; not sure what should
9851 // happen there, though.
9852 } else if (RHS.get()->getType() == Context.OverloadTy) {
9853 // As a set of extensions to C, we support overloading on functions. These
9854 // functions need to be resolved here.
9855 DeclAccessPair DAP;
9857 RHS.get(), LHSType, /*Complain=*/false, DAP))
9858 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9859 else
9861 }
9862
9863 // This check seems unnatural, however it is necessary to ensure the proper
9864 // conversion of functions/arrays. If the conversion were done for all
9865 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9866 // expressions that suppress this implicit conversion (&, sizeof). This needs
9867 // to happen before we check for null pointer conversions because C does not
9868 // undergo the same implicit conversions as C++ does above (by the calls to
9869 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
9870 // lvalue to rvalue cast before checking for null pointer constraints. This
9871 // addresses code like: nullptr_t val; int *ptr; ptr = val;
9872 //
9873 // Suppress this for references: C++ 8.5.3p5.
9874 if (!LHSType->isReferenceType()) {
9875 // FIXME: We potentially allocate here even if ConvertRHS is false.
9877 if (RHS.isInvalid())
9879 }
9880
9881 // The constraints are expressed in terms of the atomic, qualified, or
9882 // unqualified type of the LHS.
9883 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
9884
9885 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9886 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
9887 if ((LHSTypeAfterConversion->isPointerType() ||
9888 LHSTypeAfterConversion->isObjCObjectPointerType() ||
9889 LHSTypeAfterConversion->isBlockPointerType()) &&
9890 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
9894 if (Diagnose || ConvertRHS) {
9895 CastKind Kind;
9896 CXXCastPath Path;
9897 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9898 /*IgnoreBaseAccess=*/false, Diagnose);
9899
9900 // If there is a conversion of some kind, check to see what kind of
9901 // pointer conversion happened so we can diagnose a C++ compatibility
9902 // diagnostic if the conversion is invalid. This only matters if the RHS
9903 // is some kind of void pointer. We have a carve-out when the RHS is from
9904 // a macro expansion because the use of a macro may indicate different
9905 // code between C and C++. Consider: char *s = NULL; where NULL is
9906 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
9907 // C++, which is valid in C++.
9908 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
9909 !RHS.get()->getBeginLoc().isMacroID()) {
9910 QualType CanRHS =
9912 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
9913 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
9914 Ret = checkPointerTypesForAssignment(*this, CanLHS, CanRHS,
9915 RHS.get()->getExprLoc());
9916 // Anything that's not considered perfectly compatible would be
9917 // incompatible in C++.
9920 }
9921 }
9922
9923 if (ConvertRHS)
9924 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9925 }
9926 return Ret;
9927 }
9928 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
9929 // unqualified bool, and the right operand is a pointer or its type is
9930 // nullptr_t.
9931 if (getLangOpts().C23 && LHSType->isBooleanType() &&
9932 RHS.get()->getType()->isNullPtrType()) {
9933 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
9934 // only handles nullptr -> _Bool due to needing an extra conversion
9935 // step.
9936 // We model this by converting from nullptr -> void * and then let the
9937 // conversion from void * -> _Bool happen naturally.
9938 if (Diagnose || ConvertRHS) {
9939 CastKind Kind;
9940 CXXCastPath Path;
9941 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
9942 /*IgnoreBaseAccess=*/false, Diagnose);
9943 if (ConvertRHS)
9944 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
9945 &Path);
9946 }
9947 }
9948
9949 // OpenCL queue_t type assignment.
9950 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9952 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9954 }
9955
9956 CastKind Kind;
9957 AssignConvertType result =
9958 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9959
9960 // If assigning a void * created by an allocation function call to some other
9961 // type, check that the allocated size is sufficient for that type.
9962 if (result != AssignConvertType::Incompatible &&
9963 RHS.get()->getType()->isVoidPointerType())
9964 CheckSufficientAllocSize(*this, LHSType, RHS.get());
9965
9966 // C99 6.5.16.1p2: The value of the right operand is converted to the
9967 // type of the assignment expression.
9968 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9969 // so that we can use references in built-in functions even in C.
9970 // The getNonReferenceType() call makes sure that the resulting expression
9971 // does not have reference type.
9972 if (result != AssignConvertType::Incompatible &&
9973 RHS.get()->getType() != LHSType) {
9975 Expr *E = RHS.get();
9976
9977 // Check for various Objective-C errors. If we are not reporting
9978 // diagnostics and just checking for errors, e.g., during overload
9979 // resolution, return Incompatible to indicate the failure.
9980 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9981 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
9983 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
9984 if (!Diagnose)
9986 }
9987 if (getLangOpts().ObjC &&
9988 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9989 E->getType(), E, Diagnose) ||
9990 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9991 if (!Diagnose)
9993 // Replace the expression with a corrected version and continue so we
9994 // can find further errors.
9995 RHS = E;
9997 }
9998
9999 if (ConvertRHS)
10000 RHS = ImpCastExprToType(E, Ty, Kind);
10001 }
10002
10003 return result;
10004}
10005
10006namespace {
10007/// The original operand to an operator, prior to the application of the usual
10008/// arithmetic conversions and converting the arguments of a builtin operator
10009/// candidate.
10010struct OriginalOperand {
10011 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10012 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10013 Op = MTE->getSubExpr();
10014 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10015 Op = BTE->getSubExpr();
10016 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10017 Orig = ICE->getSubExprAsWritten();
10018 Conversion = ICE->getConversionFunction();
10019 }
10020 }
10021
10022 QualType getType() const { return Orig->getType(); }
10023
10024 Expr *Orig;
10025 NamedDecl *Conversion;
10026};
10027}
10028
10030 ExprResult &RHS) {
10031 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10032
10033 Diag(Loc, diag::err_typecheck_invalid_operands)
10034 << OrigLHS.getType() << OrigRHS.getType()
10035 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10036
10037 // If a user-defined conversion was applied to either of the operands prior
10038 // to applying the built-in operator rules, tell the user about it.
10039 if (OrigLHS.Conversion) {
10040 Diag(OrigLHS.Conversion->getLocation(),
10041 diag::note_typecheck_invalid_operands_converted)
10042 << 0 << LHS.get()->getType();
10043 }
10044 if (OrigRHS.Conversion) {
10045 Diag(OrigRHS.Conversion->getLocation(),
10046 diag::note_typecheck_invalid_operands_converted)
10047 << 1 << RHS.get()->getType();
10048 }
10049
10050 return QualType();
10051}
10052
10054 ExprResult &RHS) {
10055 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10056 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10057
10058 bool LHSNatVec = LHSType->isVectorType();
10059 bool RHSNatVec = RHSType->isVectorType();
10060
10061 if (!(LHSNatVec && RHSNatVec)) {
10062 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10063 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10064 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10065 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10066 << Vector->getSourceRange();
10067 return QualType();
10068 }
10069
10070 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10071 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10072 << RHS.get()->getSourceRange();
10073
10074 return QualType();
10075}
10076
10077/// Try to convert a value of non-vector type to a vector type by converting
10078/// the type to the element type of the vector and then performing a splat.
10079/// If the language is OpenCL, we only use conversions that promote scalar
10080/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10081/// for float->int.
10082///
10083/// OpenCL V2.0 6.2.6.p2:
10084/// An error shall occur if any scalar operand type has greater rank
10085/// than the type of the vector element.
10086///
10087/// \param scalar - if non-null, actually perform the conversions
10088/// \return true if the operation fails (but without diagnosing the failure)
10090 QualType scalarTy,
10091 QualType vectorEltTy,
10092 QualType vectorTy,
10093 unsigned &DiagID) {
10094 // The conversion to apply to the scalar before splatting it,
10095 // if necessary.
10096 CastKind scalarCast = CK_NoOp;
10097
10098 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
10099 scalarCast = CK_IntegralToBoolean;
10100 } else if (vectorEltTy->isIntegralType(S.Context)) {
10101 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10102 (scalarTy->isIntegerType() &&
10103 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10104 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10105 return true;
10106 }
10107 if (!scalarTy->isIntegralType(S.Context))
10108 return true;
10109 scalarCast = CK_IntegralCast;
10110 } else if (vectorEltTy->isRealFloatingType()) {
10111 if (scalarTy->isRealFloatingType()) {
10112 if (S.getLangOpts().OpenCL &&
10113 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10114 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10115 return true;
10116 }
10117 scalarCast = CK_FloatingCast;
10118 }
10119 else if (scalarTy->isIntegralType(S.Context))
10120 scalarCast = CK_IntegralToFloating;
10121 else
10122 return true;
10123 } else {
10124 return true;
10125 }
10126
10127 // Adjust scalar if desired.
10128 if (scalar) {
10129 if (scalarCast != CK_NoOp)
10130 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10131 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10132 }
10133 return false;
10134}
10135
10136/// Convert vector E to a vector with the same number of elements but different
10137/// element type.
10138static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10139 const auto *VecTy = E->getType()->getAs<VectorType>();
10140 assert(VecTy && "Expression E must be a vector");
10141 QualType NewVecTy =
10142 VecTy->isExtVectorType()
10143 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10144 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10145 VecTy->getVectorKind());
10146
10147 // Look through the implicit cast. Return the subexpression if its type is
10148 // NewVecTy.
10149 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10150 if (ICE->getSubExpr()->getType() == NewVecTy)
10151 return ICE->getSubExpr();
10152
10153 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10154 return S.ImpCastExprToType(E, NewVecTy, Cast);
10155}
10156
10157/// Test if a (constant) integer Int can be casted to another integer type
10158/// IntTy without losing precision.
10160 QualType OtherIntTy) {
10161 if (Int->get()->containsErrors())
10162 return false;
10163
10164 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10165
10166 // Reject cases where the value of the Int is unknown as that would
10167 // possibly cause truncation, but accept cases where the scalar can be
10168 // demoted without loss of precision.
10169 Expr::EvalResult EVResult;
10170 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10171 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10172 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10173 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10174
10175 if (CstInt) {
10176 // If the scalar is constant and is of a higher order and has more active
10177 // bits that the vector element type, reject it.
10178 llvm::APSInt Result = EVResult.Val.getInt();
10179 unsigned NumBits = IntSigned
10180 ? (Result.isNegative() ? Result.getSignificantBits()
10181 : Result.getActiveBits())
10182 : Result.getActiveBits();
10183 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10184 return true;
10185
10186 // If the signedness of the scalar type and the vector element type
10187 // differs and the number of bits is greater than that of the vector
10188 // element reject it.
10189 return (IntSigned != OtherIntSigned &&
10190 NumBits > S.Context.getIntWidth(OtherIntTy));
10191 }
10192
10193 // Reject cases where the value of the scalar is not constant and it's
10194 // order is greater than that of the vector element type.
10195 return (Order < 0);
10196}
10197
10198/// Test if a (constant) integer Int can be casted to floating point type
10199/// FloatTy without losing precision.
10201 QualType FloatTy) {
10202 if (Int->get()->containsErrors())
10203 return false;
10204
10205 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10206
10207 // Determine if the integer constant can be expressed as a floating point
10208 // number of the appropriate type.
10209 Expr::EvalResult EVResult;
10210 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10211
10212 uint64_t Bits = 0;
10213 if (CstInt) {
10214 // Reject constants that would be truncated if they were converted to
10215 // the floating point type. Test by simple to/from conversion.
10216 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10217 // could be avoided if there was a convertFromAPInt method
10218 // which could signal back if implicit truncation occurred.
10219 llvm::APSInt Result = EVResult.Val.getInt();
10220 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10221 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10222 llvm::APFloat::rmTowardZero);
10223 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10225 bool Ignored = false;
10226 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10227 &Ignored);
10228 if (Result != ConvertBack)
10229 return true;
10230 } else {
10231 // Reject types that cannot be fully encoded into the mantissa of
10232 // the float.
10233 Bits = S.Context.getTypeSize(IntTy);
10234 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10235 S.Context.getFloatTypeSemantics(FloatTy));
10236 if (Bits > FloatPrec)
10237 return true;
10238 }
10239
10240 return false;
10241}
10242
10243/// Attempt to convert and splat Scalar into a vector whose types matches
10244/// Vector following GCC conversion rules. The rule is that implicit
10245/// conversion can occur when Scalar can be casted to match Vector's element
10246/// type without causing truncation of Scalar.
10248 ExprResult *Vector) {
10249 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10250 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10251 QualType VectorEltTy;
10252
10253 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10254 assert(!isa<ExtVectorType>(VT) &&
10255 "ExtVectorTypes should not be handled here!");
10256 VectorEltTy = VT->getElementType();
10257 } else if (VectorTy->isSveVLSBuiltinType()) {
10258 VectorEltTy =
10259 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10260 } else {
10261 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10262 }
10263
10264 // Reject cases where the vector element type or the scalar element type are
10265 // not integral or floating point types.
10266 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10267 return true;
10268
10269 // The conversion to apply to the scalar before splatting it,
10270 // if necessary.
10271 CastKind ScalarCast = CK_NoOp;
10272
10273 // Accept cases where the vector elements are integers and the scalar is
10274 // an integer.
10275 // FIXME: Notionally if the scalar was a floating point value with a precise
10276 // integral representation, we could cast it to an appropriate integer
10277 // type and then perform the rest of the checks here. GCC will perform
10278 // this conversion in some cases as determined by the input language.
10279 // We should accept it on a language independent basis.
10280 if (VectorEltTy->isIntegralType(S.Context) &&
10281 ScalarTy->isIntegralType(S.Context) &&
10282 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10283
10284 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10285 return true;
10286
10287 ScalarCast = CK_IntegralCast;
10288 } else if (VectorEltTy->isIntegralType(S.Context) &&
10289 ScalarTy->isRealFloatingType()) {
10290 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10291 ScalarCast = CK_FloatingToIntegral;
10292 else
10293 return true;
10294 } else if (VectorEltTy->isRealFloatingType()) {
10295 if (ScalarTy->isRealFloatingType()) {
10296
10297 // Reject cases where the scalar type is not a constant and has a higher
10298 // Order than the vector element type.
10299 llvm::APFloat Result(0.0);
10300
10301 // Determine whether this is a constant scalar. In the event that the
10302 // value is dependent (and thus cannot be evaluated by the constant
10303 // evaluator), skip the evaluation. This will then diagnose once the
10304 // expression is instantiated.
10305 bool CstScalar = Scalar->get()->isValueDependent() ||
10306 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10307 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10308 if (!CstScalar && Order < 0)
10309 return true;
10310
10311 // If the scalar cannot be safely casted to the vector element type,
10312 // reject it.
10313 if (CstScalar) {
10314 bool Truncated = false;
10315 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10316 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10317 if (Truncated)
10318 return true;
10319 }
10320
10321 ScalarCast = CK_FloatingCast;
10322 } else if (ScalarTy->isIntegralType(S.Context)) {
10323 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10324 return true;
10325
10326 ScalarCast = CK_IntegralToFloating;
10327 } else
10328 return true;
10329 } else if (ScalarTy->isEnumeralType())
10330 return true;
10331
10332 // Adjust scalar if desired.
10333 if (ScalarCast != CK_NoOp)
10334 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10335 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10336 return false;
10337}
10338
10340 SourceLocation Loc, bool IsCompAssign,
10341 bool AllowBothBool,
10342 bool AllowBoolConversions,
10343 bool AllowBoolOperation,
10344 bool ReportInvalid) {
10345 if (!IsCompAssign) {
10347 if (LHS.isInvalid())
10348 return QualType();
10349 }
10351 if (RHS.isInvalid())
10352 return QualType();
10353
10354 // For conversion purposes, we ignore any qualifiers.
10355 // For example, "const float" and "float" are equivalent.
10356 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10357 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10358
10359 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10360 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10361 assert(LHSVecType || RHSVecType);
10362
10363 if (getLangOpts().HLSL)
10364 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10365 IsCompAssign);
10366
10367 // Any operation with MFloat8 type is only possible with C intrinsics
10368 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10369 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10370 return InvalidOperands(Loc, LHS, RHS);
10371
10372 // AltiVec-style "vector bool op vector bool" combinations are allowed
10373 // for some operators but not others.
10374 if (!AllowBothBool && LHSVecType &&
10375 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10376 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10377 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10378
10379 // This operation may not be performed on boolean vectors.
10380 if (!AllowBoolOperation &&
10381 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10382 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10383
10384 // If the vector types are identical, return.
10385 if (Context.hasSameType(LHSType, RHSType))
10386 return Context.getCommonSugaredType(LHSType, RHSType);
10387
10388 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10389 if (LHSVecType && RHSVecType &&
10390 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10391 if (isa<ExtVectorType>(LHSVecType)) {
10392 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10393 return LHSType;
10394 }
10395
10396 if (!IsCompAssign)
10397 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10398 return RHSType;
10399 }
10400
10401 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10402 // can be mixed, with the result being the non-bool type. The non-bool
10403 // operand must have integer element type.
10404 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10405 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10406 (Context.getTypeSize(LHSVecType->getElementType()) ==
10407 Context.getTypeSize(RHSVecType->getElementType()))) {
10408 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10409 LHSVecType->getElementType()->isIntegerType() &&
10410 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10411 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10412 return LHSType;
10413 }
10414 if (!IsCompAssign &&
10415 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10416 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10417 RHSVecType->getElementType()->isIntegerType()) {
10418 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10419 return RHSType;
10420 }
10421 }
10422
10423 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10424 // invalid since the ambiguity can affect the ABI.
10425 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10426 unsigned &SVEorRVV) {
10427 const VectorType *VecType = SecondType->getAs<VectorType>();
10428 SVEorRVV = 0;
10429 if (FirstType->isSizelessBuiltinType() && VecType) {
10432 return true;
10438 SVEorRVV = 1;
10439 return true;
10440 }
10441 }
10442
10443 return false;
10444 };
10445
10446 unsigned SVEorRVV;
10447 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10448 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10449 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10450 << SVEorRVV << LHSType << RHSType;
10451 return QualType();
10452 }
10453
10454 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10455 // invalid since the ambiguity can affect the ABI.
10456 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10457 unsigned &SVEorRVV) {
10458 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10459 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10460
10461 SVEorRVV = 0;
10462 if (FirstVecType && SecondVecType) {
10463 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10464 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10465 SecondVecType->getVectorKind() ==
10467 return true;
10468 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10469 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10470 SecondVecType->getVectorKind() ==
10472 SecondVecType->getVectorKind() ==
10474 SecondVecType->getVectorKind() ==
10476 SVEorRVV = 1;
10477 return true;
10478 }
10479 }
10480 return false;
10481 }
10482
10483 if (SecondVecType &&
10484 SecondVecType->getVectorKind() == VectorKind::Generic) {
10485 if (FirstType->isSVESizelessBuiltinType())
10486 return true;
10487 if (FirstType->isRVVSizelessBuiltinType()) {
10488 SVEorRVV = 1;
10489 return true;
10490 }
10491 }
10492
10493 return false;
10494 };
10495
10496 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10497 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10498 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10499 << SVEorRVV << LHSType << RHSType;
10500 return QualType();
10501 }
10502
10503 // If there's a vector type and a scalar, try to convert the scalar to
10504 // the vector element type and splat.
10505 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10506 if (!RHSVecType) {
10507 if (isa<ExtVectorType>(LHSVecType)) {
10508 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10509 LHSVecType->getElementType(), LHSType,
10510 DiagID))
10511 return LHSType;
10512 } else {
10513 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10514 return LHSType;
10515 }
10516 }
10517 if (!LHSVecType) {
10518 if (isa<ExtVectorType>(RHSVecType)) {
10519 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10520 LHSType, RHSVecType->getElementType(),
10521 RHSType, DiagID))
10522 return RHSType;
10523 } else {
10524 if (LHS.get()->isLValue() ||
10525 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10526 return RHSType;
10527 }
10528 }
10529
10530 // FIXME: The code below also handles conversion between vectors and
10531 // non-scalars, we should break this down into fine grained specific checks
10532 // and emit proper diagnostics.
10533 QualType VecType = LHSVecType ? LHSType : RHSType;
10534 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10535 QualType OtherType = LHSVecType ? RHSType : LHSType;
10536 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10537 if (isLaxVectorConversion(OtherType, VecType)) {
10538 if (Context.getTargetInfo().getTriple().isPPC() &&
10539 anyAltivecTypes(RHSType, LHSType) &&
10540 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10541 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10542 // If we're allowing lax vector conversions, only the total (data) size
10543 // needs to be the same. For non compound assignment, if one of the types is
10544 // scalar, the result is always the vector type.
10545 if (!IsCompAssign) {
10546 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10547 return VecType;
10548 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10549 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10550 // type. Note that this is already done by non-compound assignments in
10551 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10552 // <1 x T> -> T. The result is also a vector type.
10553 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10554 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10555 ExprResult *RHSExpr = &RHS;
10556 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10557 return VecType;
10558 }
10559 }
10560
10561 // Okay, the expression is invalid.
10562
10563 // If there's a non-vector, non-real operand, diagnose that.
10564 if ((!RHSVecType && !RHSType->isRealType()) ||
10565 (!LHSVecType && !LHSType->isRealType())) {
10566 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10567 << LHSType << RHSType
10568 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10569 return QualType();
10570 }
10571
10572 // OpenCL V1.1 6.2.6.p1:
10573 // If the operands are of more than one vector type, then an error shall
10574 // occur. Implicit conversions between vector types are not permitted, per
10575 // section 6.2.1.
10576 if (getLangOpts().OpenCL &&
10577 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10578 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10579 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10580 << RHSType;
10581 return QualType();
10582 }
10583
10584
10585 // If there is a vector type that is not a ExtVector and a scalar, we reach
10586 // this point if scalar could not be converted to the vector's element type
10587 // without truncation.
10588 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10589 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10590 QualType Scalar = LHSVecType ? RHSType : LHSType;
10591 QualType Vector = LHSVecType ? LHSType : RHSType;
10592 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10593 Diag(Loc,
10594 diag::err_typecheck_vector_not_convertable_implict_truncation)
10595 << ScalarOrVector << Scalar << Vector;
10596
10597 return QualType();
10598 }
10599
10600 // Otherwise, use the generic diagnostic.
10601 Diag(Loc, DiagID)
10602 << LHSType << RHSType
10603 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10604 return QualType();
10605}
10606
10608 SourceLocation Loc,
10609 bool IsCompAssign,
10610 ArithConvKind OperationKind) {
10611 if (!IsCompAssign) {
10613 if (LHS.isInvalid())
10614 return QualType();
10615 }
10617 if (RHS.isInvalid())
10618 return QualType();
10619
10620 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10621 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10622
10623 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10624 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10625
10626 unsigned DiagID = diag::err_typecheck_invalid_operands;
10627 if ((OperationKind == ArithConvKind::Arithmetic) &&
10628 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10629 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10630 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10631 << RHS.get()->getSourceRange();
10632 return QualType();
10633 }
10634
10635 if (Context.hasSameType(LHSType, RHSType))
10636 return LHSType;
10637
10638 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10639 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10640 return LHSType;
10641 }
10642 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10643 if (LHS.get()->isLValue() ||
10644 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10645 return RHSType;
10646 }
10647
10648 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10649 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10650 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10651 << LHSType << RHSType << LHS.get()->getSourceRange()
10652 << RHS.get()->getSourceRange();
10653 return QualType();
10654 }
10655
10656 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10657 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10658 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10659 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10660 << LHSType << RHSType << LHS.get()->getSourceRange()
10661 << RHS.get()->getSourceRange();
10662 return QualType();
10663 }
10664
10665 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10666 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10667 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10668 bool ScalarOrVector =
10669 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10670
10671 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10672 << ScalarOrVector << Scalar << Vector;
10673
10674 return QualType();
10675 }
10676
10677 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10678 << RHS.get()->getSourceRange();
10679 return QualType();
10680}
10681
10682// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10683// expression. These are mainly cases where the null pointer is used as an
10684// integer instead of a pointer.
10686 SourceLocation Loc, bool IsCompare) {
10687 // The canonical way to check for a GNU null is with isNullPointerConstant,
10688 // but we use a bit of a hack here for speed; this is a relatively
10689 // hot path, and isNullPointerConstant is slow.
10690 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10691 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10692
10693 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10694
10695 // Avoid analyzing cases where the result will either be invalid (and
10696 // diagnosed as such) or entirely valid and not something to warn about.
10697 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10698 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10699 return;
10700
10701 // Comparison operations would not make sense with a null pointer no matter
10702 // what the other expression is.
10703 if (!IsCompare) {
10704 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10705 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10706 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10707 return;
10708 }
10709
10710 // The rest of the operations only make sense with a null pointer
10711 // if the other expression is a pointer.
10712 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10713 NonNullType->canDecayToPointerType())
10714 return;
10715
10716 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10717 << LHSNull /* LHS is NULL */ << NonNullType
10718 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10719}
10720
10722 SourceLocation OpLoc) {
10723 // If the divisor is real, then this is real/real or complex/real division.
10724 // Either way there can be no precision loss.
10725 auto *CT = DivisorTy->getAs<ComplexType>();
10726 if (!CT)
10727 return;
10728
10729 QualType ElementType = CT->getElementType();
10730 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
10732 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
10733 return;
10734
10735 ASTContext &Ctx = S.getASTContext();
10736 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
10737 const llvm::fltSemantics &ElementTypeSemantics =
10738 Ctx.getFloatTypeSemantics(ElementType);
10739 const llvm::fltSemantics &HigherElementTypeSemantics =
10740 Ctx.getFloatTypeSemantics(HigherElementType);
10741
10742 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
10743 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
10744 (HigherElementType == Ctx.LongDoubleTy &&
10745 !Ctx.getTargetInfo().hasLongDoubleType())) {
10746 // Retain the location of the first use of higher precision type.
10749 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
10750 if (Type == HigherElementType) {
10751 Num++;
10752 return;
10753 }
10754 }
10755 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
10756 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
10757 }
10758}
10759
10761 SourceLocation Loc) {
10762 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10763 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10764 if (!LUE || !RUE)
10765 return;
10766 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10767 RUE->getKind() != UETT_SizeOf)
10768 return;
10769
10770 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10771 QualType LHSTy = LHSArg->getType();
10772 QualType RHSTy;
10773
10774 if (RUE->isArgumentType())
10775 RHSTy = RUE->getArgumentType().getNonReferenceType();
10776 else
10777 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10778
10779 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10780 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10781 return;
10782
10783 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10784 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10785 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10786 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10787 << LHSArgDecl;
10788 }
10789 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10790 QualType ArrayElemTy = ArrayTy->getElementType();
10791 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10792 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10793 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10794 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10795 return;
10796 S.Diag(Loc, diag::warn_division_sizeof_array)
10797 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10798 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10799 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10800 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10801 << LHSArgDecl;
10802 }
10803
10804 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10805 }
10806}
10807
10809 ExprResult &RHS,
10810 SourceLocation Loc, bool IsDiv) {
10811 // Check for division/remainder by zero.
10812 Expr::EvalResult RHSValue;
10813 if (!RHS.get()->isValueDependent() &&
10814 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10815 RHSValue.Val.getInt() == 0)
10816 S.DiagRuntimeBehavior(Loc, RHS.get(),
10817 S.PDiag(diag::warn_remainder_division_by_zero)
10818 << IsDiv << RHS.get()->getSourceRange());
10819}
10820
10821static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
10822 const ExprResult &LHS, const ExprResult &RHS,
10823 BinaryOperatorKind Opc) {
10824 if (!LHS.isUsable() || !RHS.isUsable())
10825 return;
10826 const Expr *LHSExpr = LHS.get();
10827 const Expr *RHSExpr = RHS.get();
10828 const QualType LHSType = LHSExpr->getType();
10829 const QualType RHSType = RHSExpr->getType();
10830 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
10831 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
10832 if (!LHSIsScoped && !RHSIsScoped)
10833 return;
10834 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
10835 return;
10836 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
10837 return;
10838 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
10839 return;
10840 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
10841 SourceLocation BeginLoc = expr->getBeginLoc();
10842 QualType IntType = type->castAs<EnumType>()
10843 ->getDecl()
10844 ->getDefinitionOrSelf()
10845 ->getIntegerType();
10846 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
10847 S.Diag(BeginLoc, diag::note_no_implicit_conversion_for_scoped_enum)
10848 << FixItHint::CreateInsertion(BeginLoc, InsertionString)
10849 << FixItHint::CreateInsertion(expr->getEndLoc(), ")");
10850 };
10851 if (LHSIsScoped) {
10852 DiagnosticHelper(LHSExpr, LHSType);
10853 }
10854 if (RHSIsScoped) {
10855 DiagnosticHelper(RHSExpr, RHSType);
10856 }
10857}
10858
10860 SourceLocation Loc,
10861 BinaryOperatorKind Opc) {
10862 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
10863 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
10864
10865 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10866
10867 QualType LHSTy = LHS.get()->getType();
10868 QualType RHSTy = RHS.get()->getType();
10869 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10870 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10871 /*AllowBothBool*/ getLangOpts().AltiVec,
10872 /*AllowBoolConversions*/ false,
10873 /*AllowBooleanOperation*/ false,
10874 /*ReportInvalid*/ true);
10875 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10876 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10878 if (!IsDiv &&
10879 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10880 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10881 // For division, only matrix-by-scalar is supported. Other combinations with
10882 // matrix types are invalid.
10883 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10884 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10885
10887 LHS, RHS, Loc,
10889 if (LHS.isInvalid() || RHS.isInvalid())
10890 return QualType();
10891
10892 if (compType.isNull() || !compType->isArithmeticType()) {
10893 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
10894 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
10895 return ResultTy;
10896 }
10897 if (IsDiv) {
10898 DetectPrecisionLossInComplexDivision(*this, RHS.get()->getType(), Loc);
10899 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10900 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10901 }
10902 return compType;
10903}
10904
10906 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10907 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10908
10909 // Note: This check is here to simplify the double exclusions of
10910 // scalar and vector HLSL checks. No getLangOpts().HLSL
10911 // is needed since all languages exlcude doubles.
10912 if (LHS.get()->getType()->isDoubleType() ||
10913 RHS.get()->getType()->isDoubleType() ||
10914 (LHS.get()->getType()->isVectorType() && LHS.get()
10915 ->getType()
10916 ->getAs<VectorType>()
10917 ->getElementType()
10918 ->isDoubleType()) ||
10919 (RHS.get()->getType()->isVectorType() && RHS.get()
10920 ->getType()
10921 ->getAs<VectorType>()
10922 ->getElementType()
10923 ->isDoubleType()))
10924 return InvalidOperands(Loc, LHS, RHS);
10925
10926 if (LHS.get()->getType()->isVectorType() ||
10927 RHS.get()->getType()->isVectorType()) {
10928 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
10929 RHS.get()->getType()->hasIntegerRepresentation()) ||
10930 (getLangOpts().HLSL &&
10931 (LHS.get()->getType()->hasFloatingRepresentation() ||
10933 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10934 /*AllowBothBool*/ getLangOpts().AltiVec,
10935 /*AllowBoolConversions*/ false,
10936 /*AllowBooleanOperation*/ false,
10937 /*ReportInvalid*/ true);
10938 return InvalidOperands(Loc, LHS, RHS);
10939 }
10940
10941 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10942 RHS.get()->getType()->isSveVLSBuiltinType()) {
10943 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10945 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10947
10948 return InvalidOperands(Loc, LHS, RHS);
10949 }
10950
10952 LHS, RHS, Loc,
10954 if (LHS.isInvalid() || RHS.isInvalid())
10955 return QualType();
10956
10957 if (compType.isNull() ||
10958 (!compType->isIntegerType() &&
10959 !(getLangOpts().HLSL && compType->isFloatingType()))) {
10960 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
10961 diagnoseScopedEnums(*this, Loc, LHS, RHS,
10962 IsCompAssign ? BO_RemAssign : BO_Rem);
10963 return ResultTy;
10964 }
10965 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10966 return compType;
10967}
10968
10969/// Diagnose invalid arithmetic on two void pointers.
10971 Expr *LHSExpr, Expr *RHSExpr) {
10972 S.Diag(Loc, S.getLangOpts().CPlusPlus
10973 ? diag::err_typecheck_pointer_arith_void_type
10974 : diag::ext_gnu_void_ptr)
10975 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10976 << RHSExpr->getSourceRange();
10977}
10978
10979/// Diagnose invalid arithmetic on a void pointer.
10981 Expr *Pointer) {
10982 S.Diag(Loc, S.getLangOpts().CPlusPlus
10983 ? diag::err_typecheck_pointer_arith_void_type
10984 : diag::ext_gnu_void_ptr)
10985 << 0 /* one pointer */ << Pointer->getSourceRange();
10986}
10987
10988/// Diagnose invalid arithmetic on a null pointer.
10989///
10990/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10991/// idiom, which we recognize as a GNU extension.
10992///
10994 Expr *Pointer, bool IsGNUIdiom) {
10995 if (IsGNUIdiom)
10996 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10997 << Pointer->getSourceRange();
10998 else
10999 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11000 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11001}
11002
11003/// Diagnose invalid subraction on a null pointer.
11004///
11006 Expr *Pointer, bool BothNull) {
11007 // Null - null is valid in C++ [expr.add]p7
11008 if (BothNull && S.getLangOpts().CPlusPlus)
11009 return;
11010
11011 // Is this s a macro from a system header?
11013 return;
11014
11016 S.PDiag(diag::warn_pointer_sub_null_ptr)
11017 << S.getLangOpts().CPlusPlus
11018 << Pointer->getSourceRange());
11019}
11020
11021/// Diagnose invalid arithmetic on two function pointers.
11023 Expr *LHS, Expr *RHS) {
11024 assert(LHS->getType()->isAnyPointerType());
11025 assert(RHS->getType()->isAnyPointerType());
11026 S.Diag(Loc, S.getLangOpts().CPlusPlus
11027 ? diag::err_typecheck_pointer_arith_function_type
11028 : diag::ext_gnu_ptr_func_arith)
11029 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11030 // We only show the second type if it differs from the first.
11032 RHS->getType())
11033 << RHS->getType()->getPointeeType()
11034 << LHS->getSourceRange() << RHS->getSourceRange();
11035}
11036
11037/// Diagnose invalid arithmetic on a function pointer.
11039 Expr *Pointer) {
11040 assert(Pointer->getType()->isAnyPointerType());
11041 S.Diag(Loc, S.getLangOpts().CPlusPlus
11042 ? diag::err_typecheck_pointer_arith_function_type
11043 : diag::ext_gnu_ptr_func_arith)
11044 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11045 << 0 /* one pointer, so only one type */
11046 << Pointer->getSourceRange();
11047}
11048
11049/// Emit error if Operand is incomplete pointer type
11050///
11051/// \returns True if pointer has incomplete type
11053 Expr *Operand) {
11054 QualType ResType = Operand->getType();
11055 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11056 ResType = ResAtomicType->getValueType();
11057
11058 assert(ResType->isAnyPointerType());
11059 QualType PointeeTy = ResType->getPointeeType();
11060 return S.RequireCompleteSizedType(
11061 Loc, PointeeTy,
11062 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11063 Operand->getSourceRange());
11064}
11065
11066/// Check the validity of an arithmetic pointer operand.
11067///
11068/// If the operand has pointer type, this code will check for pointer types
11069/// which are invalid in arithmetic operations. These will be diagnosed
11070/// appropriately, including whether or not the use is supported as an
11071/// extension.
11072///
11073/// \returns True when the operand is valid to use (even if as an extension).
11075 Expr *Operand) {
11076 QualType ResType = Operand->getType();
11077 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11078 ResType = ResAtomicType->getValueType();
11079
11080 if (!ResType->isAnyPointerType()) return true;
11081
11082 QualType PointeeTy = ResType->getPointeeType();
11083 if (PointeeTy->isVoidType()) {
11084 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11085 return !S.getLangOpts().CPlusPlus;
11086 }
11087 if (PointeeTy->isFunctionType()) {
11088 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11089 return !S.getLangOpts().CPlusPlus;
11090 }
11091
11092 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11093
11094 return true;
11095}
11096
11097/// Check the validity of a binary arithmetic operation w.r.t. pointer
11098/// operands.
11099///
11100/// This routine will diagnose any invalid arithmetic on pointer operands much
11101/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11102/// for emitting a single diagnostic even for operations where both LHS and RHS
11103/// are (potentially problematic) pointers.
11104///
11105/// \returns True when the operand is valid to use (even if as an extension).
11107 Expr *LHSExpr, Expr *RHSExpr) {
11108 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11109 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11110 if (!isLHSPointer && !isRHSPointer) return true;
11111
11112 QualType LHSPointeeTy, RHSPointeeTy;
11113 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11114 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11115
11116 // if both are pointers check if operation is valid wrt address spaces
11117 if (isLHSPointer && isRHSPointer) {
11118 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
11119 S.getASTContext())) {
11120 S.Diag(Loc,
11121 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11122 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11123 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11124 return false;
11125 }
11126 }
11127
11128 // Check for arithmetic on pointers to incomplete types.
11129 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11130 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11131 if (isLHSVoidPtr || isRHSVoidPtr) {
11132 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11133 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11134 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11135
11136 return !S.getLangOpts().CPlusPlus;
11137 }
11138
11139 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11140 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11141 if (isLHSFuncPtr || isRHSFuncPtr) {
11142 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11143 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11144 RHSExpr);
11145 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11146
11147 return !S.getLangOpts().CPlusPlus;
11148 }
11149
11150 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11151 return false;
11152 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11153 return false;
11154
11155 return true;
11156}
11157
11158/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11159/// literal.
11161 Expr *LHSExpr, Expr *RHSExpr) {
11162 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11163 Expr* IndexExpr = RHSExpr;
11164 if (!StrExpr) {
11165 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11166 IndexExpr = LHSExpr;
11167 }
11168
11169 bool IsStringPlusInt = StrExpr &&
11171 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11172 return;
11173
11174 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11175 Self.Diag(OpLoc, diag::warn_string_plus_int)
11176 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11177
11178 // Only print a fixit for "str" + int, not for int + "str".
11179 if (IndexExpr == RHSExpr) {
11180 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11181 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11182 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11184 << FixItHint::CreateInsertion(EndLoc, "]");
11185 } else
11186 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11187}
11188
11189/// Emit a warning when adding a char literal to a string.
11191 Expr *LHSExpr, Expr *RHSExpr) {
11192 const Expr *StringRefExpr = LHSExpr;
11193 const CharacterLiteral *CharExpr =
11194 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11195
11196 if (!CharExpr) {
11197 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11198 StringRefExpr = RHSExpr;
11199 }
11200
11201 if (!CharExpr || !StringRefExpr)
11202 return;
11203
11204 const QualType StringType = StringRefExpr->getType();
11205
11206 // Return if not a PointerType.
11207 if (!StringType->isAnyPointerType())
11208 return;
11209
11210 // Return if not a CharacterType.
11211 if (!StringType->getPointeeType()->isAnyCharacterType())
11212 return;
11213
11214 ASTContext &Ctx = Self.getASTContext();
11215 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11216
11217 const QualType CharType = CharExpr->getType();
11218 if (!CharType->isAnyCharacterType() &&
11219 CharType->isIntegerType() &&
11220 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11221 Self.Diag(OpLoc, diag::warn_string_plus_char)
11222 << DiagRange << Ctx.CharTy;
11223 } else {
11224 Self.Diag(OpLoc, diag::warn_string_plus_char)
11225 << DiagRange << CharExpr->getType();
11226 }
11227
11228 // Only print a fixit for str + char, not for char + str.
11229 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11230 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11231 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11232 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11234 << FixItHint::CreateInsertion(EndLoc, "]");
11235 } else {
11236 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11237 }
11238}
11239
11240/// Emit error when two pointers are incompatible.
11242 Expr *LHSExpr, Expr *RHSExpr) {
11243 assert(LHSExpr->getType()->isAnyPointerType());
11244 assert(RHSExpr->getType()->isAnyPointerType());
11245 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11246 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11247 << RHSExpr->getSourceRange();
11248}
11249
11250// C99 6.5.6
11253 QualType* CompLHSTy) {
11254 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11255
11256 if (LHS.get()->getType()->isVectorType() ||
11257 RHS.get()->getType()->isVectorType()) {
11258 QualType compType =
11259 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11260 /*AllowBothBool*/ getLangOpts().AltiVec,
11261 /*AllowBoolConversions*/ getLangOpts().ZVector,
11262 /*AllowBooleanOperation*/ false,
11263 /*ReportInvalid*/ true);
11264 if (CompLHSTy) *CompLHSTy = compType;
11265 return compType;
11266 }
11267
11268 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11269 RHS.get()->getType()->isSveVLSBuiltinType()) {
11270 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11272 if (CompLHSTy)
11273 *CompLHSTy = compType;
11274 return compType;
11275 }
11276
11277 if (LHS.get()->getType()->isConstantMatrixType() ||
11278 RHS.get()->getType()->isConstantMatrixType()) {
11279 QualType compType =
11280 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11281 if (CompLHSTy)
11282 *CompLHSTy = compType;
11283 return compType;
11284 }
11285
11287 LHS, RHS, Loc,
11289 if (LHS.isInvalid() || RHS.isInvalid())
11290 return QualType();
11291
11292 // Diagnose "string literal" '+' int and string '+' "char literal".
11293 if (Opc == BO_Add) {
11294 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11295 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11296 }
11297
11298 // handle the common case first (both operands are arithmetic).
11299 if (!compType.isNull() && compType->isArithmeticType()) {
11300 if (CompLHSTy) *CompLHSTy = compType;
11301 return compType;
11302 }
11303
11304 // Type-checking. Ultimately the pointer's going to be in PExp;
11305 // note that we bias towards the LHS being the pointer.
11306 Expr *PExp = LHS.get(), *IExp = RHS.get();
11307
11308 bool isObjCPointer;
11309 if (PExp->getType()->isPointerType()) {
11310 isObjCPointer = false;
11311 } else if (PExp->getType()->isObjCObjectPointerType()) {
11312 isObjCPointer = true;
11313 } else {
11314 std::swap(PExp, IExp);
11315 if (PExp->getType()->isPointerType()) {
11316 isObjCPointer = false;
11317 } else if (PExp->getType()->isObjCObjectPointerType()) {
11318 isObjCPointer = true;
11319 } else {
11320 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11321 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11322 return ResultTy;
11323 }
11324 }
11325 assert(PExp->getType()->isAnyPointerType());
11326
11327 if (!IExp->getType()->isIntegerType())
11328 return InvalidOperands(Loc, LHS, RHS);
11329
11330 // Adding to a null pointer results in undefined behavior.
11333 // In C++ adding zero to a null pointer is defined.
11334 Expr::EvalResult KnownVal;
11335 if (!getLangOpts().CPlusPlus ||
11336 (!IExp->isValueDependent() &&
11337 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11338 KnownVal.Val.getInt() != 0))) {
11339 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11341 Context, BO_Add, PExp, IExp);
11342 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11343 }
11344 }
11345
11346 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11347 return QualType();
11348
11349 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11350 return QualType();
11351
11352 // Arithmetic on label addresses is normally allowed, except when we add
11353 // a ptrauth signature to the addresses.
11354 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11355 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11356 << /*addition*/ 1;
11357 return QualType();
11358 }
11359
11360 // Check array bounds for pointer arithemtic
11361 CheckArrayAccess(PExp, IExp);
11362
11363 if (CompLHSTy) {
11364 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11365 if (LHSTy.isNull()) {
11366 LHSTy = LHS.get()->getType();
11367 if (Context.isPromotableIntegerType(LHSTy))
11368 LHSTy = Context.getPromotedIntegerType(LHSTy);
11369 }
11370 *CompLHSTy = LHSTy;
11371 }
11372
11373 return PExp->getType();
11374}
11375
11376// C99 6.5.6
11378 SourceLocation Loc,
11380 QualType *CompLHSTy) {
11381 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11382
11383 if (LHS.get()->getType()->isVectorType() ||
11384 RHS.get()->getType()->isVectorType()) {
11385 QualType compType =
11386 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11387 /*AllowBothBool*/ getLangOpts().AltiVec,
11388 /*AllowBoolConversions*/ getLangOpts().ZVector,
11389 /*AllowBooleanOperation*/ false,
11390 /*ReportInvalid*/ true);
11391 if (CompLHSTy) *CompLHSTy = compType;
11392 return compType;
11393 }
11394
11395 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11396 RHS.get()->getType()->isSveVLSBuiltinType()) {
11397 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11399 if (CompLHSTy)
11400 *CompLHSTy = compType;
11401 return compType;
11402 }
11403
11404 if (LHS.get()->getType()->isConstantMatrixType() ||
11405 RHS.get()->getType()->isConstantMatrixType()) {
11406 QualType compType =
11407 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11408 if (CompLHSTy)
11409 *CompLHSTy = compType;
11410 return compType;
11411 }
11412
11414 LHS, RHS, Loc,
11416 if (LHS.isInvalid() || RHS.isInvalid())
11417 return QualType();
11418
11419 // Enforce type constraints: C99 6.5.6p3.
11420
11421 // Handle the common case first (both operands are arithmetic).
11422 if (!compType.isNull() && compType->isArithmeticType()) {
11423 if (CompLHSTy) *CompLHSTy = compType;
11424 return compType;
11425 }
11426
11427 // Either ptr - int or ptr - ptr.
11428 if (LHS.get()->getType()->isAnyPointerType()) {
11429 QualType lpointee = LHS.get()->getType()->getPointeeType();
11430
11431 // Diagnose bad cases where we step over interface counts.
11432 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11433 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11434 return QualType();
11435
11436 // Arithmetic on label addresses is normally allowed, except when we add
11437 // a ptrauth signature to the addresses.
11438 if (isa<AddrLabelExpr>(LHS.get()) &&
11439 getLangOpts().PointerAuthIndirectGotos) {
11440 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11441 << /*subtraction*/ 0;
11442 return QualType();
11443 }
11444
11445 // The result type of a pointer-int computation is the pointer type.
11446 if (RHS.get()->getType()->isIntegerType()) {
11447 // Subtracting from a null pointer should produce a warning.
11448 // The last argument to the diagnose call says this doesn't match the
11449 // GNU int-to-pointer idiom.
11452 // In C++ adding zero to a null pointer is defined.
11453 Expr::EvalResult KnownVal;
11454 if (!getLangOpts().CPlusPlus ||
11455 (!RHS.get()->isValueDependent() &&
11456 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11457 KnownVal.Val.getInt() != 0))) {
11458 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11459 }
11460 }
11461
11462 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11463 return QualType();
11464
11465 // Check array bounds for pointer arithemtic
11466 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11467 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11468
11469 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11470 return LHS.get()->getType();
11471 }
11472
11473 // Handle pointer-pointer subtractions.
11474 if (const PointerType *RHSPTy
11475 = RHS.get()->getType()->getAs<PointerType>()) {
11476 QualType rpointee = RHSPTy->getPointeeType();
11477
11478 if (getLangOpts().CPlusPlus) {
11479 // Pointee types must be the same: C++ [expr.add]
11480 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11481 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11482 }
11483 } else {
11484 // Pointee types must be compatible C99 6.5.6p3
11485 if (!Context.typesAreCompatible(
11486 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11487 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11488 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11489 return QualType();
11490 }
11491 }
11492
11494 LHS.get(), RHS.get()))
11495 return QualType();
11496
11497 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11499 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11501
11502 // Subtracting nullptr or from nullptr is suspect
11503 if (LHSIsNullPtr)
11504 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11505 if (RHSIsNullPtr)
11506 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11507
11508 // The pointee type may have zero size. As an extension, a structure or
11509 // union may have zero size or an array may have zero length. In this
11510 // case subtraction does not make sense.
11511 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11512 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11513 if (ElementSize.isZero()) {
11514 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11515 << rpointee.getUnqualifiedType()
11516 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11517 }
11518 }
11519
11520 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11521 return Context.getPointerDiffType();
11522 }
11523 }
11524
11525 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11526 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11527 return ResultTy;
11528}
11529
11531 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11532 return ET->getDecl()->isScoped();
11533 return false;
11534}
11535
11538 QualType LHSType) {
11539 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11540 // so skip remaining warnings as we don't want to modify values within Sema.
11541 if (S.getLangOpts().OpenCL)
11542 return;
11543
11544 if (Opc == BO_Shr &&
11546 S.Diag(Loc, diag::warn_shift_bool) << LHS.get()->getSourceRange();
11547
11548 // Check right/shifter operand
11549 Expr::EvalResult RHSResult;
11550 if (RHS.get()->isValueDependent() ||
11551 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11552 return;
11553 llvm::APSInt Right = RHSResult.Val.getInt();
11554
11555 if (Right.isNegative()) {
11556 S.DiagRuntimeBehavior(Loc, RHS.get(),
11557 S.PDiag(diag::warn_shift_negative)
11558 << RHS.get()->getSourceRange());
11559 return;
11560 }
11561
11562 QualType LHSExprType = LHS.get()->getType();
11563 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11564 if (LHSExprType->isBitIntType())
11565 LeftSize = S.Context.getIntWidth(LHSExprType);
11566 else if (LHSExprType->isFixedPointType()) {
11567 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11568 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11569 }
11570 if (Right.uge(LeftSize)) {
11571 S.DiagRuntimeBehavior(Loc, RHS.get(),
11572 S.PDiag(diag::warn_shift_gt_typewidth)
11573 << RHS.get()->getSourceRange());
11574 return;
11575 }
11576
11577 // FIXME: We probably need to handle fixed point types specially here.
11578 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11579 return;
11580
11581 // When left shifting an ICE which is signed, we can check for overflow which
11582 // according to C++ standards prior to C++2a has undefined behavior
11583 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11584 // more than the maximum value representable in the result type, so never
11585 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11586 // expression is still probably a bug.)
11587 Expr::EvalResult LHSResult;
11588 if (LHS.get()->isValueDependent() ||
11590 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11591 return;
11592 llvm::APSInt Left = LHSResult.Val.getInt();
11593
11594 // Don't warn if signed overflow is defined, then all the rest of the
11595 // diagnostics will not be triggered because the behavior is defined.
11596 // Also don't warn in C++20 mode (and newer), as signed left shifts
11597 // always wrap and never overflow.
11598 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11599 return;
11600
11601 // If LHS does not have a non-negative value then, the
11602 // behavior is undefined before C++2a. Warn about it.
11603 if (Left.isNegative()) {
11604 S.DiagRuntimeBehavior(Loc, LHS.get(),
11605 S.PDiag(diag::warn_shift_lhs_negative)
11606 << LHS.get()->getSourceRange());
11607 return;
11608 }
11609
11610 llvm::APInt ResultBits =
11611 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11612 if (ResultBits.ule(LeftSize))
11613 return;
11614 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11615 Result = Result.shl(Right);
11616
11617 // Print the bit representation of the signed integer as an unsigned
11618 // hexadecimal number.
11619 SmallString<40> HexResult;
11620 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11621
11622 // If we are only missing a sign bit, this is less likely to result in actual
11623 // bugs -- if the result is cast back to an unsigned type, it will have the
11624 // expected value. Thus we place this behind a different warning that can be
11625 // turned off separately if needed.
11626 if (ResultBits - 1 == LeftSize) {
11627 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11628 << HexResult << LHSType
11629 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11630 return;
11631 }
11632
11633 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11634 << HexResult.str() << Result.getSignificantBits() << LHSType
11635 << Left.getBitWidth() << LHS.get()->getSourceRange()
11636 << RHS.get()->getSourceRange();
11637}
11638
11639/// Return the resulting type when a vector is shifted
11640/// by a scalar or vector shift amount.
11642 SourceLocation Loc, bool IsCompAssign) {
11643 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11644 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11645 !LHS.get()->getType()->isVectorType()) {
11646 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11647 << RHS.get()->getType() << LHS.get()->getType()
11648 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11649 return QualType();
11650 }
11651
11652 if (!IsCompAssign) {
11653 LHS = S.UsualUnaryConversions(LHS.get());
11654 if (LHS.isInvalid()) return QualType();
11655 }
11656
11657 RHS = S.UsualUnaryConversions(RHS.get());
11658 if (RHS.isInvalid()) return QualType();
11659
11660 QualType LHSType = LHS.get()->getType();
11661 // Note that LHS might be a scalar because the routine calls not only in
11662 // OpenCL case.
11663 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11664 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11665
11666 // Note that RHS might not be a vector.
11667 QualType RHSType = RHS.get()->getType();
11668 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11669 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11670
11671 // Do not allow shifts for boolean vectors.
11672 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11673 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11674 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11675 << LHS.get()->getType() << RHS.get()->getType()
11676 << LHS.get()->getSourceRange();
11677 return QualType();
11678 }
11679
11680 // The operands need to be integers.
11681 if (!LHSEleType->isIntegerType()) {
11682 S.Diag(Loc, diag::err_typecheck_expect_int)
11683 << LHS.get()->getType() << LHS.get()->getSourceRange();
11684 return QualType();
11685 }
11686
11687 if (!RHSEleType->isIntegerType()) {
11688 S.Diag(Loc, diag::err_typecheck_expect_int)
11689 << RHS.get()->getType() << RHS.get()->getSourceRange();
11690 return QualType();
11691 }
11692
11693 if (!LHSVecTy) {
11694 assert(RHSVecTy);
11695 if (IsCompAssign)
11696 return RHSType;
11697 if (LHSEleType != RHSEleType) {
11698 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11699 LHSEleType = RHSEleType;
11700 }
11701 QualType VecTy =
11702 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11703 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11704 LHSType = VecTy;
11705 } else if (RHSVecTy) {
11706 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11707 // are applied component-wise. So if RHS is a vector, then ensure
11708 // that the number of elements is the same as LHS...
11709 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11710 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11711 << LHS.get()->getType() << RHS.get()->getType()
11712 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11713 return QualType();
11714 }
11715 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11716 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11717 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11718 if (LHSBT != RHSBT &&
11719 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11720 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11721 << LHS.get()->getType() << RHS.get()->getType()
11722 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11723 }
11724 }
11725 } else {
11726 // ...else expand RHS to match the number of elements in LHS.
11727 QualType VecTy =
11728 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11729 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11730 }
11731
11732 return LHSType;
11733}
11734
11736 ExprResult &RHS, SourceLocation Loc,
11737 bool IsCompAssign) {
11738 if (!IsCompAssign) {
11739 LHS = S.UsualUnaryConversions(LHS.get());
11740 if (LHS.isInvalid())
11741 return QualType();
11742 }
11743
11744 RHS = S.UsualUnaryConversions(RHS.get());
11745 if (RHS.isInvalid())
11746 return QualType();
11747
11748 QualType LHSType = LHS.get()->getType();
11749 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11750 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11751 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11752 : LHSType;
11753
11754 // Note that RHS might not be a vector
11755 QualType RHSType = RHS.get()->getType();
11756 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11757 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11758 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11759 : RHSType;
11760
11761 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11762 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11763 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11764 << LHSType << RHSType << LHS.get()->getSourceRange();
11765 return QualType();
11766 }
11767
11768 if (!LHSEleType->isIntegerType()) {
11769 S.Diag(Loc, diag::err_typecheck_expect_int)
11770 << LHS.get()->getType() << LHS.get()->getSourceRange();
11771 return QualType();
11772 }
11773
11774 if (!RHSEleType->isIntegerType()) {
11775 S.Diag(Loc, diag::err_typecheck_expect_int)
11776 << RHS.get()->getType() << RHS.get()->getSourceRange();
11777 return QualType();
11778 }
11779
11780 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11781 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11782 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11783 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11784 << LHSType << RHSType << LHS.get()->getSourceRange()
11785 << RHS.get()->getSourceRange();
11786 return QualType();
11787 }
11788
11789 if (!LHSType->isSveVLSBuiltinType()) {
11790 assert(RHSType->isSveVLSBuiltinType());
11791 if (IsCompAssign)
11792 return RHSType;
11793 if (LHSEleType != RHSEleType) {
11794 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11795 LHSEleType = RHSEleType;
11796 }
11797 const llvm::ElementCount VecSize =
11798 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11799 QualType VecTy =
11800 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11801 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11802 LHSType = VecTy;
11803 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11804 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11805 S.Context.getTypeSize(LHSBuiltinTy)) {
11806 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11807 << LHSType << RHSType << LHS.get()->getSourceRange()
11808 << RHS.get()->getSourceRange();
11809 return QualType();
11810 }
11811 } else {
11812 const llvm::ElementCount VecSize =
11813 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11814 if (LHSEleType != RHSEleType) {
11815 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11816 RHSEleType = LHSEleType;
11817 }
11818 QualType VecTy =
11819 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11820 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11821 }
11822
11823 return LHSType;
11824}
11825
11826// C99 6.5.7
11829 bool IsCompAssign) {
11830 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11831
11832 // Vector shifts promote their scalar inputs to vector type.
11833 if (LHS.get()->getType()->isVectorType() ||
11834 RHS.get()->getType()->isVectorType()) {
11835 if (LangOpts.ZVector) {
11836 // The shift operators for the z vector extensions work basically
11837 // like general shifts, except that neither the LHS nor the RHS is
11838 // allowed to be a "vector bool".
11839 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11840 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11841 return InvalidOperands(Loc, LHS, RHS);
11842 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11843 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11844 return InvalidOperands(Loc, LHS, RHS);
11845 }
11846 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11847 }
11848
11849 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11850 RHS.get()->getType()->isSveVLSBuiltinType())
11851 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11852
11853 // Shifts don't perform usual arithmetic conversions, they just do integer
11854 // promotions on each operand. C99 6.5.7p3
11855
11856 // For the LHS, do usual unary conversions, but then reset them away
11857 // if this is a compound assignment.
11858 ExprResult OldLHS = LHS;
11859 LHS = UsualUnaryConversions(LHS.get());
11860 if (LHS.isInvalid())
11861 return QualType();
11862 QualType LHSType = LHS.get()->getType();
11863 if (IsCompAssign) LHS = OldLHS;
11864
11865 // The RHS is simpler.
11866 RHS = UsualUnaryConversions(RHS.get());
11867 if (RHS.isInvalid())
11868 return QualType();
11869 QualType RHSType = RHS.get()->getType();
11870
11871 // C99 6.5.7p2: Each of the operands shall have integer type.
11872 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11873 if ((!LHSType->isFixedPointOrIntegerType() &&
11874 !LHSType->hasIntegerRepresentation()) ||
11875 !RHSType->hasIntegerRepresentation()) {
11876 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11877 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11878 return ResultTy;
11879 }
11880
11881 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11882
11883 // "The type of the result is that of the promoted left operand."
11884 return LHSType;
11885}
11886
11887/// Diagnose bad pointer comparisons.
11889 ExprResult &LHS, ExprResult &RHS,
11890 bool IsError) {
11891 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11892 : diag::ext_typecheck_comparison_of_distinct_pointers)
11893 << LHS.get()->getType() << RHS.get()->getType()
11894 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11895}
11896
11897/// Returns false if the pointers are converted to a composite type,
11898/// true otherwise.
11900 ExprResult &LHS, ExprResult &RHS) {
11901 // C++ [expr.rel]p2:
11902 // [...] Pointer conversions (4.10) and qualification
11903 // conversions (4.4) are performed on pointer operands (or on
11904 // a pointer operand and a null pointer constant) to bring
11905 // them to their composite pointer type. [...]
11906 //
11907 // C++ [expr.eq]p1 uses the same notion for (in)equality
11908 // comparisons of pointers.
11909
11910 QualType LHSType = LHS.get()->getType();
11911 QualType RHSType = RHS.get()->getType();
11912 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11913 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11914
11915 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11916 if (T.isNull()) {
11917 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11918 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11919 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11920 else
11921 S.InvalidOperands(Loc, LHS, RHS);
11922 return true;
11923 }
11924
11925 return false;
11926}
11927
11929 ExprResult &LHS,
11930 ExprResult &RHS,
11931 bool IsError) {
11932 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11933 : diag::ext_typecheck_comparison_of_fptr_to_void)
11934 << LHS.get()->getType() << RHS.get()->getType()
11935 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11936}
11937
11939 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11940 case Stmt::ObjCArrayLiteralClass:
11941 case Stmt::ObjCDictionaryLiteralClass:
11942 case Stmt::ObjCStringLiteralClass:
11943 case Stmt::ObjCBoxedExprClass:
11944 return true;
11945 default:
11946 // Note that ObjCBoolLiteral is NOT an object literal!
11947 return false;
11948 }
11949}
11950
11951static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11954
11955 // If this is not actually an Objective-C object, bail out.
11956 if (!Type)
11957 return false;
11958
11959 // Get the LHS object's interface type.
11960 QualType InterfaceType = Type->getPointeeType();
11961
11962 // If the RHS isn't an Objective-C object, bail out.
11963 if (!RHS->getType()->isObjCObjectPointerType())
11964 return false;
11965
11966 // Try to find the -isEqual: method.
11967 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
11968 ObjCMethodDecl *Method =
11969 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
11970 /*IsInstance=*/true);
11971 if (!Method) {
11972 if (Type->isObjCIdType()) {
11973 // For 'id', just check the global pool.
11974 Method =
11976 /*receiverId=*/true);
11977 } else {
11978 // Check protocols.
11979 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
11980 /*IsInstance=*/true);
11981 }
11982 }
11983
11984 if (!Method)
11985 return false;
11986
11987 QualType T = Method->parameters()[0]->getType();
11988 if (!T->isObjCObjectPointerType())
11989 return false;
11990
11991 QualType R = Method->getReturnType();
11992 if (!R->isScalarType())
11993 return false;
11994
11995 return true;
11996}
11997
11999 ExprResult &LHS, ExprResult &RHS,
12001 Expr *Literal;
12002 Expr *Other;
12003 if (isObjCObjectLiteral(LHS)) {
12004 Literal = LHS.get();
12005 Other = RHS.get();
12006 } else {
12007 Literal = RHS.get();
12008 Other = LHS.get();
12009 }
12010
12011 // Don't warn on comparisons against nil.
12012 Other = Other->IgnoreParenCasts();
12013 if (Other->isNullPointerConstant(S.getASTContext(),
12015 return;
12016
12017 // This should be kept in sync with warn_objc_literal_comparison.
12018 // LK_String should always be after the other literals, since it has its own
12019 // warning flag.
12020 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
12021 assert(LiteralKind != SemaObjC::LK_Block);
12022 if (LiteralKind == SemaObjC::LK_None) {
12023 llvm_unreachable("Unknown Objective-C object literal kind");
12024 }
12025
12026 if (LiteralKind == SemaObjC::LK_String)
12027 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12028 << Literal->getSourceRange();
12029 else
12030 S.Diag(Loc, diag::warn_objc_literal_comparison)
12031 << LiteralKind << Literal->getSourceRange();
12032
12034 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12035 SourceLocation Start = LHS.get()->getBeginLoc();
12037 CharSourceRange OpRange =
12039
12040 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12041 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12042 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12043 << FixItHint::CreateInsertion(End, "]");
12044 }
12045}
12046
12047/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12049 ExprResult &RHS, SourceLocation Loc,
12050 BinaryOperatorKind Opc) {
12051 // Check that left hand side is !something.
12052 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12053 if (!UO || UO->getOpcode() != UO_LNot) return;
12054
12055 // Only check if the right hand side is non-bool arithmetic type.
12056 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12057
12058 // Make sure that the something in !something is not bool.
12059 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12060 if (SubExpr->isKnownToHaveBooleanValue()) return;
12061
12062 // Emit warning.
12063 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12064 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12065 << Loc << IsBitwiseOp;
12066
12067 // First note suggest !(x < y)
12068 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12069 SourceLocation FirstClose = RHS.get()->getEndLoc();
12070 FirstClose = S.getLocForEndOfToken(FirstClose);
12071 if (FirstClose.isInvalid())
12072 FirstOpen = SourceLocation();
12073 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12074 << IsBitwiseOp
12075 << FixItHint::CreateInsertion(FirstOpen, "(")
12076 << FixItHint::CreateInsertion(FirstClose, ")");
12077
12078 // Second note suggests (!x) < y
12079 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12080 SourceLocation SecondClose = LHS.get()->getEndLoc();
12081 SecondClose = S.getLocForEndOfToken(SecondClose);
12082 if (SecondClose.isInvalid())
12083 SecondOpen = SourceLocation();
12084 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12085 << FixItHint::CreateInsertion(SecondOpen, "(")
12086 << FixItHint::CreateInsertion(SecondClose, ")");
12087}
12088
12089// Returns true if E refers to a non-weak array.
12090static bool checkForArray(const Expr *E) {
12091 const ValueDecl *D = nullptr;
12092 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12093 D = DR->getDecl();
12094 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12095 if (Mem->isImplicitAccess())
12096 D = Mem->getMemberDecl();
12097 }
12098 if (!D)
12099 return false;
12100 return D->getType()->isArrayType() && !D->isWeak();
12101}
12102
12103/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12104/// pointer and size is an unsigned integer. Return whether the result is
12105/// always true/false.
12106static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12107 const Expr *RHS,
12108 BinaryOperatorKind Opc) {
12109 if (!LHS->getType()->isPointerType() ||
12110 S.getLangOpts().PointerOverflowDefined)
12111 return std::nullopt;
12112
12113 // Canonicalize to >= or < predicate.
12114 switch (Opc) {
12115 case BO_GE:
12116 case BO_LT:
12117 break;
12118 case BO_GT:
12119 std::swap(LHS, RHS);
12120 Opc = BO_LT;
12121 break;
12122 case BO_LE:
12123 std::swap(LHS, RHS);
12124 Opc = BO_GE;
12125 break;
12126 default:
12127 return std::nullopt;
12128 }
12129
12130 auto *BO = dyn_cast<BinaryOperator>(LHS);
12131 if (!BO || BO->getOpcode() != BO_Add)
12132 return std::nullopt;
12133
12134 Expr *Other;
12135 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
12136 Other = BO->getRHS();
12137 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
12138 Other = BO->getLHS();
12139 else
12140 return std::nullopt;
12141
12142 if (!Other->getType()->isUnsignedIntegerType())
12143 return std::nullopt;
12144
12145 return Opc == BO_GE;
12146}
12147
12148/// Diagnose some forms of syntactically-obvious tautological comparison.
12150 Expr *LHS, Expr *RHS,
12151 BinaryOperatorKind Opc) {
12152 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12153 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12154
12155 QualType LHSType = LHS->getType();
12156 QualType RHSType = RHS->getType();
12157 if (LHSType->hasFloatingRepresentation() ||
12158 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12160 return;
12161
12162 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12163 // Tautological diagnostics.
12164 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12165 return;
12166
12167 // Comparisons between two array types are ill-formed for operator<=>, so
12168 // we shouldn't emit any additional warnings about it.
12169 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12170 return;
12171
12172 // For non-floating point types, check for self-comparisons of the form
12173 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12174 // often indicate logic errors in the program.
12175 //
12176 // NOTE: Don't warn about comparison expressions resulting from macro
12177 // expansion. Also don't warn about comparisons which are only self
12178 // comparisons within a template instantiation. The warnings should catch
12179 // obvious cases in the definition of the template anyways. The idea is to
12180 // warn when the typed comparison operator will always evaluate to the same
12181 // result.
12182
12183 // Used for indexing into %select in warn_comparison_always
12184 enum {
12185 AlwaysConstant,
12186 AlwaysTrue,
12187 AlwaysFalse,
12188 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12189 };
12190
12191 // C++1a [array.comp]:
12192 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12193 // operands of array type.
12194 // C++2a [depr.array.comp]:
12195 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12196 // operands of array type are deprecated.
12197 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12198 RHSStripped->getType()->isArrayType()) {
12199 auto IsDeprArrayComparionIgnored =
12200 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
12201 auto DiagID = S.getLangOpts().CPlusPlus26
12202 ? diag::warn_array_comparison_cxx26
12203 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12204 ? diag::warn_array_comparison
12205 : diag::warn_depr_array_comparison;
12206 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12207 << LHSStripped->getType() << RHSStripped->getType();
12208 // Carry on to produce the tautological comparison warning, if this
12209 // expression is potentially-evaluated, we can resolve the array to a
12210 // non-weak declaration, and so on.
12211 }
12212
12213 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12214 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12215 unsigned Result;
12216 switch (Opc) {
12217 case BO_EQ:
12218 case BO_LE:
12219 case BO_GE:
12220 Result = AlwaysTrue;
12221 break;
12222 case BO_NE:
12223 case BO_LT:
12224 case BO_GT:
12225 Result = AlwaysFalse;
12226 break;
12227 case BO_Cmp:
12228 Result = AlwaysEqual;
12229 break;
12230 default:
12231 Result = AlwaysConstant;
12232 break;
12233 }
12234 S.DiagRuntimeBehavior(Loc, nullptr,
12235 S.PDiag(diag::warn_comparison_always)
12236 << 0 /*self-comparison*/
12237 << Result);
12238 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12239 // What is it always going to evaluate to?
12240 unsigned Result;
12241 switch (Opc) {
12242 case BO_EQ: // e.g. array1 == array2
12243 Result = AlwaysFalse;
12244 break;
12245 case BO_NE: // e.g. array1 != array2
12246 Result = AlwaysTrue;
12247 break;
12248 default: // e.g. array1 <= array2
12249 // The best we can say is 'a constant'
12250 Result = AlwaysConstant;
12251 break;
12252 }
12253 S.DiagRuntimeBehavior(Loc, nullptr,
12254 S.PDiag(diag::warn_comparison_always)
12255 << 1 /*array comparison*/
12256 << Result);
12257 } else if (std::optional<bool> Res =
12258 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12259 S.DiagRuntimeBehavior(Loc, nullptr,
12260 S.PDiag(diag::warn_comparison_always)
12261 << 2 /*pointer comparison*/
12262 << (*Res ? AlwaysTrue : AlwaysFalse));
12263 }
12264 }
12265
12266 if (isa<CastExpr>(LHSStripped))
12267 LHSStripped = LHSStripped->IgnoreParenCasts();
12268 if (isa<CastExpr>(RHSStripped))
12269 RHSStripped = RHSStripped->IgnoreParenCasts();
12270
12271 // Warn about comparisons against a string constant (unless the other
12272 // operand is null); the user probably wants string comparison function.
12273 Expr *LiteralString = nullptr;
12274 Expr *LiteralStringStripped = nullptr;
12275 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12276 !RHSStripped->isNullPointerConstant(S.Context,
12278 LiteralString = LHS;
12279 LiteralStringStripped = LHSStripped;
12280 } else if ((isa<StringLiteral>(RHSStripped) ||
12281 isa<ObjCEncodeExpr>(RHSStripped)) &&
12282 !LHSStripped->isNullPointerConstant(S.Context,
12284 LiteralString = RHS;
12285 LiteralStringStripped = RHSStripped;
12286 }
12287
12288 if (LiteralString) {
12289 S.DiagRuntimeBehavior(Loc, nullptr,
12290 S.PDiag(diag::warn_stringcompare)
12291 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12292 << LiteralString->getSourceRange());
12293 }
12294}
12295
12297 switch (CK) {
12298 default: {
12299#ifndef NDEBUG
12300 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12301 << "\n";
12302#endif
12303 llvm_unreachable("unhandled cast kind");
12304 }
12305 case CK_UserDefinedConversion:
12306 return ICK_Identity;
12307 case CK_LValueToRValue:
12308 return ICK_Lvalue_To_Rvalue;
12309 case CK_ArrayToPointerDecay:
12310 return ICK_Array_To_Pointer;
12311 case CK_FunctionToPointerDecay:
12313 case CK_IntegralCast:
12315 case CK_FloatingCast:
12317 case CK_IntegralToFloating:
12318 case CK_FloatingToIntegral:
12319 return ICK_Floating_Integral;
12320 case CK_IntegralComplexCast:
12321 case CK_FloatingComplexCast:
12322 case CK_FloatingComplexToIntegralComplex:
12323 case CK_IntegralComplexToFloatingComplex:
12325 case CK_FloatingComplexToReal:
12326 case CK_FloatingRealToComplex:
12327 case CK_IntegralComplexToReal:
12328 case CK_IntegralRealToComplex:
12329 return ICK_Complex_Real;
12330 case CK_HLSLArrayRValue:
12331 return ICK_HLSL_Array_RValue;
12332 }
12333}
12334
12336 QualType FromType,
12337 SourceLocation Loc) {
12338 // Check for a narrowing implicit conversion.
12341 SCS.setToType(0, FromType);
12342 SCS.setToType(1, ToType);
12343 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12344 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12345
12346 APValue PreNarrowingValue;
12347 QualType PreNarrowingType;
12348 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12349 PreNarrowingType,
12350 /*IgnoreFloatToIntegralConversion*/ true)) {
12352 // Implicit conversion to a narrower type, but the expression is
12353 // value-dependent so we can't tell whether it's actually narrowing.
12354 case NK_Not_Narrowing:
12355 return false;
12356
12358 // Implicit conversion to a narrower type, and the value is not a constant
12359 // expression.
12360 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12361 << /*Constant*/ 1
12362 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12363 return true;
12364
12366 // Implicit conversion to a narrower type, and the value is not a constant
12367 // expression.
12368 case NK_Type_Narrowing:
12369 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12370 << /*Constant*/ 0 << FromType << ToType;
12371 // TODO: It's not a constant expression, but what if the user intended it
12372 // to be? Can we produce notes to help them figure out why it isn't?
12373 return true;
12374 }
12375 llvm_unreachable("unhandled case in switch");
12376}
12377
12379 ExprResult &LHS,
12380 ExprResult &RHS,
12381 SourceLocation Loc) {
12382 QualType LHSType = LHS.get()->getType();
12383 QualType RHSType = RHS.get()->getType();
12384 // Dig out the original argument type and expression before implicit casts
12385 // were applied. These are the types/expressions we need to check the
12386 // [expr.spaceship] requirements against.
12387 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12388 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12389 QualType LHSStrippedType = LHSStripped.get()->getType();
12390 QualType RHSStrippedType = RHSStripped.get()->getType();
12391
12392 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12393 // other is not, the program is ill-formed.
12394 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12395 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12396 return QualType();
12397 }
12398
12399 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12400 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12401 RHSStrippedType->isEnumeralType();
12402 if (NumEnumArgs == 1) {
12403 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12404 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12405 if (OtherTy->hasFloatingRepresentation()) {
12406 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12407 return QualType();
12408 }
12409 }
12410 if (NumEnumArgs == 2) {
12411 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12412 // type E, the operator yields the result of converting the operands
12413 // to the underlying type of E and applying <=> to the converted operands.
12414 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12415 S.InvalidOperands(Loc, LHS, RHS);
12416 return QualType();
12417 }
12418 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12419 assert(IntType->isArithmeticType());
12420
12421 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12422 // promote the boolean type, and all other promotable integer types, to
12423 // avoid this.
12424 if (S.Context.isPromotableIntegerType(IntType))
12425 IntType = S.Context.getPromotedIntegerType(IntType);
12426
12427 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12428 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12429 LHSType = RHSType = IntType;
12430 }
12431
12432 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12433 // usual arithmetic conversions are applied to the operands.
12434 QualType Type =
12436 if (LHS.isInvalid() || RHS.isInvalid())
12437 return QualType();
12438 if (Type.isNull()) {
12439 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12440 diagnoseScopedEnums(S, Loc, LHS, RHS, BO_Cmp);
12441 return ResultTy;
12442 }
12443
12444 std::optional<ComparisonCategoryType> CCT =
12446 if (!CCT)
12447 return S.InvalidOperands(Loc, LHS, RHS);
12448
12449 bool HasNarrowing = checkThreeWayNarrowingConversion(
12450 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12451 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12452 RHS.get()->getBeginLoc());
12453 if (HasNarrowing)
12454 return QualType();
12455
12456 assert(!Type.isNull() && "composite type for <=> has not been set");
12457
12460}
12461
12463 ExprResult &RHS,
12464 SourceLocation Loc,
12465 BinaryOperatorKind Opc) {
12466 if (Opc == BO_Cmp)
12467 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12468
12469 // C99 6.5.8p3 / C99 6.5.9p4
12470 QualType Type =
12472 if (LHS.isInvalid() || RHS.isInvalid())
12473 return QualType();
12474 if (Type.isNull()) {
12475 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12476 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12477 return ResultTy;
12478 }
12479 assert(Type->isArithmeticType() || Type->isEnumeralType());
12480
12482 return S.InvalidOperands(Loc, LHS, RHS);
12483
12484 // Check for comparisons of floating point operands using != and ==.
12486 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12487
12488 // The result of comparisons is 'bool' in C++, 'int' in C.
12490}
12491
12493 if (!NullE.get()->getType()->isAnyPointerType())
12494 return;
12495 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12496 if (!E.get()->getType()->isAnyPointerType() &&
12500 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12501 if (CL->getValue() == 0)
12502 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12503 << NullValue
12505 NullValue ? "NULL" : "(void *)0");
12506 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12507 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12508 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12509 if (T == Context.CharTy)
12510 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12511 << NullValue
12513 NullValue ? "NULL" : "(void *)0");
12514 }
12515 }
12516}
12517
12518// C99 6.5.8, C++ [expr.rel]
12520 SourceLocation Loc,
12521 BinaryOperatorKind Opc) {
12522 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12523 bool IsThreeWay = Opc == BO_Cmp;
12524 bool IsOrdered = IsRelational || IsThreeWay;
12525 auto IsAnyPointerType = [](ExprResult E) {
12526 QualType Ty = E.get()->getType();
12527 return Ty->isPointerType() || Ty->isMemberPointerType();
12528 };
12529
12530 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12531 // type, array-to-pointer, ..., conversions are performed on both operands to
12532 // bring them to their composite type.
12533 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12534 // any type-related checks.
12535 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12537 if (LHS.isInvalid())
12538 return QualType();
12540 if (RHS.isInvalid())
12541 return QualType();
12542 } else {
12543 LHS = DefaultLvalueConversion(LHS.get());
12544 if (LHS.isInvalid())
12545 return QualType();
12546 RHS = DefaultLvalueConversion(RHS.get());
12547 if (RHS.isInvalid())
12548 return QualType();
12549 }
12550
12551 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12555 }
12556
12557 // Handle vector comparisons separately.
12558 if (LHS.get()->getType()->isVectorType() ||
12559 RHS.get()->getType()->isVectorType())
12560 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12561
12562 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12563 RHS.get()->getType()->isSveVLSBuiltinType())
12564 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12565
12566 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12567 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12568
12569 QualType LHSType = LHS.get()->getType();
12570 QualType RHSType = RHS.get()->getType();
12571 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12572 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12573 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12574
12575 if ((LHSType->isPointerType() &&
12577 (RHSType->isPointerType() &&
12579 return InvalidOperands(Loc, LHS, RHS);
12580
12581 const Expr::NullPointerConstantKind LHSNullKind =
12583 const Expr::NullPointerConstantKind RHSNullKind =
12585 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12586 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12587
12588 auto computeResultTy = [&]() {
12589 if (Opc != BO_Cmp)
12590 return QualType(Context.getLogicalOperationType());
12591 assert(getLangOpts().CPlusPlus);
12592 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12593
12594 QualType CompositeTy = LHS.get()->getType();
12595 assert(!CompositeTy->isReferenceType());
12596
12597 std::optional<ComparisonCategoryType> CCT =
12599 if (!CCT)
12600 return InvalidOperands(Loc, LHS, RHS);
12601
12602 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12603 // P0946R0: Comparisons between a null pointer constant and an object
12604 // pointer result in std::strong_equality, which is ill-formed under
12605 // P1959R0.
12606 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12607 << (LHSIsNull ? LHS.get()->getSourceRange()
12608 : RHS.get()->getSourceRange());
12609 return QualType();
12610 }
12611
12614 };
12615
12616 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12617 bool IsEquality = Opc == BO_EQ;
12618 if (RHSIsNull)
12619 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12620 RHS.get()->getSourceRange());
12621 else
12622 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12623 LHS.get()->getSourceRange());
12624 }
12625
12626 if (IsOrdered && LHSType->isFunctionPointerType() &&
12627 RHSType->isFunctionPointerType()) {
12628 // Valid unless a relational comparison of function pointers
12629 bool IsError = Opc == BO_Cmp;
12630 auto DiagID =
12631 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12632 : getLangOpts().CPlusPlus
12633 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12634 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12635 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12636 << RHS.get()->getSourceRange();
12637 if (IsError)
12638 return QualType();
12639 }
12640
12641 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12642 (RHSType->isIntegerType() && !RHSIsNull)) {
12643 // Skip normal pointer conversion checks in this case; we have better
12644 // diagnostics for this below.
12645 } else if (getLangOpts().CPlusPlus) {
12646 // Equality comparison of a function pointer to a void pointer is invalid,
12647 // but we allow it as an extension.
12648 // FIXME: If we really want to allow this, should it be part of composite
12649 // pointer type computation so it works in conditionals too?
12650 if (!IsOrdered &&
12651 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12652 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12653 // This is a gcc extension compatibility comparison.
12654 // In a SFINAE context, we treat this as a hard error to maintain
12655 // conformance with the C++ standard.
12657 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12658
12659 if (isSFINAEContext())
12660 return QualType();
12661
12662 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12663 return computeResultTy();
12664 }
12665
12666 // C++ [expr.eq]p2:
12667 // If at least one operand is a pointer [...] bring them to their
12668 // composite pointer type.
12669 // C++ [expr.spaceship]p6
12670 // If at least one of the operands is of pointer type, [...] bring them
12671 // to their composite pointer type.
12672 // C++ [expr.rel]p2:
12673 // If both operands are pointers, [...] bring them to their composite
12674 // pointer type.
12675 // For <=>, the only valid non-pointer types are arrays and functions, and
12676 // we already decayed those, so this is really the same as the relational
12677 // comparison rule.
12678 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12679 (IsOrdered ? 2 : 1) &&
12680 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12681 RHSType->isObjCObjectPointerType()))) {
12682 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12683 return QualType();
12684 return computeResultTy();
12685 }
12686 } else if (LHSType->isPointerType() &&
12687 RHSType->isPointerType()) { // C99 6.5.8p2
12688 // All of the following pointer-related warnings are GCC extensions, except
12689 // when handling null pointer constants.
12690 QualType LCanPointeeTy =
12692 QualType RCanPointeeTy =
12694
12695 // C99 6.5.9p2 and C99 6.5.8p2
12696 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12697 RCanPointeeTy.getUnqualifiedType())) {
12698 if (IsRelational) {
12699 // Pointers both need to point to complete or incomplete types
12700 if ((LCanPointeeTy->isIncompleteType() !=
12701 RCanPointeeTy->isIncompleteType()) &&
12702 !getLangOpts().C11) {
12703 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12704 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12705 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12706 << RCanPointeeTy->isIncompleteType();
12707 }
12708 }
12709 } else if (!IsRelational &&
12710 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12711 // Valid unless comparison between non-null pointer and function pointer
12712 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12713 && !LHSIsNull && !RHSIsNull)
12714 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12715 /*isError*/false);
12716 } else {
12717 // Invalid
12718 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12719 }
12720 if (LCanPointeeTy != RCanPointeeTy) {
12721 // Treat NULL constant as a special case in OpenCL.
12722 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12723 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
12724 getASTContext())) {
12725 Diag(Loc,
12726 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12727 << LHSType << RHSType << 0 /* comparison */
12728 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12729 }
12730 }
12731 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12732 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12733 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12734 : CK_BitCast;
12735
12736 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
12737 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
12738 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
12739 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
12740 bool ChangingCFIUncheckedCallee =
12741 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
12742
12743 if (LHSIsNull && !RHSIsNull)
12744 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12745 else if (!ChangingCFIUncheckedCallee)
12746 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12747 }
12748 return computeResultTy();
12749 }
12750
12751
12752 // C++ [expr.eq]p4:
12753 // Two operands of type std::nullptr_t or one operand of type
12754 // std::nullptr_t and the other a null pointer constant compare
12755 // equal.
12756 // C23 6.5.9p5:
12757 // If both operands have type nullptr_t or one operand has type nullptr_t
12758 // and the other is a null pointer constant, they compare equal if the
12759 // former is a null pointer.
12760 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12761 if (LHSType->isNullPtrType()) {
12762 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12763 return computeResultTy();
12764 }
12765 if (RHSType->isNullPtrType()) {
12766 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12767 return computeResultTy();
12768 }
12769 }
12770
12771 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12772 // C23 6.5.9p6:
12773 // Otherwise, at least one operand is a pointer. If one is a pointer and
12774 // the other is a null pointer constant or has type nullptr_t, they
12775 // compare equal
12776 if (LHSIsNull && RHSType->isPointerType()) {
12777 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12778 return computeResultTy();
12779 }
12780 if (RHSIsNull && LHSType->isPointerType()) {
12781 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12782 return computeResultTy();
12783 }
12784 }
12785
12786 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12787 // These aren't covered by the composite pointer type rules.
12788 if (!IsOrdered && RHSType->isNullPtrType() &&
12789 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12790 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12791 return computeResultTy();
12792 }
12793 if (!IsOrdered && LHSType->isNullPtrType() &&
12794 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12795 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12796 return computeResultTy();
12797 }
12798
12799 if (getLangOpts().CPlusPlus) {
12800 if (IsRelational &&
12801 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12802 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12803 // HACK: Relational comparison of nullptr_t against a pointer type is
12804 // invalid per DR583, but we allow it within std::less<> and friends,
12805 // since otherwise common uses of it break.
12806 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12807 // friends to have std::nullptr_t overload candidates.
12808 DeclContext *DC = CurContext;
12809 if (isa<FunctionDecl>(DC))
12810 DC = DC->getParent();
12811 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12812 if (CTSD->isInStdNamespace() &&
12813 llvm::StringSwitch<bool>(CTSD->getName())
12814 .Cases({"less", "less_equal", "greater", "greater_equal"}, true)
12815 .Default(false)) {
12816 if (RHSType->isNullPtrType())
12817 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12818 else
12819 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12820 return computeResultTy();
12821 }
12822 }
12823 }
12824
12825 // C++ [expr.eq]p2:
12826 // If at least one operand is a pointer to member, [...] bring them to
12827 // their composite pointer type.
12828 if (!IsOrdered &&
12829 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12830 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12831 return QualType();
12832 else
12833 return computeResultTy();
12834 }
12835 }
12836
12837 // Handle block pointer types.
12838 if (!IsOrdered && LHSType->isBlockPointerType() &&
12839 RHSType->isBlockPointerType()) {
12840 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12841 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12842
12843 if (!LHSIsNull && !RHSIsNull &&
12844 !Context.typesAreCompatible(lpointee, rpointee)) {
12845 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12846 << LHSType << RHSType << LHS.get()->getSourceRange()
12847 << RHS.get()->getSourceRange();
12848 }
12849 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12850 return computeResultTy();
12851 }
12852
12853 // Allow block pointers to be compared with null pointer constants.
12854 if (!IsOrdered
12855 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12856 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12857 if (!LHSIsNull && !RHSIsNull) {
12858 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12860 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12861 ->getPointeeType()->isVoidType())))
12862 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12863 << LHSType << RHSType << LHS.get()->getSourceRange()
12864 << RHS.get()->getSourceRange();
12865 }
12866 if (LHSIsNull && !RHSIsNull)
12867 LHS = ImpCastExprToType(LHS.get(), RHSType,
12868 RHSType->isPointerType() ? CK_BitCast
12869 : CK_AnyPointerToBlockPointerCast);
12870 else
12871 RHS = ImpCastExprToType(RHS.get(), LHSType,
12872 LHSType->isPointerType() ? CK_BitCast
12873 : CK_AnyPointerToBlockPointerCast);
12874 return computeResultTy();
12875 }
12876
12877 if (LHSType->isObjCObjectPointerType() ||
12878 RHSType->isObjCObjectPointerType()) {
12879 const PointerType *LPT = LHSType->getAs<PointerType>();
12880 const PointerType *RPT = RHSType->getAs<PointerType>();
12881 if (LPT || RPT) {
12882 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12883 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12884
12885 if (!LPtrToVoid && !RPtrToVoid &&
12886 !Context.typesAreCompatible(LHSType, RHSType)) {
12887 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12888 /*isError*/false);
12889 }
12890 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12891 // the RHS, but we have test coverage for this behavior.
12892 // FIXME: Consider using convertPointersToCompositeType in C++.
12893 if (LHSIsNull && !RHSIsNull) {
12894 Expr *E = LHS.get();
12895 if (getLangOpts().ObjCAutoRefCount)
12896 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
12898 LHS = ImpCastExprToType(E, RHSType,
12899 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12900 }
12901 else {
12902 Expr *E = RHS.get();
12903 if (getLangOpts().ObjCAutoRefCount)
12904 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
12906 /*Diagnose=*/true,
12907 /*DiagnoseCFAudited=*/false, Opc);
12908 RHS = ImpCastExprToType(E, LHSType,
12909 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12910 }
12911 return computeResultTy();
12912 }
12913 if (LHSType->isObjCObjectPointerType() &&
12914 RHSType->isObjCObjectPointerType()) {
12915 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12916 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12917 /*isError*/false);
12919 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12920
12921 if (LHSIsNull && !RHSIsNull)
12922 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12923 else
12924 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12925 return computeResultTy();
12926 }
12927
12928 if (!IsOrdered && LHSType->isBlockPointerType() &&
12930 LHS = ImpCastExprToType(LHS.get(), RHSType,
12931 CK_BlockPointerToObjCPointerCast);
12932 return computeResultTy();
12933 } else if (!IsOrdered &&
12935 RHSType->isBlockPointerType()) {
12936 RHS = ImpCastExprToType(RHS.get(), LHSType,
12937 CK_BlockPointerToObjCPointerCast);
12938 return computeResultTy();
12939 }
12940 }
12941 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12942 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12943 unsigned DiagID = 0;
12944 bool isError = false;
12945 if (LangOpts.DebuggerSupport) {
12946 // Under a debugger, allow the comparison of pointers to integers,
12947 // since users tend to want to compare addresses.
12948 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12949 (RHSIsNull && RHSType->isIntegerType())) {
12950 if (IsOrdered) {
12951 isError = getLangOpts().CPlusPlus;
12952 DiagID =
12953 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12954 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12955 }
12956 } else if (getLangOpts().CPlusPlus) {
12957 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12958 isError = true;
12959 } else if (IsOrdered)
12960 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12961 else
12962 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12963
12964 if (DiagID) {
12965 Diag(Loc, DiagID)
12966 << LHSType << RHSType << LHS.get()->getSourceRange()
12967 << RHS.get()->getSourceRange();
12968 if (isError)
12969 return QualType();
12970 }
12971
12972 if (LHSType->isIntegerType())
12973 LHS = ImpCastExprToType(LHS.get(), RHSType,
12974 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12975 else
12976 RHS = ImpCastExprToType(RHS.get(), LHSType,
12977 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12978 return computeResultTy();
12979 }
12980
12981 // Handle block pointers.
12982 if (!IsOrdered && RHSIsNull
12983 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12984 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12985 return computeResultTy();
12986 }
12987 if (!IsOrdered && LHSIsNull
12988 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12989 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12990 return computeResultTy();
12991 }
12992
12993 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12994 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12995 return computeResultTy();
12996 }
12997
12998 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12999 return computeResultTy();
13000 }
13001
13002 if (LHSIsNull && RHSType->isQueueT()) {
13003 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13004 return computeResultTy();
13005 }
13006
13007 if (LHSType->isQueueT() && RHSIsNull) {
13008 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13009 return computeResultTy();
13010 }
13011 }
13012
13013 return InvalidOperands(Loc, LHS, RHS);
13014}
13015
13017 const VectorType *VTy = V->castAs<VectorType>();
13018 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13019
13020 if (isa<ExtVectorType>(VTy)) {
13021 if (VTy->isExtVectorBoolType())
13022 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13023 if (TypeSize == Context.getTypeSize(Context.CharTy))
13024 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13025 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13026 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13027 if (TypeSize == Context.getTypeSize(Context.IntTy))
13028 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13029 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13030 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13031 if (TypeSize == Context.getTypeSize(Context.LongTy))
13032 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13033 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13034 "Unhandled vector element size in vector compare");
13035 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13036 }
13037
13038 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13039 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13041 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13042 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13044 if (TypeSize == Context.getTypeSize(Context.LongTy))
13045 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13047 if (TypeSize == Context.getTypeSize(Context.IntTy))
13048 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13050 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13051 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13053 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13054 "Unhandled vector element size in vector compare");
13055 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13057}
13058
13060 const BuiltinType *VTy = V->castAs<BuiltinType>();
13061 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13062
13063 const QualType ETy = V->getSveEltType(Context);
13064 const auto TypeSize = Context.getTypeSize(ETy);
13065
13066 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13067 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13068 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13069}
13070
13072 SourceLocation Loc,
13073 BinaryOperatorKind Opc) {
13074 if (Opc == BO_Cmp) {
13075 Diag(Loc, diag::err_three_way_vector_comparison);
13076 return QualType();
13077 }
13078
13079 // Check to make sure we're operating on vectors of the same type and width,
13080 // Allowing one side to be a scalar of element type.
13081 QualType vType =
13082 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13083 /*AllowBothBool*/ true,
13084 /*AllowBoolConversions*/ getLangOpts().ZVector,
13085 /*AllowBooleanOperation*/ true,
13086 /*ReportInvalid*/ true);
13087 if (vType.isNull())
13088 return vType;
13089
13090 QualType LHSType = LHS.get()->getType();
13091
13092 // Determine the return type of a vector compare. By default clang will return
13093 // a scalar for all vector compares except vector bool and vector pixel.
13094 // With the gcc compiler we will always return a vector type and with the xl
13095 // compiler we will always return a scalar type. This switch allows choosing
13096 // which behavior is prefered.
13097 if (getLangOpts().AltiVec) {
13098 switch (getLangOpts().getAltivecSrcCompat()) {
13100 // If AltiVec, the comparison results in a numeric type, i.e.
13101 // bool for C++, int for C
13102 if (vType->castAs<VectorType>()->getVectorKind() ==
13104 return Context.getLogicalOperationType();
13105 else
13106 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13107 break;
13109 // For GCC we always return the vector type.
13110 break;
13112 return Context.getLogicalOperationType();
13113 break;
13114 }
13115 }
13116
13117 // For non-floating point types, check for self-comparisons of the form
13118 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13119 // often indicate logic errors in the program.
13120 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13121
13122 // Check for comparisons of floating point operands using != and ==.
13123 if (LHSType->hasFloatingRepresentation()) {
13124 assert(RHS.get()->getType()->hasFloatingRepresentation());
13125 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13126 }
13127
13128 // Return a signed type for the vector.
13129 return GetSignedVectorType(vType);
13130}
13131
13133 ExprResult &RHS,
13134 SourceLocation Loc,
13135 BinaryOperatorKind Opc) {
13136 if (Opc == BO_Cmp) {
13137 Diag(Loc, diag::err_three_way_vector_comparison);
13138 return QualType();
13139 }
13140
13141 // Check to make sure we're operating on vectors of the same type and width,
13142 // Allowing one side to be a scalar of element type.
13144 LHS, RHS, Loc, /*isCompAssign*/ false, ArithConvKind::Comparison);
13145
13146 if (vType.isNull())
13147 return vType;
13148
13149 QualType LHSType = LHS.get()->getType();
13150
13151 // For non-floating point types, check for self-comparisons of the form
13152 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13153 // often indicate logic errors in the program.
13154 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13155
13156 // Check for comparisons of floating point operands using != and ==.
13157 if (LHSType->hasFloatingRepresentation()) {
13158 assert(RHS.get()->getType()->hasFloatingRepresentation());
13159 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13160 }
13161
13162 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13163 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13164
13165 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13166 RHSBuiltinTy->isSVEBool())
13167 return LHSType;
13168
13169 // Return a signed type for the vector.
13170 return GetSignedSizelessVectorType(vType);
13171}
13172
13173static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13174 const ExprResult &XorRHS,
13175 const SourceLocation Loc) {
13176 // Do not diagnose macros.
13177 if (Loc.isMacroID())
13178 return;
13179
13180 // Do not diagnose if both LHS and RHS are macros.
13181 if (XorLHS.get()->getExprLoc().isMacroID() &&
13182 XorRHS.get()->getExprLoc().isMacroID())
13183 return;
13184
13185 bool Negative = false;
13186 bool ExplicitPlus = false;
13187 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13188 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13189
13190 if (!LHSInt)
13191 return;
13192 if (!RHSInt) {
13193 // Check negative literals.
13194 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13195 UnaryOperatorKind Opc = UO->getOpcode();
13196 if (Opc != UO_Minus && Opc != UO_Plus)
13197 return;
13198 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13199 if (!RHSInt)
13200 return;
13201 Negative = (Opc == UO_Minus);
13202 ExplicitPlus = !Negative;
13203 } else {
13204 return;
13205 }
13206 }
13207
13208 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13209 llvm::APInt RightSideValue = RHSInt->getValue();
13210 if (LeftSideValue != 2 && LeftSideValue != 10)
13211 return;
13212
13213 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13214 return;
13215
13217 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13218 llvm::StringRef ExprStr =
13220
13221 CharSourceRange XorRange =
13223 llvm::StringRef XorStr =
13225 // Do not diagnose if xor keyword/macro is used.
13226 if (XorStr == "xor")
13227 return;
13228
13229 std::string LHSStr = std::string(Lexer::getSourceText(
13230 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13231 S.getSourceManager(), S.getLangOpts()));
13232 std::string RHSStr = std::string(Lexer::getSourceText(
13233 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13234 S.getSourceManager(), S.getLangOpts()));
13235
13236 if (Negative) {
13237 RightSideValue = -RightSideValue;
13238 RHSStr = "-" + RHSStr;
13239 } else if (ExplicitPlus) {
13240 RHSStr = "+" + RHSStr;
13241 }
13242
13243 StringRef LHSStrRef = LHSStr;
13244 StringRef RHSStrRef = RHSStr;
13245 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13246 // literals.
13247 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13248 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13249 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13250 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13251 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13252 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13253 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13254 return;
13255
13256 bool SuggestXor =
13257 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13258 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13259 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13260 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13261 std::string SuggestedExpr = "1 << " + RHSStr;
13262 bool Overflow = false;
13263 llvm::APInt One = (LeftSideValue - 1);
13264 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13265 if (Overflow) {
13266 if (RightSideIntValue < 64)
13267 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13268 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13269 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13270 else if (RightSideIntValue == 64)
13271 S.Diag(Loc, diag::warn_xor_used_as_pow)
13272 << ExprStr << toString(XorValue, 10, true);
13273 else
13274 return;
13275 } else {
13276 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13277 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13278 << toString(PowValue, 10, true)
13280 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13281 }
13282
13283 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13284 << ("0x2 ^ " + RHSStr) << SuggestXor;
13285 } else if (LeftSideValue == 10) {
13286 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13287 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13288 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13289 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13290 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13291 << ("0xA ^ " + RHSStr) << SuggestXor;
13292 }
13293}
13294
13296 SourceLocation Loc,
13297 BinaryOperatorKind Opc) {
13298 // Ensure that either both operands are of the same vector type, or
13299 // one operand is of a vector type and the other is of its element type.
13300 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13301 /*AllowBothBool*/ true,
13302 /*AllowBoolConversions*/ false,
13303 /*AllowBooleanOperation*/ false,
13304 /*ReportInvalid*/ false);
13305 if (vType.isNull())
13306 return InvalidOperands(Loc, LHS, RHS);
13307 if (getLangOpts().OpenCL &&
13308 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13310 return InvalidOperands(Loc, LHS, RHS);
13311 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13312 // usage of the logical operators && and || with vectors in C. This
13313 // check could be notionally dropped.
13314 if (!getLangOpts().CPlusPlus &&
13315 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13316 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13317 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13318 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13319 // `select` functions.
13320 if (getLangOpts().HLSL &&
13321 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13322 (void)InvalidOperands(Loc, LHS, RHS);
13323 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13324 return QualType();
13325 }
13326
13327 return GetSignedVectorType(LHS.get()->getType());
13328}
13329
13331 SourceLocation Loc,
13332 bool IsCompAssign) {
13333 if (!IsCompAssign) {
13335 if (LHS.isInvalid())
13336 return QualType();
13337 }
13339 if (RHS.isInvalid())
13340 return QualType();
13341
13342 // For conversion purposes, we ignore any qualifiers.
13343 // For example, "const float" and "float" are equivalent.
13344 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13345 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13346
13347 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13348 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13349 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13350
13351 if (Context.hasSameType(LHSType, RHSType))
13352 return Context.getCommonSugaredType(LHSType, RHSType);
13353
13354 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13355 // case we have to return InvalidOperands.
13356 ExprResult OriginalLHS = LHS;
13357 ExprResult OriginalRHS = RHS;
13358 if (LHSMatType && !RHSMatType) {
13359 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13360 if (!RHS.isInvalid())
13361 return LHSType;
13362
13363 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13364 }
13365
13366 if (!LHSMatType && RHSMatType) {
13367 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13368 if (!LHS.isInvalid())
13369 return RHSType;
13370 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13371 }
13372
13373 return InvalidOperands(Loc, LHS, RHS);
13374}
13375
13377 SourceLocation Loc,
13378 bool IsCompAssign) {
13379 if (!IsCompAssign) {
13381 if (LHS.isInvalid())
13382 return QualType();
13383 }
13385 if (RHS.isInvalid())
13386 return QualType();
13387
13388 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13389 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13390 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13391
13392 if (LHSMatType && RHSMatType) {
13393 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13394 return InvalidOperands(Loc, LHS, RHS);
13395
13396 if (Context.hasSameType(LHSMatType, RHSMatType))
13397 return Context.getCommonSugaredType(
13398 LHS.get()->getType().getUnqualifiedType(),
13399 RHS.get()->getType().getUnqualifiedType());
13400
13401 QualType LHSELTy = LHSMatType->getElementType(),
13402 RHSELTy = RHSMatType->getElementType();
13403 if (!Context.hasSameType(LHSELTy, RHSELTy))
13404 return InvalidOperands(Loc, LHS, RHS);
13405
13406 return Context.getConstantMatrixType(
13407 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13408 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13409 }
13410 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13411}
13412
13414 switch (Opc) {
13415 default:
13416 return false;
13417 case BO_And:
13418 case BO_AndAssign:
13419 case BO_Or:
13420 case BO_OrAssign:
13421 case BO_Xor:
13422 case BO_XorAssign:
13423 return true;
13424 }
13425}
13426
13428 SourceLocation Loc,
13429 BinaryOperatorKind Opc) {
13430 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13431
13432 bool IsCompAssign =
13433 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13434
13435 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13436
13437 if (LHS.get()->getType()->isVectorType() ||
13438 RHS.get()->getType()->isVectorType()) {
13439 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13441 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13442 /*AllowBothBool*/ true,
13443 /*AllowBoolConversions*/ getLangOpts().ZVector,
13444 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13445 /*ReportInvalid*/ true);
13446 return InvalidOperands(Loc, LHS, RHS);
13447 }
13448
13449 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13450 RHS.get()->getType()->isSveVLSBuiltinType()) {
13451 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13453 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13455 return InvalidOperands(Loc, LHS, RHS);
13456 }
13457
13458 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13459 RHS.get()->getType()->isSveVLSBuiltinType()) {
13460 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13462 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13464 return InvalidOperands(Loc, LHS, RHS);
13465 }
13466
13467 if (Opc == BO_And)
13468 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13469
13470 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13472 return InvalidOperands(Loc, LHS, RHS);
13473
13474 ExprResult LHSResult = LHS, RHSResult = RHS;
13476 LHSResult, RHSResult, Loc,
13478 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13479 return QualType();
13480 LHS = LHSResult.get();
13481 RHS = RHSResult.get();
13482
13483 if (Opc == BO_Xor)
13484 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13485
13486 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13487 return compType;
13488 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13489 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13490 return ResultTy;
13491}
13492
13493// C99 6.5.[13,14]
13495 SourceLocation Loc,
13496 BinaryOperatorKind Opc) {
13497 // Check vector operands differently.
13498 if (LHS.get()->getType()->isVectorType() ||
13499 RHS.get()->getType()->isVectorType())
13500 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13501
13502 bool EnumConstantInBoolContext = false;
13503 for (const ExprResult &HS : {LHS, RHS}) {
13504 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13505 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13506 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13507 EnumConstantInBoolContext = true;
13508 }
13509 }
13510
13511 if (EnumConstantInBoolContext)
13512 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13513
13514 // WebAssembly tables can't be used with logical operators.
13515 QualType LHSTy = LHS.get()->getType();
13516 QualType RHSTy = RHS.get()->getType();
13517 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13518 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13519 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13520 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13521 return InvalidOperands(Loc, LHS, RHS);
13522 }
13523
13524 // Diagnose cases where the user write a logical and/or but probably meant a
13525 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13526 // is a constant.
13527 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13528 !LHS.get()->getType()->isBooleanType() &&
13529 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13530 // Don't warn in macros or template instantiations.
13531 !Loc.isMacroID() && !inTemplateInstantiation()) {
13532 // If the RHS can be constant folded, and if it constant folds to something
13533 // that isn't 0 or 1 (which indicate a potential logical operation that
13534 // happened to fold to true/false) then warn.
13535 // Parens on the RHS are ignored.
13536 Expr::EvalResult EVResult;
13537 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13538 llvm::APSInt Result = EVResult.Val.getInt();
13539 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13540 !RHS.get()->getExprLoc().isMacroID()) ||
13541 (Result != 0 && Result != 1)) {
13542 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13543 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13544 // Suggest replacing the logical operator with the bitwise version
13545 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13546 << (Opc == BO_LAnd ? "&" : "|")
13549 Opc == BO_LAnd ? "&" : "|");
13550 if (Opc == BO_LAnd)
13551 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13552 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13555 RHS.get()->getEndLoc()));
13556 }
13557 }
13558 }
13559
13560 if (!Context.getLangOpts().CPlusPlus) {
13561 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13562 // not operate on the built-in scalar and vector float types.
13563 if (Context.getLangOpts().OpenCL &&
13564 Context.getLangOpts().OpenCLVersion < 120) {
13565 if (LHS.get()->getType()->isFloatingType() ||
13566 RHS.get()->getType()->isFloatingType())
13567 return InvalidOperands(Loc, LHS, RHS);
13568 }
13569
13570 LHS = UsualUnaryConversions(LHS.get());
13571 if (LHS.isInvalid())
13572 return QualType();
13573
13574 RHS = UsualUnaryConversions(RHS.get());
13575 if (RHS.isInvalid())
13576 return QualType();
13577
13578 if (!LHS.get()->getType()->isScalarType() ||
13579 !RHS.get()->getType()->isScalarType())
13580 return InvalidOperands(Loc, LHS, RHS);
13581
13582 return Context.IntTy;
13583 }
13584
13585 // The following is safe because we only use this method for
13586 // non-overloadable operands.
13587
13588 // C++ [expr.log.and]p1
13589 // C++ [expr.log.or]p1
13590 // The operands are both contextually converted to type bool.
13592 if (LHSRes.isInvalid()) {
13593 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13594 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13595 return ResultTy;
13596 }
13597 LHS = LHSRes;
13598
13600 if (RHSRes.isInvalid()) {
13601 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13602 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13603 return ResultTy;
13604 }
13605 RHS = RHSRes;
13606
13607 // C++ [expr.log.and]p2
13608 // C++ [expr.log.or]p2
13609 // The result is a bool.
13610 return Context.BoolTy;
13611}
13612
13613static bool IsReadonlyMessage(Expr *E, Sema &S) {
13614 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13615 if (!ME) return false;
13616 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13617 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13619 if (!Base) return false;
13620 return Base->getMethodDecl() != nullptr;
13621}
13622
13623/// Is the given expression (which must be 'const') a reference to a
13624/// variable which was originally non-const, but which has become
13625/// 'const' due to being captured within a block?
13628 assert(E->isLValue() && E->getType().isConstQualified());
13629 E = E->IgnoreParens();
13630
13631 // Must be a reference to a declaration from an enclosing scope.
13632 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13633 if (!DRE) return NCCK_None;
13635
13636 ValueDecl *Value = dyn_cast<ValueDecl>(DRE->getDecl());
13637
13638 // The declaration must be a value which is not declared 'const'.
13639 if (!Value || Value->getType().isConstQualified())
13640 return NCCK_None;
13641
13642 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
13643 if (Binding) {
13644 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
13645 assert(!isa<BlockDecl>(Binding->getDeclContext()));
13646 return NCCK_Lambda;
13647 }
13648
13649 VarDecl *Var = dyn_cast<VarDecl>(Value);
13650 if (!Var)
13651 return NCCK_None;
13652 if (Var->getType()->isReferenceType())
13653 return NCCK_None;
13654
13655 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
13656
13657 // Decide whether the first capture was for a block or a lambda.
13658 DeclContext *DC = S.CurContext, *Prev = nullptr;
13659 // Decide whether the first capture was for a block or a lambda.
13660 while (DC) {
13661 // For init-capture, it is possible that the variable belongs to the
13662 // template pattern of the current context.
13663 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13664 if (Var->isInitCapture() &&
13665 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
13666 break;
13667 if (DC == Var->getDeclContext())
13668 break;
13669 Prev = DC;
13670 DC = DC->getParent();
13671 }
13672 // Unless we have an init-capture, we've gone one step too far.
13673 if (!Var->isInitCapture())
13674 DC = Prev;
13675 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13676}
13677
13678static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13679 Ty = Ty.getNonReferenceType();
13680 if (IsDereference && Ty->isPointerType())
13681 Ty = Ty->getPointeeType();
13682 return !Ty.isConstQualified();
13683}
13684
13685// Update err_typecheck_assign_const and note_typecheck_assign_const
13686// when this enum is changed.
13687enum {
13693 ConstUnknown, // Keep as last element
13694};
13695
13696/// Emit the "read-only variable not assignable" error and print notes to give
13697/// more information about why the variable is not assignable, such as pointing
13698/// to the declaration of a const variable, showing that a method is const, or
13699/// that the function is returning a const reference.
13700static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13701 SourceLocation Loc) {
13702 SourceRange ExprRange = E->getSourceRange();
13703
13704 // Only emit one error on the first const found. All other consts will emit
13705 // a note to the error.
13706 bool DiagnosticEmitted = false;
13707
13708 // Track if the current expression is the result of a dereference, and if the
13709 // next checked expression is the result of a dereference.
13710 bool IsDereference = false;
13711 bool NextIsDereference = false;
13712
13713 // Loop to process MemberExpr chains.
13714 while (true) {
13715 IsDereference = NextIsDereference;
13716
13718 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13719 NextIsDereference = ME->isArrow();
13720 const ValueDecl *VD = ME->getMemberDecl();
13721 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13722 // Mutable fields can be modified even if the class is const.
13723 if (Field->isMutable()) {
13724 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13725 break;
13726 }
13727
13728 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13729 if (!DiagnosticEmitted) {
13730 S.Diag(Loc, diag::err_typecheck_assign_const)
13731 << ExprRange << ConstMember << false /*static*/ << Field
13732 << Field->getType();
13733 DiagnosticEmitted = true;
13734 }
13735 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13736 << ConstMember << false /*static*/ << Field << Field->getType()
13737 << Field->getSourceRange();
13738 }
13739 E = ME->getBase();
13740 continue;
13741 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13742 if (VDecl->getType().isConstQualified()) {
13743 if (!DiagnosticEmitted) {
13744 S.Diag(Loc, diag::err_typecheck_assign_const)
13745 << ExprRange << ConstMember << true /*static*/ << VDecl
13746 << VDecl->getType();
13747 DiagnosticEmitted = true;
13748 }
13749 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13750 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13751 << VDecl->getSourceRange();
13752 }
13753 // Static fields do not inherit constness from parents.
13754 break;
13755 }
13756 break; // End MemberExpr
13757 } else if (const ArraySubscriptExpr *ASE =
13758 dyn_cast<ArraySubscriptExpr>(E)) {
13759 E = ASE->getBase()->IgnoreParenImpCasts();
13760 continue;
13761 } else if (const ExtVectorElementExpr *EVE =
13762 dyn_cast<ExtVectorElementExpr>(E)) {
13763 E = EVE->getBase()->IgnoreParenImpCasts();
13764 continue;
13765 }
13766 break;
13767 }
13768
13769 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13770 // Function calls
13771 const FunctionDecl *FD = CE->getDirectCallee();
13772 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13773 if (!DiagnosticEmitted) {
13774 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13775 << ConstFunction << FD;
13776 DiagnosticEmitted = true;
13777 }
13779 diag::note_typecheck_assign_const)
13780 << ConstFunction << FD << FD->getReturnType()
13781 << FD->getReturnTypeSourceRange();
13782 }
13783 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13784 // Point to variable declaration.
13785 if (const ValueDecl *VD = DRE->getDecl()) {
13786 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13787 if (!DiagnosticEmitted) {
13788 S.Diag(Loc, diag::err_typecheck_assign_const)
13789 << ExprRange << ConstVariable << VD << VD->getType();
13790 DiagnosticEmitted = true;
13791 }
13792 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13793 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13794 }
13795 }
13796 } else if (isa<CXXThisExpr>(E)) {
13797 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13798 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13799 if (MD->isConst()) {
13800 if (!DiagnosticEmitted) {
13801 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13802 << ConstMethod << MD;
13803 DiagnosticEmitted = true;
13804 }
13805 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13806 << ConstMethod << MD << MD->getSourceRange();
13807 }
13808 }
13809 }
13810 }
13811
13812 if (DiagnosticEmitted)
13813 return;
13814
13815 // Can't determine a more specific message, so display the generic error.
13816 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13817}
13818
13824
13826 const RecordType *Ty,
13827 SourceLocation Loc, SourceRange Range,
13828 OriginalExprKind OEK,
13829 bool &DiagnosticEmitted) {
13830 std::vector<const RecordType *> RecordTypeList;
13831 RecordTypeList.push_back(Ty);
13832 unsigned NextToCheckIndex = 0;
13833 // We walk the record hierarchy breadth-first to ensure that we print
13834 // diagnostics in field nesting order.
13835 while (RecordTypeList.size() > NextToCheckIndex) {
13836 bool IsNested = NextToCheckIndex > 0;
13837 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
13838 ->getDecl()
13840 ->fields()) {
13841 // First, check every field for constness.
13842 QualType FieldTy = Field->getType();
13843 if (FieldTy.isConstQualified()) {
13844 if (!DiagnosticEmitted) {
13845 S.Diag(Loc, diag::err_typecheck_assign_const)
13846 << Range << NestedConstMember << OEK << VD
13847 << IsNested << Field;
13848 DiagnosticEmitted = true;
13849 }
13850 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13851 << NestedConstMember << IsNested << Field
13852 << FieldTy << Field->getSourceRange();
13853 }
13854
13855 // Then we append it to the list to check next in order.
13856 FieldTy = FieldTy.getCanonicalType();
13857 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
13858 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13859 RecordTypeList.push_back(FieldRecTy);
13860 }
13861 }
13862 ++NextToCheckIndex;
13863 }
13864}
13865
13866/// Emit an error for the case where a record we are trying to assign to has a
13867/// const-qualified field somewhere in its hierarchy.
13868static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13869 SourceLocation Loc) {
13870 QualType Ty = E->getType();
13871 assert(Ty->isRecordType() && "lvalue was not record?");
13872 SourceRange Range = E->getSourceRange();
13873 const auto *RTy = Ty->getAsCanonical<RecordType>();
13874 bool DiagEmitted = false;
13875
13876 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13877 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13878 Range, OEK_Member, DiagEmitted);
13879 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13880 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13881 Range, OEK_Variable, DiagEmitted);
13882 else
13883 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13884 Range, OEK_LValue, DiagEmitted);
13885 if (!DiagEmitted)
13886 DiagnoseConstAssignment(S, E, Loc);
13887}
13888
13889/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13890/// emit an error and return true. If so, return false.
13892 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13893
13895
13896 SourceLocation OrigLoc = Loc;
13898 &Loc);
13899 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13901 if (IsLV == Expr::MLV_Valid)
13902 return false;
13903
13904 unsigned DiagID = 0;
13905 bool NeedType = false;
13906 switch (IsLV) { // C99 6.5.16p2
13908 // Use a specialized diagnostic when we're assigning to an object
13909 // from an enclosing function or block.
13911 if (NCCK == NCCK_Block)
13912 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13913 else
13914 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13915 break;
13916 }
13917
13918 // In ARC, use some specialized diagnostics for occasions where we
13919 // infer 'const'. These are always pseudo-strong variables.
13920 if (S.getLangOpts().ObjCAutoRefCount) {
13921 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13922 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13923 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13924
13925 // Use the normal diagnostic if it's pseudo-__strong but the
13926 // user actually wrote 'const'.
13927 if (var->isARCPseudoStrong() &&
13928 (!var->getTypeSourceInfo() ||
13929 !var->getTypeSourceInfo()->getType().isConstQualified())) {
13930 // There are three pseudo-strong cases:
13931 // - self
13932 ObjCMethodDecl *method = S.getCurMethodDecl();
13933 if (method && var == method->getSelfDecl()) {
13934 DiagID = method->isClassMethod()
13935 ? diag::err_typecheck_arc_assign_self_class_method
13936 : diag::err_typecheck_arc_assign_self;
13937
13938 // - Objective-C externally_retained attribute.
13939 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13940 isa<ParmVarDecl>(var)) {
13941 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13942
13943 // - fast enumeration variables
13944 } else {
13945 DiagID = diag::err_typecheck_arr_assign_enumeration;
13946 }
13947
13948 SourceRange Assign;
13949 if (Loc != OrigLoc)
13950 Assign = SourceRange(OrigLoc, OrigLoc);
13951 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13952 // We need to preserve the AST regardless, so migration tool
13953 // can do its job.
13954 return false;
13955 }
13956 }
13957 }
13958
13959 // If none of the special cases above are triggered, then this is a
13960 // simple const assignment.
13961 if (DiagID == 0) {
13962 DiagnoseConstAssignment(S, E, Loc);
13963 return true;
13964 }
13965
13966 break;
13968 DiagnoseConstAssignment(S, E, Loc);
13969 return true;
13972 return true;
13975 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13976 NeedType = true;
13977 break;
13979 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13980 NeedType = true;
13981 break;
13983 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13984 break;
13985 case Expr::MLV_Valid:
13986 llvm_unreachable("did not take early return for MLV_Valid");
13990 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13991 break;
13994 return S.RequireCompleteType(Loc, E->getType(),
13995 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13997 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13998 break;
14000 llvm_unreachable("readonly properties should be processed differently");
14002 DiagID = diag::err_readonly_message_assignment;
14003 break;
14005 DiagID = diag::err_no_subobject_property_setting;
14006 break;
14007 }
14008
14009 SourceRange Assign;
14010 if (Loc != OrigLoc)
14011 Assign = SourceRange(OrigLoc, OrigLoc);
14012 if (NeedType)
14013 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14014 else
14015 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14016 return true;
14017}
14018
14019static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14020 SourceLocation Loc,
14021 Sema &Sema) {
14023 return;
14025 return;
14026 if (Loc.isInvalid() || Loc.isMacroID())
14027 return;
14028 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14029 return;
14030
14031 // C / C++ fields
14032 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14033 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14034 if (ML && MR) {
14035 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14036 return;
14037 const ValueDecl *LHSDecl =
14039 const ValueDecl *RHSDecl =
14041 if (LHSDecl != RHSDecl)
14042 return;
14043 if (LHSDecl->getType().isVolatileQualified())
14044 return;
14045 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14046 if (RefTy->getPointeeType().isVolatileQualified())
14047 return;
14048
14049 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14050 }
14051
14052 // Objective-C instance variables
14053 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14054 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14055 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14056 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14057 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14058 if (RL && RR && RL->getDecl() == RR->getDecl())
14059 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14060 }
14061}
14062
14063// C99 6.5.16.1
14065 SourceLocation Loc,
14066 QualType CompoundType,
14067 BinaryOperatorKind Opc) {
14068 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14069
14070 // Verify that LHS is a modifiable lvalue, and emit error if not.
14071 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14072 return QualType();
14073
14074 QualType LHSType = LHSExpr->getType();
14075 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14076 CompoundType;
14077
14078 if (RHS.isUsable()) {
14079 // Even if this check fails don't return early to allow the best
14080 // possible error recovery and to allow any subsequent diagnostics to
14081 // work.
14082 const ValueDecl *Assignee = nullptr;
14083 bool ShowFullyQualifiedAssigneeName = false;
14084 // In simple cases describe what is being assigned to
14085 if (auto *DR = dyn_cast<DeclRefExpr>(LHSExpr->IgnoreParenCasts())) {
14086 Assignee = DR->getDecl();
14087 } else if (auto *ME = dyn_cast<MemberExpr>(LHSExpr->IgnoreParenCasts())) {
14088 Assignee = ME->getMemberDecl();
14089 ShowFullyQualifiedAssigneeName = true;
14090 }
14091
14093 LHSType, RHS.get(), AssignmentAction::Assigning, Loc, Assignee,
14094 ShowFullyQualifiedAssigneeName);
14095 }
14096
14097 // OpenCL v1.2 s6.1.1.1 p2:
14098 // The half data type can only be used to declare a pointer to a buffer that
14099 // contains half values
14100 if (getLangOpts().OpenCL &&
14101 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14102 LHSType->isHalfType()) {
14103 Diag(Loc, diag::err_opencl_half_load_store) << 1
14104 << LHSType.getUnqualifiedType();
14105 return QualType();
14106 }
14107
14108 // WebAssembly tables can't be used on RHS of an assignment expression.
14109 if (RHSType->isWebAssemblyTableType()) {
14110 Diag(Loc, diag::err_wasm_table_art) << 0;
14111 return QualType();
14112 }
14113
14114 AssignConvertType ConvTy;
14115 if (CompoundType.isNull()) {
14116 Expr *RHSCheck = RHS.get();
14117
14118 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14119
14120 QualType LHSTy(LHSType);
14121 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14122 if (RHS.isInvalid())
14123 return QualType();
14124 // Special case of NSObject attributes on c-style pointer types.
14126 ((Context.isObjCNSObjectType(LHSType) &&
14127 RHSType->isObjCObjectPointerType()) ||
14128 (Context.isObjCNSObjectType(RHSType) &&
14129 LHSType->isObjCObjectPointerType())))
14131
14132 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14133 Diag(Loc, diag::err_objc_object_assignment) << LHSType;
14134
14135 // If the RHS is a unary plus or minus, check to see if they = and + are
14136 // right next to each other. If so, the user may have typo'd "x =+ 4"
14137 // instead of "x += 4".
14138 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14139 RHSCheck = ICE->getSubExpr();
14140 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14141 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14142 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14143 // Only if the two operators are exactly adjacent.
14144 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14145 // And there is a space or other character before the subexpr of the
14146 // unary +/-. We don't want to warn on "x=-1".
14147 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14148 UO->getSubExpr()->getBeginLoc().isFileID()) {
14149 Diag(Loc, diag::warn_not_compound_assign)
14150 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14151 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14152 }
14153 }
14154
14155 if (IsAssignConvertCompatible(ConvTy)) {
14156 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14157 // Warn about retain cycles where a block captures the LHS, but
14158 // not if the LHS is a simple variable into which the block is
14159 // being stored...unless that variable can be captured by reference!
14160 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14161 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14162 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14163 ObjC().checkRetainCycles(LHSExpr, RHS.get());
14164 }
14165
14166 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14168 // It is safe to assign a weak reference into a strong variable.
14169 // Although this code can still have problems:
14170 // id x = self.weakProp;
14171 // id y = self.weakProp;
14172 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14173 // paths through the function. This should be revisited if
14174 // -Wrepeated-use-of-weak is made flow-sensitive.
14175 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14176 // variable, which will be valid for the current autorelease scope.
14177 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14178 RHS.get()->getBeginLoc()))
14180
14181 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14182 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14183 }
14184 }
14185 } else {
14186 // Compound assignment "x += y"
14187 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14188 }
14189
14190 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
14192 return QualType();
14193
14194 CheckForNullPointerDereference(*this, LHSExpr);
14195
14196 AssignedEntity AE{LHSExpr};
14197 checkAssignmentLifetime(*this, AE, RHS.get());
14198
14199 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14200 if (CompoundType.isNull()) {
14201 // C++2a [expr.ass]p5:
14202 // A simple-assignment whose left operand is of a volatile-qualified
14203 // type is deprecated unless the assignment is either a discarded-value
14204 // expression or an unevaluated operand
14205 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14206 }
14207 }
14208
14209 // C11 6.5.16p3: The type of an assignment expression is the type of the
14210 // left operand would have after lvalue conversion.
14211 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14212 // qualified type, the value has the unqualified version of the type of the
14213 // lvalue; additionally, if the lvalue has atomic type, the value has the
14214 // non-atomic version of the type of the lvalue.
14215 // C++ 5.17p1: the type of the assignment expression is that of its left
14216 // operand.
14217 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14218}
14219
14220// Scenarios to ignore if expression E is:
14221// 1. an explicit cast expression into void
14222// 2. a function call expression that returns void
14223static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14224 E = E->IgnoreParens();
14225
14226 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14227 if (CE->getCastKind() == CK_ToVoid) {
14228 return true;
14229 }
14230
14231 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14232 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14233 CE->getSubExpr()->getType()->isDependentType()) {
14234 return true;
14235 }
14236 }
14237
14238 if (const auto *CE = dyn_cast<CallExpr>(E))
14239 return CE->getCallReturnType(Context)->isVoidType();
14240 return false;
14241}
14242
14244 // No warnings in macros
14245 if (Loc.isMacroID())
14246 return;
14247
14248 // Don't warn in template instantiations.
14250 return;
14251
14252 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14253 // instead, skip more than needed, then call back into here with the
14254 // CommaVisitor in SemaStmt.cpp.
14255 // The listed locations are the initialization and increment portions
14256 // of a for loop. The additional checks are on the condition of
14257 // if statements, do/while loops, and for loops.
14258 // Differences in scope flags for C89 mode requires the extra logic.
14259 const unsigned ForIncrementFlags =
14260 getLangOpts().C99 || getLangOpts().CPlusPlus
14263 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14264 const unsigned ScopeFlags = getCurScope()->getFlags();
14265 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14266 (ScopeFlags & ForInitFlags) == ForInitFlags)
14267 return;
14268
14269 // If there are multiple comma operators used together, get the RHS of the
14270 // of the comma operator as the LHS.
14271 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14272 if (BO->getOpcode() != BO_Comma)
14273 break;
14274 LHS = BO->getRHS();
14275 }
14276
14277 // Only allow some expressions on LHS to not warn.
14278 if (IgnoreCommaOperand(LHS, Context))
14279 return;
14280
14281 Diag(Loc, diag::warn_comma_operator);
14282 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14283 << LHS->getSourceRange()
14285 LangOpts.CPlusPlus ? "static_cast<void>("
14286 : "(void)(")
14287 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14288 ")");
14289}
14290
14291// C99 6.5.17
14293 SourceLocation Loc) {
14294 LHS = S.CheckPlaceholderExpr(LHS.get());
14295 RHS = S.CheckPlaceholderExpr(RHS.get());
14296 if (LHS.isInvalid() || RHS.isInvalid())
14297 return QualType();
14298
14299 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14300 // operands, but not unary promotions.
14301 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14302
14303 // So we treat the LHS as a ignored value, and in C++ we allow the
14304 // containing site to determine what should be done with the RHS.
14305 LHS = S.IgnoredValueConversions(LHS.get());
14306 if (LHS.isInvalid())
14307 return QualType();
14308
14309 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14310
14311 if (!S.getLangOpts().CPlusPlus) {
14313 if (RHS.isInvalid())
14314 return QualType();
14315 if (!RHS.get()->getType()->isVoidType())
14316 S.RequireCompleteType(Loc, RHS.get()->getType(),
14317 diag::err_incomplete_type);
14318 }
14319
14320 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14321 S.DiagnoseCommaOperator(LHS.get(), Loc);
14322
14323 return RHS.get()->getType();
14324}
14325
14326/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14327/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14330 ExprObjectKind &OK,
14331 SourceLocation OpLoc, bool IsInc,
14332 bool IsPrefix) {
14333 QualType ResType = Op->getType();
14334 // Atomic types can be used for increment / decrement where the non-atomic
14335 // versions can, so ignore the _Atomic() specifier for the purpose of
14336 // checking.
14337 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14338 ResType = ResAtomicType->getValueType();
14339
14340 assert(!ResType.isNull() && "no type for increment/decrement expression");
14341
14342 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14343 // Decrement of bool is not allowed.
14344 if (!IsInc) {
14345 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14346 return QualType();
14347 }
14348 // Increment of bool sets it to true, but is deprecated.
14349 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14350 : diag::warn_increment_bool)
14351 << Op->getSourceRange();
14352 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14353 // Error on enum increments and decrements in C++ mode
14354 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14355 return QualType();
14356 } else if (ResType->isRealType()) {
14357 // OK!
14358 } else if (ResType->isPointerType()) {
14359 // C99 6.5.2.4p2, 6.5.6p2
14360 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14361 return QualType();
14362 } else if (ResType->isObjCObjectPointerType()) {
14363 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14364 // Otherwise, we just need a complete type.
14365 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14366 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14367 return QualType();
14368 } else if (ResType->isAnyComplexType()) {
14369 // C99 does not support ++/-- on complex types, we allow as an extension.
14370 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14371 : diag::ext_c2y_increment_complex)
14372 << IsInc << Op->getSourceRange();
14373 } else if (ResType->isPlaceholderType()) {
14375 if (PR.isInvalid()) return QualType();
14376 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14377 IsInc, IsPrefix);
14378 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14379 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14380 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14381 (ResType->castAs<VectorType>()->getVectorKind() !=
14383 // The z vector extensions allow ++ and -- for non-bool vectors.
14384 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14385 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14386 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14387 } else {
14388 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14389 << ResType << int(IsInc) << Op->getSourceRange();
14390 return QualType();
14391 }
14392 // At this point, we know we have a real, complex or pointer type.
14393 // Now make sure the operand is a modifiable lvalue.
14394 if (CheckForModifiableLvalue(Op, OpLoc, S))
14395 return QualType();
14396 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14397 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14398 // An operand with volatile-qualified type is deprecated
14399 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14400 << IsInc << ResType;
14401 }
14402 // In C++, a prefix increment is the same type as the operand. Otherwise
14403 // (in C or with postfix), the increment is the unqualified type of the
14404 // operand.
14405 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14406 VK = VK_LValue;
14407 OK = Op->getObjectKind();
14408 return ResType;
14409 } else {
14410 VK = VK_PRValue;
14411 return ResType.getUnqualifiedType();
14412 }
14413}
14414
14415/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14416/// This routine allows us to typecheck complex/recursive expressions
14417/// where the declaration is needed for type checking. We only need to
14418/// handle cases when the expression references a function designator
14419/// or is an lvalue. Here are some examples:
14420/// - &(x) => x
14421/// - &*****f => f for f a function designator.
14422/// - &s.xx => s
14423/// - &s.zz[1].yy -> s, if zz is an array
14424/// - *(x + 1) -> x, if x is an array
14425/// - &"123"[2] -> 0
14426/// - & __real__ x -> x
14427///
14428/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14429/// members.
14431 switch (E->getStmtClass()) {
14432 case Stmt::DeclRefExprClass:
14433 return cast<DeclRefExpr>(E)->getDecl();
14434 case Stmt::MemberExprClass:
14435 // If this is an arrow operator, the address is an offset from
14436 // the base's value, so the object the base refers to is
14437 // irrelevant.
14438 if (cast<MemberExpr>(E)->isArrow())
14439 return nullptr;
14440 // Otherwise, the expression refers to a part of the base
14441 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14442 case Stmt::ArraySubscriptExprClass: {
14443 // FIXME: This code shouldn't be necessary! We should catch the implicit
14444 // promotion of register arrays earlier.
14445 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14446 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14447 if (ICE->getSubExpr()->getType()->isArrayType())
14448 return getPrimaryDecl(ICE->getSubExpr());
14449 }
14450 return nullptr;
14451 }
14452 case Stmt::UnaryOperatorClass: {
14454
14455 switch(UO->getOpcode()) {
14456 case UO_Real:
14457 case UO_Imag:
14458 case UO_Extension:
14459 return getPrimaryDecl(UO->getSubExpr());
14460 default:
14461 return nullptr;
14462 }
14463 }
14464 case Stmt::ParenExprClass:
14465 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14466 case Stmt::ImplicitCastExprClass:
14467 // If the result of an implicit cast is an l-value, we care about
14468 // the sub-expression; otherwise, the result here doesn't matter.
14469 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14470 case Stmt::CXXUuidofExprClass:
14471 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14472 default:
14473 return nullptr;
14474 }
14475}
14476
14477namespace {
14478enum {
14479 AO_Bit_Field = 0,
14480 AO_Vector_Element = 1,
14481 AO_Property_Expansion = 2,
14482 AO_Register_Variable = 3,
14483 AO_Matrix_Element = 4,
14484 AO_No_Error = 5
14485};
14486}
14487/// Diagnose invalid operand for address of operations.
14488///
14489/// \param Type The type of operand which cannot have its address taken.
14491 Expr *E, unsigned Type) {
14492 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14493}
14494
14496 const Expr *Op,
14497 const CXXMethodDecl *MD) {
14498 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14499
14500 if (Op != DRE)
14501 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14502 << Op->getSourceRange();
14503
14504 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14505 if (isa<CXXDestructorDecl>(MD))
14506 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14507 << DRE->getSourceRange();
14508
14509 if (DRE->getQualifier())
14510 return false;
14511
14512 if (MD->getParent()->getName().empty())
14513 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14514 << DRE->getSourceRange();
14515
14516 SmallString<32> Str;
14517 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14518 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14519 << DRE->getSourceRange()
14520 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14521}
14522
14524 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14525 if (PTy->getKind() == BuiltinType::Overload) {
14526 Expr *E = OrigOp.get()->IgnoreParens();
14527 if (!isa<OverloadExpr>(E)) {
14528 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14529 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14530 << OrigOp.get()->getSourceRange();
14531 return QualType();
14532 }
14533
14537 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14538 << OrigOp.get()->getSourceRange();
14539 return QualType();
14540 }
14541
14542 return Context.OverloadTy;
14543 }
14544
14545 if (PTy->getKind() == BuiltinType::UnknownAny)
14546 return Context.UnknownAnyTy;
14547
14548 if (PTy->getKind() == BuiltinType::BoundMember) {
14549 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14550 << OrigOp.get()->getSourceRange();
14551 return QualType();
14552 }
14553
14554 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14555 if (OrigOp.isInvalid()) return QualType();
14556 }
14557
14558 if (OrigOp.get()->isTypeDependent())
14559 return Context.DependentTy;
14560
14561 assert(!OrigOp.get()->hasPlaceholderType());
14562
14563 // Make sure to ignore parentheses in subsequent checks
14564 Expr *op = OrigOp.get()->IgnoreParens();
14565
14566 // In OpenCL captures for blocks called as lambda functions
14567 // are located in the private address space. Blocks used in
14568 // enqueue_kernel can be located in a different address space
14569 // depending on a vendor implementation. Thus preventing
14570 // taking an address of the capture to avoid invalid AS casts.
14571 if (LangOpts.OpenCL) {
14572 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14573 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14574 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14575 return QualType();
14576 }
14577 }
14578
14579 if (getLangOpts().C99) {
14580 // Implement C99-only parts of addressof rules.
14581 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14582 if (uOp->getOpcode() == UO_Deref)
14583 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14584 // (assuming the deref expression is valid).
14585 return uOp->getSubExpr()->getType();
14586 }
14587 // Technically, there should be a check for array subscript
14588 // expressions here, but the result of one is always an lvalue anyway.
14589 }
14590 ValueDecl *dcl = getPrimaryDecl(op);
14591
14592 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14593 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14594 op->getBeginLoc()))
14595 return QualType();
14596
14598 unsigned AddressOfError = AO_No_Error;
14599
14600 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14601 bool sfinae = (bool)isSFINAEContext();
14602 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14603 : diag::ext_typecheck_addrof_temporary)
14604 << op->getType() << op->getSourceRange();
14605 if (sfinae)
14606 return QualType();
14607 // Materialize the temporary as an lvalue so that we can take its address.
14608 OrigOp = op =
14609 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14610 } else if (isa<ObjCSelectorExpr>(op)) {
14611 return Context.getPointerType(op->getType());
14612 } else if (lval == Expr::LV_MemberFunction) {
14613 // If it's an instance method, make a member pointer.
14614 // The expression must have exactly the form &A::foo.
14615
14616 // If the underlying expression isn't a decl ref, give up.
14617 if (!isa<DeclRefExpr>(op)) {
14618 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14619 << OrigOp.get()->getSourceRange();
14620 return QualType();
14621 }
14622 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14624
14625 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14626 QualType MPTy = Context.getMemberPointerType(
14627 op->getType(), DRE->getQualifier(), MD->getParent());
14628
14629 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14630 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14631 // When pointer authentication is enabled, argument and return types of
14632 // vitual member functions must be complete. This is because vitrual
14633 // member function pointers are implemented using virtual dispatch
14634 // thunks and the thunks cannot be emitted if the argument or return
14635 // types are incomplete.
14636 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14637 SourceLocation DeclRefLoc,
14638 SourceLocation RetArgTypeLoc) {
14639 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
14640 Diag(DeclRefLoc,
14641 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14642 Diag(RetArgTypeLoc,
14643 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14644 << T;
14645 return true;
14646 }
14647 return false;
14648 };
14649 QualType RetTy = MD->getReturnType();
14650 bool IsIncomplete =
14651 !RetTy->isVoidType() &&
14652 ReturnOrParamTypeIsIncomplete(
14653 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14654 for (auto *PVD : MD->parameters())
14655 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14656 PVD->getBeginLoc());
14657 if (IsIncomplete)
14658 return QualType();
14659 }
14660
14661 // Under the MS ABI, lock down the inheritance model now.
14662 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14663 (void)isCompleteType(OpLoc, MPTy);
14664 return MPTy;
14665 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14666 // C99 6.5.3.2p1
14667 // The operand must be either an l-value or a function designator
14668 if (!op->getType()->isFunctionType()) {
14669 // Use a special diagnostic for loads from property references.
14670 if (isa<PseudoObjectExpr>(op)) {
14671 AddressOfError = AO_Property_Expansion;
14672 } else {
14673 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14674 << op->getType() << op->getSourceRange();
14675 return QualType();
14676 }
14677 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14678 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14679 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14680 }
14681
14682 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14683 // The operand cannot be a bit-field
14684 AddressOfError = AO_Bit_Field;
14685 } else if (op->getObjectKind() == OK_VectorComponent) {
14686 // The operand cannot be an element of a vector
14687 AddressOfError = AO_Vector_Element;
14688 } else if (op->getObjectKind() == OK_MatrixComponent) {
14689 // The operand cannot be an element of a matrix.
14690 AddressOfError = AO_Matrix_Element;
14691 } else if (dcl) { // C99 6.5.3.2p1
14692 // We have an lvalue with a decl. Make sure the decl is not declared
14693 // with the register storage-class specifier.
14694 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14695 // in C++ it is not error to take address of a register
14696 // variable (c++03 7.1.1P3)
14697 if (vd->getStorageClass() == SC_Register &&
14699 AddressOfError = AO_Register_Variable;
14700 }
14701 } else if (isa<MSPropertyDecl>(dcl)) {
14702 AddressOfError = AO_Property_Expansion;
14703 } else if (isa<FunctionTemplateDecl>(dcl)) {
14704 return Context.OverloadTy;
14705 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14706 // Okay: we can take the address of a field.
14707 // Could be a pointer to member, though, if there is an explicit
14708 // scope qualifier for the class.
14709
14710 // [C++26] [expr.prim.id.general]
14711 // If an id-expression E denotes a non-static non-type member
14712 // of some class C [...] and if E is a qualified-id, E is
14713 // not the un-parenthesized operand of the unary & operator [...]
14714 // the id-expression is transformed into a class member access expression.
14715 if (auto *DRE = dyn_cast<DeclRefExpr>(op);
14716 DRE && DRE->getQualifier() && !isa<ParenExpr>(OrigOp.get())) {
14717 DeclContext *Ctx = dcl->getDeclContext();
14718 if (Ctx && Ctx->isRecord()) {
14719 if (dcl->getType()->isReferenceType()) {
14720 Diag(OpLoc,
14721 diag::err_cannot_form_pointer_to_member_of_reference_type)
14722 << dcl->getDeclName() << dcl->getType();
14723 return QualType();
14724 }
14725
14726 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14727 Ctx = Ctx->getParent();
14728
14729 QualType MPTy = Context.getMemberPointerType(
14730 op->getType(), DRE->getQualifier(), cast<CXXRecordDecl>(Ctx));
14731 // Under the MS ABI, lock down the inheritance model now.
14732 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14733 (void)isCompleteType(OpLoc, MPTy);
14734 return MPTy;
14735 }
14736 }
14740 llvm_unreachable("Unknown/unexpected decl type");
14741 }
14742
14743 if (AddressOfError != AO_No_Error) {
14744 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14745 return QualType();
14746 }
14747
14748 if (lval == Expr::LV_IncompleteVoidType) {
14749 // Taking the address of a void variable is technically illegal, but we
14750 // allow it in cases which are otherwise valid.
14751 // Example: "extern void x; void* y = &x;".
14752 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14753 }
14754
14755 // If the operand has type "type", the result has type "pointer to type".
14756 if (op->getType()->isObjCObjectType())
14757 return Context.getObjCObjectPointerType(op->getType());
14758
14759 // Cannot take the address of WebAssembly references or tables.
14760 if (Context.getTargetInfo().getTriple().isWasm()) {
14761 QualType OpTy = op->getType();
14762 if (OpTy.isWebAssemblyReferenceType()) {
14763 Diag(OpLoc, diag::err_wasm_ca_reference)
14764 << 1 << OrigOp.get()->getSourceRange();
14765 return QualType();
14766 }
14767 if (OpTy->isWebAssemblyTableType()) {
14768 Diag(OpLoc, diag::err_wasm_table_pr)
14769 << 1 << OrigOp.get()->getSourceRange();
14770 return QualType();
14771 }
14772 }
14773
14774 CheckAddressOfPackedMember(op);
14775
14776 return Context.getPointerType(op->getType());
14777}
14778
14779static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14780 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14781 if (!DRE)
14782 return;
14783 const Decl *D = DRE->getDecl();
14784 if (!D)
14785 return;
14786 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14787 if (!Param)
14788 return;
14789 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14790 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14791 return;
14792 if (FunctionScopeInfo *FD = S.getCurFunction())
14793 FD->ModifiedNonNullParams.insert(Param);
14794}
14795
14796/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14798 SourceLocation OpLoc,
14799 bool IsAfterAmp = false) {
14800 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14801 if (ConvResult.isInvalid())
14802 return QualType();
14803 Op = ConvResult.get();
14804 QualType OpTy = Op->getType();
14805 QualType Result;
14806
14808 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14809 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14810 Op->getSourceRange());
14811 }
14812
14813 if (const PointerType *PT = OpTy->getAs<PointerType>())
14814 {
14815 Result = PT->getPointeeType();
14816 }
14817 else if (const ObjCObjectPointerType *OPT =
14819 Result = OPT->getPointeeType();
14820 else {
14822 if (PR.isInvalid()) return QualType();
14823 if (PR.get() != Op)
14824 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14825 }
14826
14827 if (Result.isNull()) {
14828 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14829 << OpTy << Op->getSourceRange();
14830 return QualType();
14831 }
14832
14833 if (Result->isVoidType()) {
14834 // C++ [expr.unary.op]p1:
14835 // [...] the expression to which [the unary * operator] is applied shall
14836 // be a pointer to an object type, or a pointer to a function type
14837 LangOptions LO = S.getLangOpts();
14838 if (LO.CPlusPlus)
14839 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14840 << OpTy << Op->getSourceRange();
14841 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14842 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14843 << OpTy << Op->getSourceRange();
14844 }
14845
14846 // Dereferences are usually l-values...
14847 VK = VK_LValue;
14848
14849 // ...except that certain expressions are never l-values in C.
14850 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14851 VK = VK_PRValue;
14852
14853 return Result;
14854}
14855
14856BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14858 switch (Kind) {
14859 default: llvm_unreachable("Unknown binop!");
14860 case tok::periodstar: Opc = BO_PtrMemD; break;
14861 case tok::arrowstar: Opc = BO_PtrMemI; break;
14862 case tok::star: Opc = BO_Mul; break;
14863 case tok::slash: Opc = BO_Div; break;
14864 case tok::percent: Opc = BO_Rem; break;
14865 case tok::plus: Opc = BO_Add; break;
14866 case tok::minus: Opc = BO_Sub; break;
14867 case tok::lessless: Opc = BO_Shl; break;
14868 case tok::greatergreater: Opc = BO_Shr; break;
14869 case tok::lessequal: Opc = BO_LE; break;
14870 case tok::less: Opc = BO_LT; break;
14871 case tok::greaterequal: Opc = BO_GE; break;
14872 case tok::greater: Opc = BO_GT; break;
14873 case tok::exclaimequal: Opc = BO_NE; break;
14874 case tok::equalequal: Opc = BO_EQ; break;
14875 case tok::spaceship: Opc = BO_Cmp; break;
14876 case tok::amp: Opc = BO_And; break;
14877 case tok::caret: Opc = BO_Xor; break;
14878 case tok::pipe: Opc = BO_Or; break;
14879 case tok::ampamp: Opc = BO_LAnd; break;
14880 case tok::pipepipe: Opc = BO_LOr; break;
14881 case tok::equal: Opc = BO_Assign; break;
14882 case tok::starequal: Opc = BO_MulAssign; break;
14883 case tok::slashequal: Opc = BO_DivAssign; break;
14884 case tok::percentequal: Opc = BO_RemAssign; break;
14885 case tok::plusequal: Opc = BO_AddAssign; break;
14886 case tok::minusequal: Opc = BO_SubAssign; break;
14887 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14888 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14889 case tok::ampequal: Opc = BO_AndAssign; break;
14890 case tok::caretequal: Opc = BO_XorAssign; break;
14891 case tok::pipeequal: Opc = BO_OrAssign; break;
14892 case tok::comma: Opc = BO_Comma; break;
14893 }
14894 return Opc;
14895}
14896
14898 tok::TokenKind Kind) {
14900 switch (Kind) {
14901 default: llvm_unreachable("Unknown unary op!");
14902 case tok::plusplus: Opc = UO_PreInc; break;
14903 case tok::minusminus: Opc = UO_PreDec; break;
14904 case tok::amp: Opc = UO_AddrOf; break;
14905 case tok::star: Opc = UO_Deref; break;
14906 case tok::plus: Opc = UO_Plus; break;
14907 case tok::minus: Opc = UO_Minus; break;
14908 case tok::tilde: Opc = UO_Not; break;
14909 case tok::exclaim: Opc = UO_LNot; break;
14910 case tok::kw___real: Opc = UO_Real; break;
14911 case tok::kw___imag: Opc = UO_Imag; break;
14912 case tok::kw___extension__: Opc = UO_Extension; break;
14913 }
14914 return Opc;
14915}
14916
14917const FieldDecl *
14919 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14920 // common for setters.
14921 // struct A {
14922 // int X;
14923 // -void setX(int X) { X = X; }
14924 // +void setX(int X) { this->X = X; }
14925 // };
14926
14927 // Only consider parameters for self assignment fixes.
14928 if (!isa<ParmVarDecl>(SelfAssigned))
14929 return nullptr;
14930 const auto *Method =
14931 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14932 if (!Method)
14933 return nullptr;
14934
14935 const CXXRecordDecl *Parent = Method->getParent();
14936 // In theory this is fixable if the lambda explicitly captures this, but
14937 // that's added complexity that's rarely going to be used.
14938 if (Parent->isLambda())
14939 return nullptr;
14940
14941 // FIXME: Use an actual Lookup operation instead of just traversing fields
14942 // in order to get base class fields.
14943 auto Field =
14944 llvm::find_if(Parent->fields(),
14945 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14946 return F->getDeclName() == Name;
14947 });
14948 return (Field != Parent->field_end()) ? *Field : nullptr;
14949}
14950
14951/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14952/// This warning suppressed in the event of macro expansions.
14953static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14954 SourceLocation OpLoc, bool IsBuiltin) {
14956 return;
14957 if (S.isUnevaluatedContext())
14958 return;
14959 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14960 return;
14961 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14962 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14963 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14964 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14965 if (!LHSDeclRef || !RHSDeclRef ||
14966 LHSDeclRef->getLocation().isMacroID() ||
14967 RHSDeclRef->getLocation().isMacroID())
14968 return;
14969 const ValueDecl *LHSDecl =
14970 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14971 const ValueDecl *RHSDecl =
14972 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14973 if (LHSDecl != RHSDecl)
14974 return;
14975 if (LHSDecl->getType().isVolatileQualified())
14976 return;
14977 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14978 if (RefTy->getPointeeType().isVolatileQualified())
14979 return;
14980
14981 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14982 : diag::warn_self_assignment_overloaded)
14983 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14984 << RHSExpr->getSourceRange();
14985 if (const FieldDecl *SelfAssignField =
14987 Diag << 1 << SelfAssignField
14988 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14989 else
14990 Diag << 0;
14991}
14992
14993/// Check if a bitwise-& is performed on an Objective-C pointer. This
14994/// is usually indicative of introspection within the Objective-C pointer.
14996 SourceLocation OpLoc) {
14997 if (!S.getLangOpts().ObjC)
14998 return;
14999
15000 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15001 const Expr *LHS = L.get();
15002 const Expr *RHS = R.get();
15003
15005 ObjCPointerExpr = LHS;
15006 OtherExpr = RHS;
15007 }
15008 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15009 ObjCPointerExpr = RHS;
15010 OtherExpr = LHS;
15011 }
15012
15013 // This warning is deliberately made very specific to reduce false
15014 // positives with logic that uses '&' for hashing. This logic mainly
15015 // looks for code trying to introspect into tagged pointers, which
15016 // code should generally never do.
15017 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15018 unsigned Diag = diag::warn_objc_pointer_masking;
15019 // Determine if we are introspecting the result of performSelectorXXX.
15020 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15021 // Special case messages to -performSelector and friends, which
15022 // can return non-pointer values boxed in a pointer value.
15023 // Some clients may wish to silence warnings in this subcase.
15024 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15025 Selector S = ME->getSelector();
15026 StringRef SelArg0 = S.getNameForSlot(0);
15027 if (SelArg0.starts_with("performSelector"))
15028 Diag = diag::warn_objc_pointer_masking_performSelector;
15029 }
15030
15031 S.Diag(OpLoc, Diag)
15032 << ObjCPointerExpr->getSourceRange();
15033 }
15034}
15035
15036// This helper function promotes a binary operator's operands (which are of a
15037// half vector type) to a vector of floats and then truncates the result to
15038// a vector of either half or short.
15040 BinaryOperatorKind Opc, QualType ResultTy,
15042 bool IsCompAssign, SourceLocation OpLoc,
15043 FPOptionsOverride FPFeatures) {
15044 auto &Context = S.getASTContext();
15045 assert((isVector(ResultTy, Context.HalfTy) ||
15046 isVector(ResultTy, Context.ShortTy)) &&
15047 "Result must be a vector of half or short");
15048 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15049 isVector(RHS.get()->getType(), Context.HalfTy) &&
15050 "both operands expected to be a half vector");
15051
15052 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15053 QualType BinOpResTy = RHS.get()->getType();
15054
15055 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15056 // change BinOpResTy to a vector of ints.
15057 if (isVector(ResultTy, Context.ShortTy))
15058 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15059
15060 if (IsCompAssign)
15061 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15062 ResultTy, VK, OK, OpLoc, FPFeatures,
15063 BinOpResTy, BinOpResTy);
15064
15065 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15066 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15067 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15068 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15069}
15070
15071/// Returns true if conversion between vectors of halfs and vectors of floats
15072/// is needed.
15073static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15074 Expr *E0, Expr *E1 = nullptr) {
15075 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15077 return false;
15078
15079 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15080 QualType Ty = E->IgnoreImplicit()->getType();
15081
15082 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15083 // to vectors of floats. Although the element type of the vectors is __fp16,
15084 // the vectors shouldn't be treated as storage-only types. See the
15085 // discussion here: https://reviews.llvm.org/rG825235c140e7
15086 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15087 if (VT->getVectorKind() == VectorKind::Neon)
15088 return false;
15089 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15090 }
15091 return false;
15092 };
15093
15094 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15095}
15096
15098 BinaryOperatorKind Opc, Expr *LHSExpr,
15099 Expr *RHSExpr, bool ForFoldExpression) {
15100 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15101 // The syntax only allows initializer lists on the RHS of assignment,
15102 // so we don't need to worry about accepting invalid code for
15103 // non-assignment operators.
15104 // C++11 5.17p9:
15105 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15106 // of x = {} is x = T().
15108 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15109 InitializedEntity Entity =
15111 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15112 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15113 if (Init.isInvalid())
15114 return Init;
15115 RHSExpr = Init.get();
15116 }
15117
15118 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15119 QualType ResultTy; // Result type of the binary operator.
15120 // The following two variables are used for compound assignment operators
15121 QualType CompLHSTy; // Type of LHS after promotions for computation
15122 QualType CompResultTy; // Type of computation result
15125 bool ConvertHalfVec = false;
15126
15127 if (!LHS.isUsable() || !RHS.isUsable())
15128 return ExprError();
15129
15130 if (getLangOpts().OpenCL) {
15131 QualType LHSTy = LHSExpr->getType();
15132 QualType RHSTy = RHSExpr->getType();
15133 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15134 // the ATOMIC_VAR_INIT macro.
15135 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15136 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15137 if (BO_Assign == Opc)
15138 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15139 else
15140 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15141 return ExprError();
15142 }
15143
15144 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15145 // only with a builtin functions and therefore should be disallowed here.
15146 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15147 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15148 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15149 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15150 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15151 return ExprError();
15152 }
15153 }
15154
15155 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15156 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15157
15158 switch (Opc) {
15159 case BO_Assign:
15160 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15161 if (getLangOpts().CPlusPlus &&
15162 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15163 VK = LHS.get()->getValueKind();
15164 OK = LHS.get()->getObjectKind();
15165 }
15166 if (!ResultTy.isNull()) {
15167 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15168 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15169
15170 // Avoid copying a block to the heap if the block is assigned to a local
15171 // auto variable that is declared in the same scope as the block. This
15172 // optimization is unsafe if the local variable is declared in an outer
15173 // scope. For example:
15174 //
15175 // BlockTy b;
15176 // {
15177 // b = ^{...};
15178 // }
15179 // // It is unsafe to invoke the block here if it wasn't copied to the
15180 // // heap.
15181 // b();
15182
15183 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15184 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15185 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15186 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15187 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15188
15190 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15192 }
15193 RecordModifiableNonNullParam(*this, LHS.get());
15194 break;
15195 case BO_PtrMemD:
15196 case BO_PtrMemI:
15197 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15198 Opc == BO_PtrMemI);
15199 break;
15200 case BO_Mul:
15201 case BO_Div:
15202 ConvertHalfVec = true;
15203 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15204 break;
15205 case BO_Rem:
15206 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15207 break;
15208 case BO_Add:
15209 ConvertHalfVec = true;
15210 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15211 break;
15212 case BO_Sub:
15213 ConvertHalfVec = true;
15214 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);
15215 break;
15216 case BO_Shl:
15217 case BO_Shr:
15218 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15219 break;
15220 case BO_LE:
15221 case BO_LT:
15222 case BO_GE:
15223 case BO_GT:
15224 ConvertHalfVec = true;
15225 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15226
15227 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
15228 !ForFoldExpression && BI && BI->isComparisonOp())
15229 Diag(OpLoc, diag::warn_consecutive_comparison)
15230 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
15231
15232 break;
15233 case BO_EQ:
15234 case BO_NE:
15235 ConvertHalfVec = true;
15236 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15237 break;
15238 case BO_Cmp:
15239 ConvertHalfVec = true;
15240 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15241 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15242 break;
15243 case BO_And:
15244 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15245 [[fallthrough]];
15246 case BO_Xor:
15247 case BO_Or:
15248 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15249 break;
15250 case BO_LAnd:
15251 case BO_LOr:
15252 ConvertHalfVec = true;
15253 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15254 break;
15255 case BO_MulAssign:
15256 case BO_DivAssign:
15257 ConvertHalfVec = true;
15258 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15259 CompLHSTy = CompResultTy;
15260 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15261 ResultTy =
15262 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15263 break;
15264 case BO_RemAssign:
15265 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15266 CompLHSTy = CompResultTy;
15267 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15268 ResultTy =
15269 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15270 break;
15271 case BO_AddAssign:
15272 ConvertHalfVec = true;
15273 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15274 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15275 ResultTy =
15276 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15277 break;
15278 case BO_SubAssign:
15279 ConvertHalfVec = true;
15280 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15281 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15282 ResultTy =
15283 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15284 break;
15285 case BO_ShlAssign:
15286 case BO_ShrAssign:
15287 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15288 CompLHSTy = CompResultTy;
15289 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15290 ResultTy =
15291 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15292 break;
15293 case BO_AndAssign:
15294 case BO_OrAssign: // fallthrough
15295 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15296 [[fallthrough]];
15297 case BO_XorAssign:
15298 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15299 CompLHSTy = CompResultTy;
15300 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15301 ResultTy =
15302 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15303 break;
15304 case BO_Comma:
15305 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15306 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15307 VK = RHS.get()->getValueKind();
15308 OK = RHS.get()->getObjectKind();
15309 }
15310 break;
15311 }
15312 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15313 return ExprError();
15314
15315 // Some of the binary operations require promoting operands of half vector to
15316 // float vectors and truncating the result back to half vector. For now, we do
15317 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15318 // arm64).
15319 assert(
15320 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15321 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15322 "both sides are half vectors or neither sides are");
15323 ConvertHalfVec =
15324 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15325
15326 // Check for array bounds violations for both sides of the BinaryOperator
15327 CheckArrayAccess(LHS.get());
15328 CheckArrayAccess(RHS.get());
15329
15330 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15331 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15332 &Context.Idents.get("object_setClass"),
15334 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15335 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15336 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15338 "object_setClass(")
15339 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15340 ",")
15341 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15342 }
15343 else
15344 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15345 }
15346 else if (const ObjCIvarRefExpr *OIRE =
15347 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15348 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15349
15350 // Opc is not a compound assignment if CompResultTy is null.
15351 if (CompResultTy.isNull()) {
15352 if (ConvertHalfVec)
15353 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15354 OpLoc, CurFPFeatureOverrides());
15355 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15356 VK, OK, OpLoc, CurFPFeatureOverrides());
15357 }
15358
15359 // Handle compound assignments.
15360 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15362 VK = VK_LValue;
15363 OK = LHS.get()->getObjectKind();
15364 }
15365
15366 // The LHS is not converted to the result type for fixed-point compound
15367 // assignment as the common type is computed on demand. Reset the CompLHSTy
15368 // to the LHS type we would have gotten after unary conversions.
15369 if (CompResultTy->isFixedPointType())
15370 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15371
15372 if (ConvertHalfVec)
15373 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15374 OpLoc, CurFPFeatureOverrides());
15375
15377 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15378 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15379}
15380
15381/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15382/// operators are mixed in a way that suggests that the programmer forgot that
15383/// comparison operators have higher precedence. The most typical example of
15384/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15386 SourceLocation OpLoc, Expr *LHSExpr,
15387 Expr *RHSExpr) {
15388 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15389 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15390
15391 // Check that one of the sides is a comparison operator and the other isn't.
15392 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15393 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15394 if (isLeftComp == isRightComp)
15395 return;
15396
15397 // Bitwise operations are sometimes used as eager logical ops.
15398 // Don't diagnose this.
15399 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15400 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15401 if (isLeftBitwise || isRightBitwise)
15402 return;
15403
15404 SourceRange DiagRange = isLeftComp
15405 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15406 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15407 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15408 SourceRange ParensRange =
15409 isLeftComp
15410 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15411 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15412
15413 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15414 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15415 SuggestParentheses(Self, OpLoc,
15416 Self.PDiag(diag::note_precedence_silence) << OpStr,
15417 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15418 SuggestParentheses(Self, OpLoc,
15419 Self.PDiag(diag::note_precedence_bitwise_first)
15421 ParensRange);
15422}
15423
15424/// It accepts a '&&' expr that is inside a '||' one.
15425/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15426/// in parentheses.
15427static void
15429 BinaryOperator *Bop) {
15430 assert(Bop->getOpcode() == BO_LAnd);
15431 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15432 << Bop->getSourceRange() << OpLoc;
15434 Self.PDiag(diag::note_precedence_silence)
15435 << Bop->getOpcodeStr(),
15436 Bop->getSourceRange());
15437}
15438
15439/// Look for '&&' in the left hand of a '||' expr.
15441 Expr *LHSExpr, Expr *RHSExpr) {
15442 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15443 if (Bop->getOpcode() == BO_LAnd) {
15444 // If it's "string_literal && a || b" don't warn since the precedence
15445 // doesn't matter.
15446 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15447 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15448 } else if (Bop->getOpcode() == BO_LOr) {
15449 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15450 // If it's "a || b && string_literal || c" we didn't warn earlier for
15451 // "a || b && string_literal", but warn now.
15452 if (RBop->getOpcode() == BO_LAnd &&
15453 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15454 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15455 }
15456 }
15457 }
15458}
15459
15460/// Look for '&&' in the right hand of a '||' expr.
15462 Expr *LHSExpr, Expr *RHSExpr) {
15463 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15464 if (Bop->getOpcode() == BO_LAnd) {
15465 // If it's "a || b && string_literal" don't warn since the precedence
15466 // doesn't matter.
15467 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15468 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15469 }
15470 }
15471}
15472
15473/// Look for bitwise op in the left or right hand of a bitwise op with
15474/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15475/// the '&' expression in parentheses.
15477 SourceLocation OpLoc, Expr *SubExpr) {
15478 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15479 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15480 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15481 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15482 << Bop->getSourceRange() << OpLoc;
15483 SuggestParentheses(S, Bop->getOperatorLoc(),
15484 S.PDiag(diag::note_precedence_silence)
15485 << Bop->getOpcodeStr(),
15486 Bop->getSourceRange());
15487 }
15488 }
15489}
15490
15492 Expr *SubExpr, StringRef Shift) {
15493 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15494 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15495 StringRef Op = Bop->getOpcodeStr();
15496 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15497 << Bop->getSourceRange() << OpLoc << Shift << Op;
15498 SuggestParentheses(S, Bop->getOperatorLoc(),
15499 S.PDiag(diag::note_precedence_silence) << Op,
15500 Bop->getSourceRange());
15501 }
15502 }
15503}
15504
15506 Expr *LHSExpr, Expr *RHSExpr) {
15507 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15508 if (!OCE)
15509 return;
15510
15511 FunctionDecl *FD = OCE->getDirectCallee();
15512 if (!FD || !FD->isOverloadedOperator())
15513 return;
15514
15516 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15517 return;
15518
15519 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15520 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15521 << (Kind == OO_LessLess);
15523 S.PDiag(diag::note_precedence_silence)
15524 << (Kind == OO_LessLess ? "<<" : ">>"),
15525 OCE->getSourceRange());
15527 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15528 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15529}
15530
15531/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15532/// precedence.
15534 SourceLocation OpLoc, Expr *LHSExpr,
15535 Expr *RHSExpr){
15536 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15538 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15539
15540 // Diagnose "arg1 & arg2 | arg3"
15541 if ((Opc == BO_Or || Opc == BO_Xor) &&
15542 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15543 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15544 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15545 }
15546
15547 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15548 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15549 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15550 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15551 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15552 }
15553
15554 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15555 || Opc == BO_Shr) {
15556 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15557 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15558 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15559 }
15560
15561 // Warn on overloaded shift operators and comparisons, such as:
15562 // cout << 5 == 4;
15564 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15565}
15566
15568 tok::TokenKind Kind,
15569 Expr *LHSExpr, Expr *RHSExpr) {
15570 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15571 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15572 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15573
15574 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15575 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15576
15580
15581 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
15582 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
15583
15584 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15585}
15586
15588 UnresolvedSetImpl &Functions) {
15590 if (OverOp != OO_None && OverOp != OO_Equal)
15591 LookupOverloadedOperatorName(OverOp, S, Functions);
15592
15593 // In C++20 onwards, we may have a second operator to look up.
15594 if (getLangOpts().CPlusPlus20) {
15596 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15597 }
15598}
15599
15600/// Build an overloaded binary operator expression in the given scope.
15603 Expr *LHS, Expr *RHS) {
15604 switch (Opc) {
15605 case BO_Assign:
15606 // In the non-overloaded case, we warn about self-assignment (x = x) for
15607 // both simple assignment and certain compound assignments where algebra
15608 // tells us the operation yields a constant result. When the operator is
15609 // overloaded, we can't do the latter because we don't want to assume that
15610 // those algebraic identities still apply; for example, a path-building
15611 // library might use operator/= to append paths. But it's still reasonable
15612 // to assume that simple assignment is just moving/copying values around
15613 // and so self-assignment is likely a bug.
15614 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15615 [[fallthrough]];
15616 case BO_DivAssign:
15617 case BO_RemAssign:
15618 case BO_SubAssign:
15619 case BO_AndAssign:
15620 case BO_OrAssign:
15621 case BO_XorAssign:
15622 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15623 break;
15624 default:
15625 break;
15626 }
15627
15628 // Find all of the overloaded operators visible from this point.
15629 UnresolvedSet<16> Functions;
15630 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15631
15632 // Build the (potentially-overloaded, potentially-dependent)
15633 // binary operation.
15634 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15635}
15636
15638 BinaryOperatorKind Opc, Expr *LHSExpr,
15639 Expr *RHSExpr, bool ForFoldExpression) {
15640 if (!LHSExpr || !RHSExpr)
15641 return ExprError();
15642
15643 // We want to end up calling one of SemaPseudoObject::checkAssignment
15644 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15645 // both expressions are overloadable or either is type-dependent),
15646 // or CreateBuiltinBinOp (in any other case). We also want to get
15647 // any placeholder types out of the way.
15648
15649 // Handle pseudo-objects in the LHS.
15650 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15651 // Assignments with a pseudo-object l-value need special analysis.
15652 if (pty->getKind() == BuiltinType::PseudoObject &&
15654 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15655
15656 // Don't resolve overloads if the other type is overloadable.
15657 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15658 // We can't actually test that if we still have a placeholder,
15659 // though. Fortunately, none of the exceptions we see in that
15660 // code below are valid when the LHS is an overload set. Note
15661 // that an overload set can be dependently-typed, but it never
15662 // instantiates to having an overloadable type.
15663 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15664 if (resolvedRHS.isInvalid()) return ExprError();
15665 RHSExpr = resolvedRHS.get();
15666
15667 if (RHSExpr->isTypeDependent() ||
15668 RHSExpr->getType()->isOverloadableType())
15669 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15670 }
15671
15672 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15673 // template, diagnose the missing 'template' keyword instead of diagnosing
15674 // an invalid use of a bound member function.
15675 //
15676 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15677 // to C++1z [over.over]/1.4, but we already checked for that case above.
15678 if (Opc == BO_LT && inTemplateInstantiation() &&
15679 (pty->getKind() == BuiltinType::BoundMember ||
15680 pty->getKind() == BuiltinType::Overload)) {
15681 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15682 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15683 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15684 return isa<FunctionTemplateDecl>(ND);
15685 })) {
15686 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15687 : OE->getNameLoc(),
15688 diag::err_template_kw_missing)
15689 << OE->getName().getAsIdentifierInfo();
15690 return ExprError();
15691 }
15692 }
15693
15694 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15695 if (LHS.isInvalid()) return ExprError();
15696 LHSExpr = LHS.get();
15697 }
15698
15699 // Handle pseudo-objects in the RHS.
15700 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15701 // An overload in the RHS can potentially be resolved by the type
15702 // being assigned to.
15703 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15704 if (getLangOpts().CPlusPlus &&
15705 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15706 LHSExpr->getType()->isOverloadableType()))
15707 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15708
15709 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
15710 ForFoldExpression);
15711 }
15712
15713 // Don't resolve overloads if the other type is overloadable.
15714 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15715 LHSExpr->getType()->isOverloadableType())
15716 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15717
15718 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15719 if (!resolvedRHS.isUsable()) return ExprError();
15720 RHSExpr = resolvedRHS.get();
15721 }
15722
15723 if (getLangOpts().HLSL && (LHSExpr->getType()->isHLSLResourceRecord() ||
15724 LHSExpr->getType()->isHLSLResourceRecordArray())) {
15725 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, OpLoc))
15726 return ExprError();
15727 }
15728
15729 if (getLangOpts().CPlusPlus) {
15730 // Otherwise, build an overloaded op if either expression is type-dependent
15731 // or has an overloadable type.
15732 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15733 LHSExpr->getType()->isOverloadableType() ||
15734 RHSExpr->getType()->isOverloadableType())
15735 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15736 }
15737
15738 if (getLangOpts().RecoveryAST &&
15739 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15740 assert(!getLangOpts().CPlusPlus);
15741 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15742 "Should only occur in error-recovery path.");
15744 // C [6.15.16] p3:
15745 // An assignment expression has the value of the left operand after the
15746 // assignment, but is not an lvalue.
15748 Context, LHSExpr, RHSExpr, Opc,
15750 OpLoc, CurFPFeatureOverrides());
15751 QualType ResultType;
15752 switch (Opc) {
15753 case BO_Assign:
15754 ResultType = LHSExpr->getType().getUnqualifiedType();
15755 break;
15756 case BO_LT:
15757 case BO_GT:
15758 case BO_LE:
15759 case BO_GE:
15760 case BO_EQ:
15761 case BO_NE:
15762 case BO_LAnd:
15763 case BO_LOr:
15764 // These operators have a fixed result type regardless of operands.
15765 ResultType = Context.IntTy;
15766 break;
15767 case BO_Comma:
15768 ResultType = RHSExpr->getType();
15769 break;
15770 default:
15771 ResultType = Context.DependentTy;
15772 break;
15773 }
15774 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15775 VK_PRValue, OK_Ordinary, OpLoc,
15777 }
15778
15779 // Build a built-in binary operation.
15780 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
15781}
15782
15784 if (T.isNull() || T->isDependentType())
15785 return false;
15786
15787 if (!Ctx.isPromotableIntegerType(T))
15788 return true;
15789
15790 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15791}
15792
15794 UnaryOperatorKind Opc, Expr *InputExpr,
15795 bool IsAfterAmp) {
15796 ExprResult Input = InputExpr;
15799 QualType resultType;
15800 bool CanOverflow = false;
15801
15802 bool ConvertHalfVec = false;
15803 if (getLangOpts().OpenCL) {
15804 QualType Ty = InputExpr->getType();
15805 // The only legal unary operation for atomics is '&'.
15806 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15807 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15808 // only with a builtin functions and therefore should be disallowed here.
15809 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15810 || Ty->isBlockPointerType())) {
15811 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15812 << InputExpr->getType()
15813 << Input.get()->getSourceRange());
15814 }
15815 }
15816
15817 if (getLangOpts().HLSL && OpLoc.isValid()) {
15818 if (Opc == UO_AddrOf)
15819 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15820 if (Opc == UO_Deref)
15821 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15822 }
15823
15824 if (InputExpr->isTypeDependent() &&
15825 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
15826 resultType = Context.DependentTy;
15827 } else {
15828 switch (Opc) {
15829 case UO_PreInc:
15830 case UO_PreDec:
15831 case UO_PostInc:
15832 case UO_PostDec:
15833 resultType =
15834 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
15835 Opc == UO_PreInc || Opc == UO_PostInc,
15836 Opc == UO_PreInc || Opc == UO_PreDec);
15837 CanOverflow = isOverflowingIntegerType(Context, resultType);
15838 break;
15839 case UO_AddrOf:
15840 resultType = CheckAddressOfOperand(Input, OpLoc);
15841 CheckAddressOfNoDeref(InputExpr);
15842 RecordModifiableNonNullParam(*this, InputExpr);
15843 break;
15844 case UO_Deref: {
15846 if (Input.isInvalid())
15847 return ExprError();
15848 resultType =
15849 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15850 break;
15851 }
15852 case UO_Plus:
15853 case UO_Minus:
15854 CanOverflow = Opc == UO_Minus &&
15856 Input = UsualUnaryConversions(Input.get());
15857 if (Input.isInvalid())
15858 return ExprError();
15859 // Unary plus and minus require promoting an operand of half vector to a
15860 // float vector and truncating the result back to a half vector. For now,
15861 // we do this only when HalfArgsAndReturns is set (that is, when the
15862 // target is arm or arm64).
15863 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15864
15865 // If the operand is a half vector, promote it to a float vector.
15866 if (ConvertHalfVec)
15867 Input = convertVector(Input.get(), Context.FloatTy, *this);
15868 resultType = Input.get()->getType();
15869 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15870 break;
15871 else if (resultType->isVectorType() &&
15872 // The z vector extensions don't allow + or - with bool vectors.
15873 (!Context.getLangOpts().ZVector ||
15874 resultType->castAs<VectorType>()->getVectorKind() !=
15876 break;
15877 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
15878 break;
15879 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15880 Opc == UO_Plus && resultType->isPointerType())
15881 break;
15882
15883 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15884 << resultType << Input.get()->getSourceRange());
15885
15886 case UO_Not: // bitwise complement
15887 Input = UsualUnaryConversions(Input.get());
15888 if (Input.isInvalid())
15889 return ExprError();
15890 resultType = Input.get()->getType();
15891 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15892 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15893 // C99 does not support '~' for complex conjugation.
15894 Diag(OpLoc, diag::ext_integer_complement_complex)
15895 << resultType << Input.get()->getSourceRange();
15896 else if (resultType->hasIntegerRepresentation())
15897 break;
15898 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15899 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15900 // on vector float types.
15901 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15902 if (!T->isIntegerType())
15903 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15904 << resultType << Input.get()->getSourceRange());
15905 } else {
15906 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15907 << resultType << Input.get()->getSourceRange());
15908 }
15909 break;
15910
15911 case UO_LNot: // logical negation
15912 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15914 if (Input.isInvalid())
15915 return ExprError();
15916 resultType = Input.get()->getType();
15917
15918 // Though we still have to promote half FP to float...
15919 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15920 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
15921 .get();
15922 resultType = Context.FloatTy;
15923 }
15924
15925 // WebAsembly tables can't be used in unary expressions.
15926 if (resultType->isPointerType() &&
15928 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15929 << resultType << Input.get()->getSourceRange());
15930 }
15931
15932 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15933 // C99 6.5.3.3p1: ok, fallthrough;
15934 if (Context.getLangOpts().CPlusPlus) {
15935 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15936 // operand contextually converted to bool.
15937 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15938 ScalarTypeToBooleanCastKind(resultType));
15939 } else if (Context.getLangOpts().OpenCL &&
15940 Context.getLangOpts().OpenCLVersion < 120) {
15941 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15942 // operate on scalar float types.
15943 if (!resultType->isIntegerType() && !resultType->isPointerType())
15944 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15945 << resultType << Input.get()->getSourceRange());
15946 }
15947 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
15948 !resultType->hasBooleanRepresentation()) {
15949 // HLSL unary logical 'not' behaves like C++, which states that the
15950 // operand is converted to bool and the result is bool, however HLSL
15951 // extends this property to vectors.
15952 const VectorType *VTy = resultType->castAs<VectorType>();
15953 resultType =
15954 Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
15955
15956 Input = ImpCastExprToType(
15957 Input.get(), resultType,
15959 .get();
15960 break;
15961 } else if (resultType->isExtVectorType()) {
15962 if (Context.getLangOpts().OpenCL &&
15963 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15964 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15965 // operate on vector float types.
15966 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15967 if (!T->isIntegerType())
15968 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15969 << resultType << Input.get()->getSourceRange());
15970 }
15971 // Vector logical not returns the signed variant of the operand type.
15972 resultType = GetSignedVectorType(resultType);
15973 break;
15974 } else if (Context.getLangOpts().CPlusPlus &&
15975 resultType->isVectorType()) {
15976 const VectorType *VTy = resultType->castAs<VectorType>();
15977 if (VTy->getVectorKind() != VectorKind::Generic)
15978 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15979 << resultType << Input.get()->getSourceRange());
15980
15981 // Vector logical not returns the signed variant of the operand type.
15982 resultType = GetSignedVectorType(resultType);
15983 break;
15984 } else {
15985 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15986 << resultType << Input.get()->getSourceRange());
15987 }
15988
15989 // LNot always has type int. C99 6.5.3.3p5.
15990 // In C++, it's bool. C++ 5.3.1p8
15991 resultType = Context.getLogicalOperationType();
15992 break;
15993 case UO_Real:
15994 case UO_Imag:
15995 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15996 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
15997 // ordinary complex l-values to ordinary l-values and all other values to
15998 // r-values.
15999 if (Input.isInvalid())
16000 return ExprError();
16001 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16002 if (Input.get()->isGLValue() &&
16003 Input.get()->getObjectKind() == OK_Ordinary)
16004 VK = Input.get()->getValueKind();
16005 } else if (!getLangOpts().CPlusPlus) {
16006 // In C, a volatile scalar is read by __imag. In C++, it is not.
16007 Input = DefaultLvalueConversion(Input.get());
16008 }
16009 break;
16010 case UO_Extension:
16011 resultType = Input.get()->getType();
16012 VK = Input.get()->getValueKind();
16013 OK = Input.get()->getObjectKind();
16014 break;
16015 case UO_Coawait:
16016 // It's unnecessary to represent the pass-through operator co_await in the
16017 // AST; just return the input expression instead.
16018 assert(!Input.get()->getType()->isDependentType() &&
16019 "the co_await expression must be non-dependant before "
16020 "building operator co_await");
16021 return Input;
16022 }
16023 }
16024 if (resultType.isNull() || Input.isInvalid())
16025 return ExprError();
16026
16027 // Check for array bounds violations in the operand of the UnaryOperator,
16028 // except for the '*' and '&' operators that have to be handled specially
16029 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16030 // that are explicitly defined as valid by the standard).
16031 if (Opc != UO_AddrOf && Opc != UO_Deref)
16032 CheckArrayAccess(Input.get());
16033
16034 auto *UO =
16035 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16036 OpLoc, CanOverflow, CurFPFeatureOverrides());
16037
16038 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16039 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16041 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16042
16043 // Convert the result back to a half vector.
16044 if (ConvertHalfVec)
16045 return convertVector(UO, Context.HalfTy, *this);
16046 return UO;
16047}
16048
16050 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16051 if (!DRE->getQualifier())
16052 return false;
16053
16054 ValueDecl *VD = DRE->getDecl();
16055 if (!VD->isCXXClassMember())
16056 return false;
16057
16059 return true;
16060 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16061 return Method->isImplicitObjectMemberFunction();
16062
16063 return false;
16064 }
16065
16066 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16067 if (!ULE->getQualifier())
16068 return false;
16069
16070 for (NamedDecl *D : ULE->decls()) {
16071 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16072 if (Method->isImplicitObjectMemberFunction())
16073 return true;
16074 } else {
16075 // Overload set does not contain methods.
16076 break;
16077 }
16078 }
16079
16080 return false;
16081 }
16082
16083 return false;
16084}
16085
16087 UnaryOperatorKind Opc, Expr *Input,
16088 bool IsAfterAmp) {
16089 // First things first: handle placeholders so that the
16090 // overloaded-operator check considers the right type.
16091 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16092 // Increment and decrement of pseudo-object references.
16093 if (pty->getKind() == BuiltinType::PseudoObject &&
16095 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
16096
16097 // extension is always a builtin operator.
16098 if (Opc == UO_Extension)
16099 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16100
16101 // & gets special logic for several kinds of placeholder.
16102 // The builtin code knows what to do.
16103 if (Opc == UO_AddrOf &&
16104 (pty->getKind() == BuiltinType::Overload ||
16105 pty->getKind() == BuiltinType::UnknownAny ||
16106 pty->getKind() == BuiltinType::BoundMember))
16107 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16108
16109 // Anything else needs to be handled now.
16111 if (Result.isInvalid()) return ExprError();
16112 Input = Result.get();
16113 }
16114
16115 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16117 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16118 // Find all of the overloaded operators visible from this point.
16119 UnresolvedSet<16> Functions;
16121 if (S && OverOp != OO_None)
16122 LookupOverloadedOperatorName(OverOp, S, Functions);
16123
16124 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16125 }
16126
16127 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16128}
16129
16131 Expr *Input, bool IsAfterAmp) {
16132 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16133 IsAfterAmp);
16134}
16135
16137 LabelDecl *TheDecl) {
16138 TheDecl->markUsed(Context);
16139 // Create the AST node. The address of a label always has type 'void*'.
16140 auto *Res = new (Context) AddrLabelExpr(
16141 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16142
16143 if (getCurFunction())
16144 getCurFunction()->AddrLabels.push_back(Res);
16145
16146 return Res;
16147}
16148
16151 // Make sure we diagnose jumping into a statement expression.
16153}
16154
16156 // Note that function is also called by TreeTransform when leaving a
16157 // StmtExpr scope without rebuilding anything.
16158
16161}
16162
16164 SourceLocation RPLoc) {
16165 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16166}
16167
16169 SourceLocation RPLoc, unsigned TemplateDepth) {
16170 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16171 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16172
16175 assert(!Cleanup.exprNeedsCleanups() &&
16176 "cleanups within StmtExpr not correctly bound!");
16178
16179 // FIXME: there are a variety of strange constraints to enforce here, for
16180 // example, it is not possible to goto into a stmt expression apparently.
16181 // More semantic analysis is needed.
16182
16183 // If there are sub-stmts in the compound stmt, take the type of the last one
16184 // as the type of the stmtexpr.
16185 QualType Ty = Context.VoidTy;
16186 bool StmtExprMayBindToTemp = false;
16187 if (!Compound->body_empty()) {
16188 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
16189 if (const auto *LastStmt =
16190 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
16191 if (const Expr *Value = LastStmt->getExprStmt()) {
16192 StmtExprMayBindToTemp = true;
16193 Ty = Value->getType();
16194 }
16195 }
16196 }
16197
16198 // FIXME: Check that expression type is complete/non-abstract; statement
16199 // expressions are not lvalues.
16200 Expr *ResStmtExpr =
16201 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16202 if (StmtExprMayBindToTemp)
16203 return MaybeBindToTemporary(ResStmtExpr);
16204 return ResStmtExpr;
16205}
16206
16208 if (ER.isInvalid())
16209 return ExprError();
16210
16211 // Do function/array conversion on the last expression, but not
16212 // lvalue-to-rvalue. However, initialize an unqualified type.
16214 if (ER.isInvalid())
16215 return ExprError();
16216 Expr *E = ER.get();
16217
16218 if (E->isTypeDependent())
16219 return E;
16220
16221 // In ARC, if the final expression ends in a consume, splice
16222 // the consume out and bind it later. In the alternate case
16223 // (when dealing with a retainable type), the result
16224 // initialization will create a produce. In both cases the
16225 // result will be +1, and we'll need to balance that out with
16226 // a bind.
16227 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16228 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16229 return Cast->getSubExpr();
16230
16231 // FIXME: Provide a better location for the initialization.
16235 SourceLocation(), E);
16236}
16237
16239 TypeSourceInfo *TInfo,
16240 ArrayRef<OffsetOfComponent> Components,
16241 SourceLocation RParenLoc) {
16242 QualType ArgTy = TInfo->getType();
16243 bool Dependent = ArgTy->isDependentType();
16244 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16245
16246 // We must have at least one component that refers to the type, and the first
16247 // one is known to be a field designator. Verify that the ArgTy represents
16248 // a struct/union/class.
16249 if (!Dependent && !ArgTy->isRecordType())
16250 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16251 << ArgTy << TypeRange);
16252
16253 // Type must be complete per C99 7.17p3 because a declaring a variable
16254 // with an incomplete type would be ill-formed.
16255 if (!Dependent
16256 && RequireCompleteType(BuiltinLoc, ArgTy,
16257 diag::err_offsetof_incomplete_type, TypeRange))
16258 return ExprError();
16259
16260 bool DidWarnAboutNonPOD = false;
16261 QualType CurrentType = ArgTy;
16264 for (const OffsetOfComponent &OC : Components) {
16265 if (OC.isBrackets) {
16266 // Offset of an array sub-field. TODO: Should we allow vector elements?
16267 if (!CurrentType->isDependentType()) {
16268 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16269 if(!AT)
16270 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16271 << CurrentType);
16272 CurrentType = AT->getElementType();
16273 } else
16274 CurrentType = Context.DependentTy;
16275
16276 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16277 if (IdxRval.isInvalid())
16278 return ExprError();
16279 Expr *Idx = IdxRval.get();
16280
16281 // The expression must be an integral expression.
16282 // FIXME: An integral constant expression?
16283 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16284 !Idx->getType()->isIntegerType())
16285 return ExprError(
16286 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16287 << Idx->getSourceRange());
16288
16289 // Record this array index.
16290 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16291 Exprs.push_back(Idx);
16292 continue;
16293 }
16294
16295 // Offset of a field.
16296 if (CurrentType->isDependentType()) {
16297 // We have the offset of a field, but we can't look into the dependent
16298 // type. Just record the identifier of the field.
16299 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16300 CurrentType = Context.DependentTy;
16301 continue;
16302 }
16303
16304 // We need to have a complete type to look into.
16305 if (RequireCompleteType(OC.LocStart, CurrentType,
16306 diag::err_offsetof_incomplete_type))
16307 return ExprError();
16308
16309 // Look for the designated field.
16310 auto *RD = CurrentType->getAsRecordDecl();
16311 if (!RD)
16312 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16313 << CurrentType);
16314
16315 // C++ [lib.support.types]p5:
16316 // The macro offsetof accepts a restricted set of type arguments in this
16317 // International Standard. type shall be a POD structure or a POD union
16318 // (clause 9).
16319 // C++11 [support.types]p4:
16320 // If type is not a standard-layout class (Clause 9), the results are
16321 // undefined.
16322 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16323 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16324 unsigned DiagID =
16325 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16326 : diag::ext_offsetof_non_pod_type;
16327
16328 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16329 Diag(BuiltinLoc, DiagID)
16330 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16331 DidWarnAboutNonPOD = true;
16332 }
16333 }
16334
16335 // Look for the field.
16336 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16337 LookupQualifiedName(R, RD);
16338 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16339 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16340 if (!MemberDecl) {
16341 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16342 MemberDecl = IndirectMemberDecl->getAnonField();
16343 }
16344
16345 if (!MemberDecl) {
16346 // Lookup could be ambiguous when looking up a placeholder variable
16347 // __builtin_offsetof(S, _).
16348 // In that case we would already have emitted a diagnostic
16349 if (!R.isAmbiguous())
16350 Diag(BuiltinLoc, diag::err_no_member)
16351 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16352 return ExprError();
16353 }
16354
16355 // C99 7.17p3:
16356 // (If the specified member is a bit-field, the behavior is undefined.)
16357 //
16358 // We diagnose this as an error.
16359 if (MemberDecl->isBitField()) {
16360 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16361 << MemberDecl->getDeclName()
16362 << SourceRange(BuiltinLoc, RParenLoc);
16363 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16364 return ExprError();
16365 }
16366
16367 RecordDecl *Parent = MemberDecl->getParent();
16368 if (IndirectMemberDecl)
16369 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16370
16371 // If the member was found in a base class, introduce OffsetOfNodes for
16372 // the base class indirections.
16373 CXXBasePaths Paths;
16374 if (IsDerivedFrom(OC.LocStart, CurrentType,
16375 Context.getCanonicalTagType(Parent), Paths)) {
16376 if (Paths.getDetectedVirtual()) {
16377 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16378 << MemberDecl->getDeclName()
16379 << SourceRange(BuiltinLoc, RParenLoc);
16380 return ExprError();
16381 }
16382
16383 CXXBasePath &Path = Paths.front();
16384 for (const CXXBasePathElement &B : Path)
16385 Comps.push_back(OffsetOfNode(B.Base));
16386 }
16387
16388 if (IndirectMemberDecl) {
16389 for (auto *FI : IndirectMemberDecl->chain()) {
16390 assert(isa<FieldDecl>(FI));
16391 Comps.push_back(OffsetOfNode(OC.LocStart,
16392 cast<FieldDecl>(FI), OC.LocEnd));
16393 }
16394 } else
16395 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16396
16397 CurrentType = MemberDecl->getType().getNonReferenceType();
16398 }
16399
16400 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16401 Comps, Exprs, RParenLoc);
16402}
16403
16405 SourceLocation BuiltinLoc,
16407 ParsedType ParsedArgTy,
16408 ArrayRef<OffsetOfComponent> Components,
16409 SourceLocation RParenLoc) {
16410
16411 TypeSourceInfo *ArgTInfo;
16412 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16413 if (ArgTy.isNull())
16414 return ExprError();
16415
16416 if (!ArgTInfo)
16417 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16418
16419 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16420}
16421
16422
16424 Expr *CondExpr,
16425 Expr *LHSExpr, Expr *RHSExpr,
16426 SourceLocation RPLoc) {
16427 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16428
16431 QualType resType;
16432 bool CondIsTrue = false;
16433 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16434 resType = Context.DependentTy;
16435 } else {
16436 // The conditional expression is required to be a constant expression.
16437 llvm::APSInt condEval(32);
16439 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16440 if (CondICE.isInvalid())
16441 return ExprError();
16442 CondExpr = CondICE.get();
16443 CondIsTrue = condEval.getZExtValue();
16444
16445 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16446 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16447
16448 resType = ActiveExpr->getType();
16449 VK = ActiveExpr->getValueKind();
16450 OK = ActiveExpr->getObjectKind();
16451 }
16452
16453 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16454 resType, VK, OK, RPLoc, CondIsTrue);
16455}
16456
16457//===----------------------------------------------------------------------===//
16458// Clang Extensions.
16459//===----------------------------------------------------------------------===//
16460
16461void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16463
16464 if (LangOpts.CPlusPlus) {
16466 Decl *ManglingContextDecl;
16467 std::tie(MCtx, ManglingContextDecl) =
16468 getCurrentMangleNumberContext(Block->getDeclContext());
16469 if (MCtx) {
16470 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16471 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16472 }
16473 }
16474
16475 PushBlockScope(CurScope, Block);
16476 CurContext->addDecl(Block);
16477 if (CurScope)
16478 PushDeclContext(CurScope, Block);
16479 else
16480 CurContext = Block;
16481
16483
16484 // Enter a new evaluation context to insulate the block from any
16485 // cleanups from the enclosing full-expression.
16488}
16489
16491 Scope *CurScope) {
16492 assert(ParamInfo.getIdentifier() == nullptr &&
16493 "block-id should have no identifier!");
16494 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16495 BlockScopeInfo *CurBlock = getCurBlock();
16496
16497 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16498 QualType T = Sig->getType();
16500
16501 // GetTypeForDeclarator always produces a function type for a block
16502 // literal signature. Furthermore, it is always a FunctionProtoType
16503 // unless the function was written with a typedef.
16504 assert(T->isFunctionType() &&
16505 "GetTypeForDeclarator made a non-function block signature");
16506
16507 // Look for an explicit signature in that function type.
16508 FunctionProtoTypeLoc ExplicitSignature;
16509
16510 if ((ExplicitSignature = Sig->getTypeLoc()
16512
16513 // Check whether that explicit signature was synthesized by
16514 // GetTypeForDeclarator. If so, don't save that as part of the
16515 // written signature.
16516 if (ExplicitSignature.getLocalRangeBegin() ==
16517 ExplicitSignature.getLocalRangeEnd()) {
16518 // This would be much cheaper if we stored TypeLocs instead of
16519 // TypeSourceInfos.
16520 TypeLoc Result = ExplicitSignature.getReturnLoc();
16521 unsigned Size = Result.getFullDataSize();
16522 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16523 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16524
16525 ExplicitSignature = FunctionProtoTypeLoc();
16526 }
16527 }
16528
16529 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16530 CurBlock->FunctionType = T;
16531
16532 const auto *Fn = T->castAs<FunctionType>();
16533 QualType RetTy = Fn->getReturnType();
16534 bool isVariadic =
16535 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16536
16537 CurBlock->TheDecl->setIsVariadic(isVariadic);
16538
16539 // Context.DependentTy is used as a placeholder for a missing block
16540 // return type. TODO: what should we do with declarators like:
16541 // ^ * { ... }
16542 // If the answer is "apply template argument deduction"....
16543 if (RetTy != Context.DependentTy) {
16544 CurBlock->ReturnType = RetTy;
16545 CurBlock->TheDecl->setBlockMissingReturnType(false);
16546 CurBlock->HasImplicitReturnType = false;
16547 }
16548
16549 // Push block parameters from the declarator if we had them.
16551 if (ExplicitSignature) {
16552 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16553 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16554 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16555 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16556 // Diagnose this as an extension in C17 and earlier.
16557 if (!getLangOpts().C23)
16558 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16559 }
16560 Params.push_back(Param);
16561 }
16562
16563 // Fake up parameter variables if we have a typedef, like
16564 // ^ fntype { ... }
16565 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16566 for (const auto &I : Fn->param_types()) {
16568 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16569 Params.push_back(Param);
16570 }
16571 }
16572
16573 // Set the parameters on the block decl.
16574 if (!Params.empty()) {
16575 CurBlock->TheDecl->setParams(Params);
16577 /*CheckParameterNames=*/false);
16578 }
16579
16580 // Finally we can process decl attributes.
16581 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16582
16583 // Put the parameter variables in scope.
16584 for (auto *AI : CurBlock->TheDecl->parameters()) {
16585 AI->setOwningFunction(CurBlock->TheDecl);
16586
16587 // If this has an identifier, add it to the scope stack.
16588 if (AI->getIdentifier()) {
16589 CheckShadow(CurBlock->TheScope, AI);
16590
16591 PushOnScopeChains(AI, CurBlock->TheScope);
16592 }
16593
16594 if (AI->isInvalidDecl())
16595 CurBlock->TheDecl->setInvalidDecl();
16596 }
16597}
16598
16599void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16600 // Leave the expression-evaluation context.
16603
16604 // Pop off CurBlock, handle nested blocks.
16607}
16608
16610 Stmt *Body, Scope *CurScope) {
16611 // If blocks are disabled, emit an error.
16612 if (!LangOpts.Blocks)
16613 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16614
16615 // Leave the expression-evaluation context.
16618 assert(!Cleanup.exprNeedsCleanups() &&
16619 "cleanups within block not correctly bound!");
16621
16623 BlockDecl *BD = BSI->TheDecl;
16624
16626
16627 if (BSI->HasImplicitReturnType)
16629
16630 QualType RetTy = Context.VoidTy;
16631 if (!BSI->ReturnType.isNull())
16632 RetTy = BSI->ReturnType;
16633
16634 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16635 QualType BlockTy;
16636
16637 // If the user wrote a function type in some form, try to use that.
16638 if (!BSI->FunctionType.isNull()) {
16639 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16640
16641 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16642 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16643
16644 // Turn protoless block types into nullary block types.
16645 if (isa<FunctionNoProtoType>(FTy)) {
16647 EPI.ExtInfo = Ext;
16648 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16649
16650 // Otherwise, if we don't need to change anything about the function type,
16651 // preserve its sugar structure.
16652 } else if (FTy->getReturnType() == RetTy &&
16653 (!NoReturn || FTy->getNoReturnAttr())) {
16654 BlockTy = BSI->FunctionType;
16655
16656 // Otherwise, make the minimal modifications to the function type.
16657 } else {
16660 EPI.TypeQuals = Qualifiers();
16661 EPI.ExtInfo = Ext;
16662 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16663 }
16664
16665 // If we don't have a function type, just build one from nothing.
16666 } else {
16668 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16669 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16670 }
16671
16673 BlockTy = Context.getBlockPointerType(BlockTy);
16674
16675 // If needed, diagnose invalid gotos and switches in the block.
16676 if (getCurFunction()->NeedsScopeChecking() &&
16677 !PP.isCodeCompletionEnabled())
16679
16680 BD->setBody(cast<CompoundStmt>(Body));
16681
16682 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16684
16685 // Try to apply the named return value optimization. We have to check again
16686 // if we can do this, though, because blocks keep return statements around
16687 // to deduce an implicit return type.
16688 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16689 !BD->isDependentContext())
16690 computeNRVO(Body, BSI);
16691
16697
16699
16700 // Set the captured variables on the block.
16702 for (Capture &Cap : BSI->Captures) {
16703 if (Cap.isInvalid() || Cap.isThisCapture())
16704 continue;
16705 // Cap.getVariable() is always a VarDecl because
16706 // blocks cannot capture structured bindings or other ValueDecl kinds.
16707 auto *Var = cast<VarDecl>(Cap.getVariable());
16708 Expr *CopyExpr = nullptr;
16709 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16710 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
16711 // The capture logic needs the destructor, so make sure we mark it.
16712 // Usually this is unnecessary because most local variables have
16713 // their destructors marked at declaration time, but parameters are
16714 // an exception because it's technically only the call site that
16715 // actually requires the destructor.
16716 if (isa<ParmVarDecl>(Var))
16718
16719 // Enter a separate potentially-evaluated context while building block
16720 // initializers to isolate their cleanups from those of the block
16721 // itself.
16722 // FIXME: Is this appropriate even when the block itself occurs in an
16723 // unevaluated operand?
16726
16727 SourceLocation Loc = Cap.getLocation();
16728
16730 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16731
16732 // According to the blocks spec, the capture of a variable from
16733 // the stack requires a const copy constructor. This is not true
16734 // of the copy/move done to move a __block variable to the heap.
16735 if (!Result.isInvalid() &&
16736 !Result.get()->getType().isConstQualified()) {
16738 Result.get()->getType().withConst(),
16739 CK_NoOp, VK_LValue);
16740 }
16741
16742 if (!Result.isInvalid()) {
16744 InitializedEntity::InitializeBlock(Var->getLocation(),
16745 Cap.getCaptureType()),
16746 Loc, Result.get());
16747 }
16748
16749 // Build a full-expression copy expression if initialization
16750 // succeeded and used a non-trivial constructor. Recover from
16751 // errors by pretending that the copy isn't necessary.
16752 if (!Result.isInvalid() &&
16753 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16754 ->isTrivial()) {
16756 CopyExpr = Result.get();
16757 }
16758 }
16759 }
16760
16761 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16762 CopyExpr);
16763 Captures.push_back(NewCap);
16764 }
16765 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16766
16767 // Pop the block scope now but keep it alive to the end of this function.
16769 AnalysisWarnings.getPolicyInEffectAt(Body->getEndLoc());
16770 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16771
16772 BlockExpr *Result = new (Context)
16773 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
16774
16775 // If the block isn't obviously global, i.e. it captures anything at
16776 // all, then we need to do a few things in the surrounding context:
16777 if (Result->getBlockDecl()->hasCaptures()) {
16778 // First, this expression has a new cleanup object.
16779 ExprCleanupObjects.push_back(Result->getBlockDecl());
16780 Cleanup.setExprNeedsCleanups(true);
16781
16782 // It also gets a branch-protected scope if any of the captured
16783 // variables needs destruction.
16784 for (const auto &CI : Result->getBlockDecl()->captures()) {
16785 const VarDecl *var = CI.getVariable();
16786 if (var->getType().isDestructedType() != QualType::DK_none) {
16788 break;
16789 }
16790 }
16791 }
16792
16793 if (getCurFunction())
16794 getCurFunction()->addBlock(BD);
16795
16796 // This can happen if the block's return type is deduced, but
16797 // the return expression is invalid.
16798 if (BD->isInvalidDecl())
16799 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16800 {Result}, Result->getType());
16801 return Result;
16802}
16803
16805 SourceLocation RPLoc) {
16806 TypeSourceInfo *TInfo;
16807 GetTypeFromParser(Ty, &TInfo);
16808 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16809}
16810
16812 Expr *E, TypeSourceInfo *TInfo,
16813 SourceLocation RPLoc) {
16814 Expr *OrigExpr = E;
16815 bool IsMS = false;
16816
16817 // CUDA device global function does not support varargs.
16818 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16819 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16822 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16823 }
16824 }
16825
16826 // NVPTX does not support va_arg expression.
16827 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16828 Context.getTargetInfo().getTriple().isNVPTX())
16829 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16830
16831 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16832 // as Microsoft ABI on an actual Microsoft platform, where
16833 // __builtin_ms_va_list and __builtin_va_list are the same.)
16834 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16835 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16836 QualType MSVaListType = Context.getBuiltinMSVaListType();
16837 if (Context.hasSameType(MSVaListType, E->getType())) {
16838 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16839 return ExprError();
16840 IsMS = true;
16841 }
16842 }
16843
16844 // Get the va_list type
16845 QualType VaListType = Context.getBuiltinVaListType();
16846 if (!IsMS) {
16847 if (VaListType->isArrayType()) {
16848 // Deal with implicit array decay; for example, on x86-64,
16849 // va_list is an array, but it's supposed to decay to
16850 // a pointer for va_arg.
16851 VaListType = Context.getArrayDecayedType(VaListType);
16852 // Make sure the input expression also decays appropriately.
16854 if (Result.isInvalid())
16855 return ExprError();
16856 E = Result.get();
16857 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16858 // If va_list is a record type and we are compiling in C++ mode,
16859 // check the argument using reference binding.
16861 Context, Context.getLValueReferenceType(VaListType), false);
16863 if (Init.isInvalid())
16864 return ExprError();
16865 E = Init.getAs<Expr>();
16866 } else {
16867 // Otherwise, the va_list argument must be an l-value because
16868 // it is modified by va_arg.
16869 if (!E->isTypeDependent() &&
16870 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16871 return ExprError();
16872 }
16873 }
16874
16875 if (!IsMS && !E->isTypeDependent() &&
16876 !Context.hasSameType(VaListType, E->getType()))
16877 return ExprError(
16878 Diag(E->getBeginLoc(),
16879 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16880 << OrigExpr->getType() << E->getSourceRange());
16881
16882 if (!TInfo->getType()->isDependentType()) {
16883 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16884 diag::err_second_parameter_to_va_arg_incomplete,
16885 TInfo->getTypeLoc()))
16886 return ExprError();
16887
16889 TInfo->getType(),
16890 diag::err_second_parameter_to_va_arg_abstract,
16891 TInfo->getTypeLoc()))
16892 return ExprError();
16893
16894 if (!TInfo->getType().isPODType(Context)) {
16895 Diag(TInfo->getTypeLoc().getBeginLoc(),
16896 TInfo->getType()->isObjCLifetimeType()
16897 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16898 : diag::warn_second_parameter_to_va_arg_not_pod)
16899 << TInfo->getType()
16900 << TInfo->getTypeLoc().getSourceRange();
16901 }
16902
16903 if (TInfo->getType()->isArrayType()) {
16905 PDiag(diag::warn_second_parameter_to_va_arg_array)
16906 << TInfo->getType()
16907 << TInfo->getTypeLoc().getSourceRange());
16908 }
16909
16910 // Check for va_arg where arguments of the given type will be promoted
16911 // (i.e. this va_arg is guaranteed to have undefined behavior).
16912 QualType PromoteType;
16913 if (Context.isPromotableIntegerType(TInfo->getType())) {
16914 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16915 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16916 // and C23 7.16.1.1p2 says, in part:
16917 // If type is not compatible with the type of the actual next argument
16918 // (as promoted according to the default argument promotions), the
16919 // behavior is undefined, except for the following cases:
16920 // - both types are pointers to qualified or unqualified versions of
16921 // compatible types;
16922 // - one type is compatible with a signed integer type, the other
16923 // type is compatible with the corresponding unsigned integer type,
16924 // and the value is representable in both types;
16925 // - one type is pointer to qualified or unqualified void and the
16926 // other is a pointer to a qualified or unqualified character type;
16927 // - or, the type of the next argument is nullptr_t and type is a
16928 // pointer type that has the same representation and alignment
16929 // requirements as a pointer to a character type.
16930 // Given that type compatibility is the primary requirement (ignoring
16931 // qualifications), you would think we could call typesAreCompatible()
16932 // directly to test this. However, in C++, that checks for *same type*,
16933 // which causes false positives when passing an enumeration type to
16934 // va_arg. Instead, get the underlying type of the enumeration and pass
16935 // that.
16936 QualType UnderlyingType = TInfo->getType();
16937 if (const auto *ED = UnderlyingType->getAsEnumDecl())
16938 UnderlyingType = ED->getIntegerType();
16939 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16940 /*CompareUnqualified*/ true))
16941 PromoteType = QualType();
16942
16943 // If the types are still not compatible, we need to test whether the
16944 // promoted type and the underlying type are the same except for
16945 // signedness. Ask the AST for the correctly corresponding type and see
16946 // if that's compatible.
16947 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16948 PromoteType->isUnsignedIntegerType() !=
16949 UnderlyingType->isUnsignedIntegerType()) {
16950 UnderlyingType =
16951 UnderlyingType->isUnsignedIntegerType()
16952 ? Context.getCorrespondingSignedType(UnderlyingType)
16953 : Context.getCorrespondingUnsignedType(UnderlyingType);
16954 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16955 /*CompareUnqualified*/ true))
16956 PromoteType = QualType();
16957 }
16958 }
16959 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16960 PromoteType = Context.DoubleTy;
16961 if (!PromoteType.isNull())
16963 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16964 << TInfo->getType()
16965 << PromoteType
16966 << TInfo->getTypeLoc().getSourceRange());
16967 }
16968
16970 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16971}
16972
16974 // The type of __null will be int or long, depending on the size of
16975 // pointers on the target.
16976 QualType Ty;
16977 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
16978 if (pw == Context.getTargetInfo().getIntWidth())
16979 Ty = Context.IntTy;
16980 else if (pw == Context.getTargetInfo().getLongWidth())
16981 Ty = Context.LongTy;
16982 else if (pw == Context.getTargetInfo().getLongLongWidth())
16983 Ty = Context.LongLongTy;
16984 else {
16985 llvm_unreachable("I don't know size of pointer!");
16986 }
16987
16988 return new (Context) GNUNullExpr(Ty, TokenLoc);
16989}
16990
16992 CXXRecordDecl *ImplDecl = nullptr;
16993
16994 // Fetch the std::source_location::__impl decl.
16995 if (NamespaceDecl *Std = S.getStdNamespace()) {
16996 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16998 if (S.LookupQualifiedName(ResultSL, Std)) {
16999 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17000 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17002 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17003 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17004 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17005 }
17006 }
17007 }
17008 }
17009
17010 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17011 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17012 return nullptr;
17013 }
17014
17015 // Verify that __impl is a trivial struct type, with no base classes, and with
17016 // only the four expected fields.
17017 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17018 ImplDecl->getNumBases() != 0) {
17019 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17020 return nullptr;
17021 }
17022
17023 unsigned Count = 0;
17024 for (FieldDecl *F : ImplDecl->fields()) {
17025 StringRef Name = F->getName();
17026
17027 if (Name == "_M_file_name") {
17028 if (F->getType() !=
17030 break;
17031 Count++;
17032 } else if (Name == "_M_function_name") {
17033 if (F->getType() !=
17035 break;
17036 Count++;
17037 } else if (Name == "_M_line") {
17038 if (!F->getType()->isIntegerType())
17039 break;
17040 Count++;
17041 } else if (Name == "_M_column") {
17042 if (!F->getType()->isIntegerType())
17043 break;
17044 Count++;
17045 } else {
17046 Count = 100; // invalid
17047 break;
17048 }
17049 }
17050 if (Count != 4) {
17051 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17052 return nullptr;
17053 }
17054
17055 return ImplDecl;
17056}
17057
17059 SourceLocation BuiltinLoc,
17060 SourceLocation RPLoc) {
17061 QualType ResultTy;
17062 switch (Kind) {
17067 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17068 ResultTy =
17069 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17070 break;
17071 }
17074 ResultTy = Context.UnsignedIntTy;
17075 break;
17079 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17081 return ExprError();
17082 }
17083 ResultTy = Context.getPointerType(
17084 Context.getCanonicalTagType(StdSourceLocationImplDecl).withConst());
17085 break;
17086 }
17087
17088 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17089}
17090
17092 SourceLocation BuiltinLoc,
17093 SourceLocation RPLoc,
17094 DeclContext *ParentContext) {
17095 return new (Context)
17096 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17097}
17098
17100 StringLiteral *BinaryData, StringRef FileName) {
17102 Data->BinaryData = BinaryData;
17103 Data->FileName = FileName;
17104 return new (Context)
17105 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17106 Data->getDataElementCount());
17107}
17108
17110 const Expr *SrcExpr) {
17111 if (!DstType->isFunctionPointerType() ||
17112 !SrcExpr->getType()->isFunctionType())
17113 return false;
17114
17115 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17116 if (!DRE)
17117 return false;
17118
17119 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17120 if (!FD)
17121 return false;
17122
17124 /*Complain=*/true,
17125 SrcExpr->getBeginLoc());
17126}
17127
17129 SourceLocation Loc,
17130 QualType DstType, QualType SrcType,
17131 Expr *SrcExpr, AssignmentAction Action,
17132 bool *Complained) {
17133 if (Complained)
17134 *Complained = false;
17135
17136 // Decode the result (notice that AST's are still created for extensions).
17137 bool CheckInferredResultType = false;
17138 bool isInvalid = false;
17139 unsigned DiagKind = 0;
17140 ConversionFixItGenerator ConvHints;
17141 bool MayHaveConvFixit = false;
17142 bool MayHaveFunctionDiff = false;
17143 const ObjCInterfaceDecl *IFace = nullptr;
17144 const ObjCProtocolDecl *PDecl = nullptr;
17145
17146 switch (ConvTy) {
17148 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17149 return false;
17151 // Still a valid conversion, but we may want to diagnose for C++
17152 // compatibility reasons.
17153 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17154 break;
17156 if (getLangOpts().CPlusPlus) {
17157 DiagKind = diag::err_typecheck_convert_pointer_int;
17158 isInvalid = true;
17159 } else {
17160 DiagKind = diag::ext_typecheck_convert_pointer_int;
17161 }
17162 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17163 MayHaveConvFixit = true;
17164 break;
17166 if (getLangOpts().CPlusPlus) {
17167 DiagKind = diag::err_typecheck_convert_int_pointer;
17168 isInvalid = true;
17169 } else {
17170 DiagKind = diag::ext_typecheck_convert_int_pointer;
17171 }
17172 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17173 MayHaveConvFixit = true;
17174 break;
17176 DiagKind =
17177 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17178 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17179 MayHaveConvFixit = true;
17180 break;
17182 if (getLangOpts().CPlusPlus) {
17183 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17184 isInvalid = true;
17185 } else {
17186 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17187 }
17188 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17189 MayHaveConvFixit = true;
17190 break;
17193 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17194 } else if (getLangOpts().CPlusPlus) {
17195 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17196 isInvalid = true;
17197 } else {
17198 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17199 }
17200 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17201 SrcType->isObjCObjectPointerType();
17202 if (CheckInferredResultType) {
17203 SrcType = SrcType.getUnqualifiedType();
17204 DstType = DstType.getUnqualifiedType();
17205 } else {
17206 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17207 }
17208 MayHaveConvFixit = true;
17209 break;
17211 if (getLangOpts().CPlusPlus) {
17212 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17213 isInvalid = true;
17214 } else {
17215 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17216 }
17217 break;
17219 if (getLangOpts().CPlusPlus) {
17220 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17221 isInvalid = true;
17222 } else {
17223 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17224 }
17225 break;
17227 // Perform array-to-pointer decay if necessary.
17228 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17229
17230 isInvalid = true;
17231
17232 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17233 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17234 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17235 DiagKind = diag::err_typecheck_incompatible_address_space;
17236 break;
17237 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17238 DiagKind = diag::err_typecheck_incompatible_ownership;
17239 break;
17240 } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {
17241 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17242 break;
17243 }
17244
17245 llvm_unreachable("unknown error case for discarding qualifiers!");
17246 // fallthrough
17247 }
17249 // If the qualifiers lost were because we were applying the
17250 // (deprecated) C++ conversion from a string literal to a char*
17251 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17252 // Ideally, this check would be performed in
17253 // checkPointerTypesForAssignment. However, that would require a
17254 // bit of refactoring (so that the second argument is an
17255 // expression, rather than a type), which should be done as part
17256 // of a larger effort to fix checkPointerTypesForAssignment for
17257 // C++ semantics.
17258 if (getLangOpts().CPlusPlus &&
17260 return false;
17261 if (getLangOpts().CPlusPlus) {
17262 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17263 isInvalid = true;
17264 } else {
17265 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17266 }
17267
17268 break;
17270 if (getLangOpts().CPlusPlus) {
17271 isInvalid = true;
17272 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17273 } else {
17274 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17275 }
17276 break;
17278 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17279 isInvalid = true;
17280 break;
17282 DiagKind = diag::err_int_to_block_pointer;
17283 isInvalid = true;
17284 break;
17286 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17287 isInvalid = true;
17288 break;
17290 if (SrcType->isObjCQualifiedIdType()) {
17291 const ObjCObjectPointerType *srcOPT =
17292 SrcType->castAs<ObjCObjectPointerType>();
17293 for (auto *srcProto : srcOPT->quals()) {
17294 PDecl = srcProto;
17295 break;
17296 }
17297 if (const ObjCInterfaceType *IFaceT =
17299 IFace = IFaceT->getDecl();
17300 }
17301 else if (DstType->isObjCQualifiedIdType()) {
17302 const ObjCObjectPointerType *dstOPT =
17303 DstType->castAs<ObjCObjectPointerType>();
17304 for (auto *dstProto : dstOPT->quals()) {
17305 PDecl = dstProto;
17306 break;
17307 }
17308 if (const ObjCInterfaceType *IFaceT =
17310 IFace = IFaceT->getDecl();
17311 }
17312 if (getLangOpts().CPlusPlus) {
17313 DiagKind = diag::err_incompatible_qualified_id;
17314 isInvalid = true;
17315 } else {
17316 DiagKind = diag::warn_incompatible_qualified_id;
17317 }
17318 break;
17319 }
17321 if (getLangOpts().CPlusPlus) {
17322 DiagKind = diag::err_incompatible_vectors;
17323 isInvalid = true;
17324 } else {
17325 DiagKind = diag::warn_incompatible_vectors;
17326 }
17327 break;
17329 DiagKind = diag::err_arc_weak_unavailable_assign;
17330 isInvalid = true;
17331 break;
17333 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17334 if (Complained)
17335 *Complained = true;
17336 return true;
17337 }
17338
17339 DiagKind = diag::err_typecheck_convert_incompatible;
17340 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17341 MayHaveConvFixit = true;
17342 isInvalid = true;
17343 MayHaveFunctionDiff = true;
17344 break;
17345 }
17346
17347 QualType FirstType, SecondType;
17348 switch (Action) {
17351 // The destination type comes first.
17352 FirstType = DstType;
17353 SecondType = SrcType;
17354 break;
17355
17362 // The source type comes first.
17363 FirstType = SrcType;
17364 SecondType = DstType;
17365 break;
17366 }
17367
17368 PartialDiagnostic FDiag = PDiag(DiagKind);
17369 AssignmentAction ActionForDiag = Action;
17371 ActionForDiag = AssignmentAction::Passing;
17372
17373 FDiag << FirstType << SecondType << ActionForDiag
17374 << SrcExpr->getSourceRange();
17375
17376 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17377 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17378 auto isPlainChar = [](const clang::Type *Type) {
17379 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17380 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17381 };
17382 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17383 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17384 }
17385
17386 // If we can fix the conversion, suggest the FixIts.
17387 if (!ConvHints.isNull()) {
17388 for (FixItHint &H : ConvHints.Hints)
17389 FDiag << H;
17390 }
17391
17392 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17393
17394 if (MayHaveFunctionDiff)
17395 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17396
17397 Diag(Loc, FDiag);
17398 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17399 DiagKind == diag::err_incompatible_qualified_id) &&
17400 PDecl && IFace && !IFace->hasDefinition())
17401 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17402 << IFace << PDecl;
17403
17404 if (SecondType == Context.OverloadTy)
17406 FirstType, /*TakingAddress=*/true);
17407
17408 if (CheckInferredResultType)
17410
17411 if (Action == AssignmentAction::Returning &&
17414
17415 if (Complained)
17416 *Complained = true;
17417 return isInvalid;
17418}
17419
17421 llvm::APSInt *Result,
17422 AllowFoldKind CanFold) {
17423 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17424 public:
17425 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17426 QualType T) override {
17427 return S.Diag(Loc, diag::err_ice_not_integral)
17428 << T << S.LangOpts.CPlusPlus;
17429 }
17430 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17431 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17432 }
17433 } Diagnoser;
17434
17435 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17436}
17437
17439 llvm::APSInt *Result,
17440 unsigned DiagID,
17441 AllowFoldKind CanFold) {
17442 class IDDiagnoser : public VerifyICEDiagnoser {
17443 unsigned DiagID;
17444
17445 public:
17446 IDDiagnoser(unsigned DiagID)
17447 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17448
17449 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17450 return S.Diag(Loc, DiagID);
17451 }
17452 } Diagnoser(DiagID);
17453
17454 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17455}
17456
17462
17465 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17466}
17467
17470 VerifyICEDiagnoser &Diagnoser,
17471 AllowFoldKind CanFold) {
17472 SourceLocation DiagLoc = E->getBeginLoc();
17473
17474 if (getLangOpts().CPlusPlus11) {
17475 // C++11 [expr.const]p5:
17476 // If an expression of literal class type is used in a context where an
17477 // integral constant expression is required, then that class type shall
17478 // have a single non-explicit conversion function to an integral or
17479 // unscoped enumeration type
17480 ExprResult Converted;
17481 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17482 VerifyICEDiagnoser &BaseDiagnoser;
17483 public:
17484 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17485 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17486 BaseDiagnoser.Suppress, true),
17487 BaseDiagnoser(BaseDiagnoser) {}
17488
17489 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17490 QualType T) override {
17491 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17492 }
17493
17494 SemaDiagnosticBuilder diagnoseIncomplete(
17495 Sema &S, SourceLocation Loc, QualType T) override {
17496 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17497 }
17498
17499 SemaDiagnosticBuilder diagnoseExplicitConv(
17500 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17501 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17502 }
17503
17504 SemaDiagnosticBuilder noteExplicitConv(
17505 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17506 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17507 << ConvTy->isEnumeralType() << ConvTy;
17508 }
17509
17510 SemaDiagnosticBuilder diagnoseAmbiguous(
17511 Sema &S, SourceLocation Loc, QualType T) override {
17512 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17513 }
17514
17515 SemaDiagnosticBuilder noteAmbiguous(
17516 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17517 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17518 << ConvTy->isEnumeralType() << ConvTy;
17519 }
17520
17521 SemaDiagnosticBuilder diagnoseConversion(
17522 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17523 llvm_unreachable("conversion functions are permitted");
17524 }
17525 } ConvertDiagnoser(Diagnoser);
17526
17527 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17528 ConvertDiagnoser);
17529 if (Converted.isInvalid())
17530 return Converted;
17531 E = Converted.get();
17532 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17533 // don't try to evaluate it later. We also don't want to return the
17534 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17535 // this function will attempt to use 'Value'.
17536 if (isa<RecoveryExpr>(E))
17537 return ExprError();
17539 return ExprError();
17540 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17541 // An ICE must be of integral or unscoped enumeration type.
17542 if (!Diagnoser.Suppress)
17543 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17544 << E->getSourceRange();
17545 return ExprError();
17546 }
17547
17548 ExprResult RValueExpr = DefaultLvalueConversion(E);
17549 if (RValueExpr.isInvalid())
17550 return ExprError();
17551
17552 E = RValueExpr.get();
17553
17554 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17555 // in the non-ICE case.
17558 if (Result)
17560 if (!isa<ConstantExpr>(E))
17563
17564 if (Notes.empty())
17565 return E;
17566
17567 // If our only note is the usual "invalid subexpression" note, just point
17568 // the caret at its location rather than producing an essentially
17569 // redundant note.
17570 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17571 diag::note_invalid_subexpr_in_const_expr) {
17572 DiagLoc = Notes[0].first;
17573 Notes.clear();
17574 }
17575
17576 if (getLangOpts().CPlusPlus) {
17577 if (!Diagnoser.Suppress) {
17578 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17579 for (const PartialDiagnosticAt &Note : Notes)
17580 Diag(Note.first, Note.second);
17581 }
17582 return ExprError();
17583 }
17584
17585 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17586 for (const PartialDiagnosticAt &Note : Notes)
17587 Diag(Note.first, Note.second);
17588
17589 return E;
17590 }
17591
17592 Expr::EvalResult EvalResult;
17594 EvalResult.Diag = &Notes;
17595
17596 // Try to evaluate the expression, and produce diagnostics explaining why it's
17597 // not a constant expression as a side-effect.
17598 bool Folded =
17599 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17600 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17601 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17602
17603 if (!isa<ConstantExpr>(E))
17604 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17605
17606 // In C++11, we can rely on diagnostics being produced for any expression
17607 // which is not a constant expression. If no diagnostics were produced, then
17608 // this is a constant expression.
17609 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17610 if (Result)
17611 *Result = EvalResult.Val.getInt();
17612 return E;
17613 }
17614
17615 // If our only note is the usual "invalid subexpression" note, just point
17616 // the caret at its location rather than producing an essentially
17617 // redundant note.
17618 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17619 diag::note_invalid_subexpr_in_const_expr) {
17620 DiagLoc = Notes[0].first;
17621 Notes.clear();
17622 }
17623
17624 if (!Folded || CanFold == AllowFoldKind::No) {
17625 if (!Diagnoser.Suppress) {
17626 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17627 for (const PartialDiagnosticAt &Note : Notes)
17628 Diag(Note.first, Note.second);
17629 }
17630
17631 return ExprError();
17632 }
17633
17634 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17635 for (const PartialDiagnosticAt &Note : Notes)
17636 Diag(Note.first, Note.second);
17637
17638 if (Result)
17639 *Result = EvalResult.Val.getInt();
17640 return E;
17641}
17642
17643namespace {
17644 // Handle the case where we conclude a expression which we speculatively
17645 // considered to be unevaluated is actually evaluated.
17646 class TransformToPE : public TreeTransform<TransformToPE> {
17647 typedef TreeTransform<TransformToPE> BaseTransform;
17648
17649 public:
17650 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17651
17652 // Make sure we redo semantic analysis
17653 bool AlwaysRebuild() { return true; }
17654 bool ReplacingOriginal() { return true; }
17655
17656 // We need to special-case DeclRefExprs referring to FieldDecls which
17657 // are not part of a member pointer formation; normal TreeTransforming
17658 // doesn't catch this case because of the way we represent them in the AST.
17659 // FIXME: This is a bit ugly; is it really the best way to handle this
17660 // case?
17661 //
17662 // Error on DeclRefExprs referring to FieldDecls.
17663 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17664 if (isa<FieldDecl>(E->getDecl()) &&
17665 !SemaRef.isUnevaluatedContext())
17666 return SemaRef.Diag(E->getLocation(),
17667 diag::err_invalid_non_static_member_use)
17668 << E->getDecl() << E->getSourceRange();
17669
17670 return BaseTransform::TransformDeclRefExpr(E);
17671 }
17672
17673 // Exception: filter out member pointer formation
17674 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17675 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17676 return E;
17677
17678 return BaseTransform::TransformUnaryOperator(E);
17679 }
17680
17681 // The body of a lambda-expression is in a separate expression evaluation
17682 // context so never needs to be transformed.
17683 // FIXME: Ideally we wouldn't transform the closure type either, and would
17684 // just recreate the capture expressions and lambda expression.
17685 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17686 return SkipLambdaBody(E, Body);
17687 }
17688 };
17689}
17690
17692 assert(isUnevaluatedContext() &&
17693 "Should only transform unevaluated expressions");
17694 ExprEvalContexts.back().Context =
17695 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17697 return E;
17698 return TransformToPE(*this).TransformExpr(E);
17699}
17700
17702 assert(isUnevaluatedContext() &&
17703 "Should only transform unevaluated expressions");
17706 return TInfo;
17707 return TransformToPE(*this).TransformType(TInfo);
17708}
17709
17710void
17712 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17714 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17715 LambdaContextDecl, ExprContext);
17716
17717 // Discarded statements and immediate contexts nested in other
17718 // discarded statements or immediate context are themselves
17719 // a discarded statement or an immediate context, respectively.
17720 ExprEvalContexts.back().InDiscardedStatement =
17722
17723 // C++23 [expr.const]/p15
17724 // An expression or conversion is in an immediate function context if [...]
17725 // it is a subexpression of a manifestly constant-evaluated expression or
17726 // conversion.
17727 const auto &Prev = parentEvaluationContext();
17728 ExprEvalContexts.back().InImmediateFunctionContext =
17729 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17730
17731 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17732 Prev.InImmediateEscalatingFunctionContext;
17733
17734 Cleanup.reset();
17735 if (!MaybeODRUseExprs.empty())
17736 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17737}
17738
17739void
17743 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17744 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17745}
17746
17748 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
17749 // [expr.const]/p14.1
17750 // An expression or conversion is in an immediate function context if it is
17751 // potentially evaluated and either: its innermost enclosing non-block scope
17752 // is a function parameter scope of an immediate function.
17754 FD && FD->isConsteval()
17756 : NewContext);
17760
17761 Current.InDiscardedStatement = false;
17762
17763 if (FD) {
17764
17765 // Each ExpressionEvaluationContextRecord also keeps track of whether the
17766 // context is nested in an immediate function context, so smaller contexts
17767 // that appear inside immediate functions (like variable initializers) are
17768 // considered to be inside an immediate function context even though by
17769 // themselves they are not immediate function contexts. But when a new
17770 // function is entered, we need to reset this tracking, since the entered
17771 // function might be not an immediate function.
17772
17774 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
17775
17776 if (isLambdaMethod(FD))
17778 FD->isConsteval() ||
17779 (isLambdaMethod(FD) && (Parent.isConstantEvaluated() ||
17780 Parent.isImmediateFunctionContext()));
17781 else
17783 }
17784}
17785
17786namespace {
17787
17788const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17789 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17790 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17791 if (E->getOpcode() == UO_Deref)
17792 return CheckPossibleDeref(S, E->getSubExpr());
17793 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17794 return CheckPossibleDeref(S, E->getBase());
17795 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17796 return CheckPossibleDeref(S, E->getBase());
17797 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17798 QualType Inner;
17799 QualType Ty = E->getType();
17800 if (const auto *Ptr = Ty->getAs<PointerType>())
17801 Inner = Ptr->getPointeeType();
17802 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17803 Inner = Arr->getElementType();
17804 else
17805 return nullptr;
17806
17807 if (Inner->hasAttr(attr::NoDeref))
17808 return E;
17809 }
17810 return nullptr;
17811}
17812
17813} // namespace
17814
17816 for (const Expr *E : Rec.PossibleDerefs) {
17817 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17818 if (DeclRef) {
17819 const ValueDecl *Decl = DeclRef->getDecl();
17820 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17821 << Decl->getName() << E->getSourceRange();
17822 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17823 } else {
17824 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17825 << E->getSourceRange();
17826 }
17827 }
17828 Rec.PossibleDerefs.clear();
17829}
17830
17833 return;
17834
17835 // Note: ignoring parens here is not justified by the standard rules, but
17836 // ignoring parentheses seems like a more reasonable approach, and this only
17837 // drives a deprecation warning so doesn't affect conformance.
17838 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17839 if (BO->getOpcode() == BO_Assign) {
17840 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17841 llvm::erase(LHSs, BO->getLHS());
17842 }
17843 }
17844}
17845
17847 assert(getLangOpts().CPlusPlus20 &&
17848 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17849 "Cannot mark an immediate escalating expression outside of an "
17850 "immediate escalating context");
17851 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17852 Call && Call->getCallee()) {
17853 if (auto *DeclRef =
17854 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17855 DeclRef->setIsImmediateEscalating(true);
17856 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
17857 Ctr->setIsImmediateEscalating(true);
17858 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
17859 DeclRef->setIsImmediateEscalating(true);
17860 } else {
17861 assert(false && "expected an immediately escalating expression");
17862 }
17864 FI->FoundImmediateEscalatingExpression = true;
17865}
17866
17868 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17869 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17872 return E;
17873
17874 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17875 /// It's OK if this fails; we'll also remove this in
17876 /// HandleImmediateInvocations, but catching it here allows us to avoid
17877 /// walking the AST looking for it in simple cases.
17878 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17879 if (auto *DeclRef =
17880 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17881 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17882
17883 // C++23 [expr.const]/p16
17884 // An expression or conversion is immediate-escalating if it is not initially
17885 // in an immediate function context and it is [...] an immediate invocation
17886 // that is not a constant expression and is not a subexpression of an
17887 // immediate invocation.
17888 APValue Cached;
17889 auto CheckConstantExpressionAndKeepResult = [&]() {
17891 Expr::EvalResult Eval;
17892 Eval.Diag = &Notes;
17893 bool Res = E.get()->EvaluateAsConstantExpr(
17894 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
17895 if (Res && Notes.empty()) {
17896 Cached = std::move(Eval.Val);
17897 return true;
17898 }
17899 return false;
17900 };
17901
17902 if (!E.get()->isValueDependent() &&
17903 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17904 !CheckConstantExpressionAndKeepResult()) {
17906 return E;
17907 }
17908
17909 if (Cleanup.exprNeedsCleanups()) {
17910 // Since an immediate invocation is a full expression itself - it requires
17911 // an additional ExprWithCleanups node, but it can participate to a bigger
17912 // full expression which actually requires cleanups to be run after so
17913 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
17914 // may discard cleanups for outer expression too early.
17915
17916 // Note that ExprWithCleanups created here must always have empty cleanup
17917 // objects:
17918 // - compound literals do not create cleanup objects in C++ and immediate
17919 // invocations are C++-only.
17920 // - blocks are not allowed inside constant expressions and compiler will
17921 // issue an error if they appear there.
17922 //
17923 // Hence, in correct code any cleanup objects created inside current
17924 // evaluation context must be outside the immediate invocation.
17926 Cleanup.cleanupsHaveSideEffects(), {});
17927 }
17928
17930 getASTContext(), E.get(),
17931 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17932 getASTContext()),
17933 /*IsImmediateInvocation*/ true);
17934 if (Cached.hasValue())
17935 Res->MoveIntoResult(Cached, getASTContext());
17936 /// Value-dependent constant expressions should not be immediately
17937 /// evaluated until they are instantiated.
17938 if (!Res->isValueDependent())
17939 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17940 return Res;
17941}
17942
17946 Expr::EvalResult Eval;
17947 Eval.Diag = &Notes;
17948 ConstantExpr *CE = Candidate.getPointer();
17949 bool Result = CE->EvaluateAsConstantExpr(
17950 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17951 if (!Result || !Notes.empty()) {
17953 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17954 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17955 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
17956 FunctionDecl *FD = nullptr;
17957 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17958 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17959 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17960 FD = Call->getConstructor();
17961 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
17962 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
17963
17964 assert(FD && FD->isImmediateFunction() &&
17965 "could not find an immediate function in this expression");
17966 if (FD->isInvalidDecl())
17967 return;
17968 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
17969 << FD << FD->isConsteval();
17970 if (auto Context =
17972 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17973 << Context->Decl;
17974 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17975 }
17976 if (!FD->isConsteval())
17978 for (auto &Note : Notes)
17979 SemaRef.Diag(Note.first, Note.second);
17980 return;
17981 }
17983}
17984
17988 struct ComplexRemove : TreeTransform<ComplexRemove> {
17990 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17993 CurrentII;
17994 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17997 4>::reverse_iterator Current)
17998 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17999 void RemoveImmediateInvocation(ConstantExpr* E) {
18000 auto It = std::find_if(CurrentII, IISet.rend(),
18002 return Elem.getPointer() == E;
18003 });
18004 // It is possible that some subexpression of the current immediate
18005 // invocation was handled from another expression evaluation context. Do
18006 // not handle the current immediate invocation if some of its
18007 // subexpressions failed before.
18008 if (It == IISet.rend()) {
18009 if (SemaRef.FailedImmediateInvocations.contains(E))
18010 CurrentII->setInt(1);
18011 } else {
18012 It->setInt(1); // Mark as deleted
18013 }
18014 }
18015 ExprResult TransformConstantExpr(ConstantExpr *E) {
18016 if (!E->isImmediateInvocation())
18017 return Base::TransformConstantExpr(E);
18018 RemoveImmediateInvocation(E);
18019 return Base::TransformExpr(E->getSubExpr());
18020 }
18021 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18022 /// we need to remove its DeclRefExpr from the DRSet.
18023 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18024 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18025 return Base::TransformCXXOperatorCallExpr(E);
18026 }
18027 /// Base::TransformUserDefinedLiteral doesn't preserve the
18028 /// UserDefinedLiteral node.
18029 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18030 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18031 /// here.
18032 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18033 if (!Init)
18034 return Init;
18035
18036 // We cannot use IgnoreImpCasts because we need to preserve
18037 // full expressions.
18038 while (true) {
18039 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
18040 Init = ICE->getSubExpr();
18041 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
18042 Init = ICE->getSubExpr();
18043 else
18044 break;
18045 }
18046 /// ConstantExprs are the first layer of implicit node to be removed so if
18047 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18048 if (auto *CE = dyn_cast<ConstantExpr>(Init);
18049 CE && CE->isImmediateInvocation())
18050 RemoveImmediateInvocation(CE);
18051 return Base::TransformInitializer(Init, NotCopyInit);
18052 }
18053 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18054 DRSet.erase(E);
18055 return E;
18056 }
18057 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18058 // Do not rebuild lambdas to avoid creating a new type.
18059 // Lambdas have already been processed inside their eval contexts.
18060 return E;
18061 }
18062 bool AlwaysRebuild() { return false; }
18063 bool ReplacingOriginal() { return true; }
18064 bool AllowSkippingCXXConstructExpr() {
18065 bool Res = AllowSkippingFirstCXXConstructExpr;
18066 AllowSkippingFirstCXXConstructExpr = true;
18067 return Res;
18068 }
18069 bool AllowSkippingFirstCXXConstructExpr = true;
18070 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18072
18073 /// CXXConstructExpr with a single argument are getting skipped by
18074 /// TreeTransform in some situtation because they could be implicit. This
18075 /// can only occur for the top-level CXXConstructExpr because it is used
18076 /// nowhere in the expression being transformed therefore will not be rebuilt.
18077 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18078 /// skipping the first CXXConstructExpr.
18079 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18080 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18081
18082 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18083 // The result may not be usable in case of previous compilation errors.
18084 // In this case evaluation of the expression may result in crash so just
18085 // don't do anything further with the result.
18086 if (Res.isUsable()) {
18088 It->getPointer()->setSubExpr(Res.get());
18089 }
18090}
18091
18092static void
18095 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18096 Rec.ReferenceToConsteval.size() == 0) ||
18098 return;
18099
18100 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18101 // [...]
18102 // - the initializer of a variable that is usable in constant expressions or
18103 // has constant initialization.
18104 if (SemaRef.getLangOpts().CPlusPlus23 &&
18105 Rec.ExprContext ==
18107 auto *VD = cast<VarDecl>(Rec.ManglingContextDecl);
18108 if (VD->isUsableInConstantExpressions(SemaRef.Context) ||
18109 VD->hasConstantInitialization()) {
18110 // An expression or conversion is in an 'immediate function context' if it
18111 // is potentially evaluated and either:
18112 // [...]
18113 // - it is a subexpression of a manifestly constant-evaluated expression
18114 // or conversion.
18115 return;
18116 }
18117 }
18118
18119 /// When we have more than 1 ImmediateInvocationCandidates or previously
18120 /// failed immediate invocations, we need to check for nested
18121 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18122 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18123 /// invocation.
18124 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18126
18127 /// Prevent sema calls during the tree transform from adding pointers that
18128 /// are already in the sets.
18129 llvm::SaveAndRestore DisableIITracking(
18131
18132 /// Prevent diagnostic during tree transfrom as they are duplicates
18134
18135 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18136 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18137 if (!It->getInt())
18139 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18140 Rec.ReferenceToConsteval.size()) {
18141 struct SimpleRemove : DynamicRecursiveASTVisitor {
18142 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18143 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18144 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18145 DRSet.erase(E);
18146 return DRSet.size();
18147 }
18148 } Visitor(Rec.ReferenceToConsteval);
18149 Visitor.TraverseStmt(
18150 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18151 }
18152 for (auto CE : Rec.ImmediateInvocationCandidates)
18153 if (!CE.getInt())
18155 for (auto *DR : Rec.ReferenceToConsteval) {
18156 // If the expression is immediate escalating, it is not an error;
18157 // The outer context itself becomes immediate and further errors,
18158 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18159 if (DR->isImmediateEscalating())
18160 continue;
18161 auto *FD = cast<FunctionDecl>(DR->getDecl());
18162 const NamedDecl *ND = FD;
18163 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18164 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18165 ND = MD->getParent();
18166
18167 // C++23 [expr.const]/p16
18168 // An expression or conversion is immediate-escalating if it is not
18169 // initially in an immediate function context and it is [...] a
18170 // potentially-evaluated id-expression that denotes an immediate function
18171 // that is not a subexpression of an immediate invocation.
18172 bool ImmediateEscalating = false;
18173 bool IsPotentiallyEvaluated =
18174 Rec.Context ==
18176 Rec.Context ==
18178 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18179 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18180
18182 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18183 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18184 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18185 if (!FD->getBuiltinID())
18186 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18187 if (auto Context =
18189 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18190 << Context->Decl;
18191 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18192 }
18193 if (FD->isImmediateEscalating() && !FD->isConsteval())
18195
18196 } else {
18198 }
18199 }
18200}
18201
18204 if (!Rec.Lambdas.empty()) {
18206 if (!getLangOpts().CPlusPlus20 &&
18207 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18208 Rec.isUnevaluated() ||
18210 unsigned D;
18211 if (Rec.isUnevaluated()) {
18212 // C++11 [expr.prim.lambda]p2:
18213 // A lambda-expression shall not appear in an unevaluated operand
18214 // (Clause 5).
18215 D = diag::err_lambda_unevaluated_operand;
18216 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18217 // C++1y [expr.const]p2:
18218 // A conditional-expression e is a core constant expression unless the
18219 // evaluation of e, following the rules of the abstract machine, would
18220 // evaluate [...] a lambda-expression.
18221 D = diag::err_lambda_in_constant_expression;
18222 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18223 // C++17 [expr.prim.lamda]p2:
18224 // A lambda-expression shall not appear [...] in a template-argument.
18225 D = diag::err_lambda_in_invalid_context;
18226 } else
18227 llvm_unreachable("Couldn't infer lambda error message.");
18228
18229 for (const auto *L : Rec.Lambdas)
18230 Diag(L->getBeginLoc(), D);
18231 }
18232 }
18233
18234 // Append the collected materialized temporaries into previous context before
18235 // exit if the previous also is a lifetime extending context.
18237 parentEvaluationContext().InLifetimeExtendingContext &&
18238 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18241 }
18242
18244 HandleImmediateInvocations(*this, Rec);
18245
18246 // Warn on any volatile-qualified simple-assignments that are not discarded-
18247 // value expressions nor unevaluated operands (those cases get removed from
18248 // this list by CheckUnusedVolatileAssignment).
18249 for (auto *BO : Rec.VolatileAssignmentLHSs)
18250 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18251 << BO->getType();
18252
18253 // When are coming out of an unevaluated context, clear out any
18254 // temporaries that we may have created as part of the evaluation of
18255 // the expression in that context: they aren't relevant because they
18256 // will never be constructed.
18257 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18259 ExprCleanupObjects.end());
18260 Cleanup = Rec.ParentCleanup;
18263 // Otherwise, merge the contexts together.
18264 } else {
18265 Cleanup.mergeFrom(Rec.ParentCleanup);
18266 MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
18267 }
18268
18270
18271 // Pop the current expression evaluation context off the stack.
18272 ExprEvalContexts.pop_back();
18273}
18274
18276 ExprCleanupObjects.erase(
18277 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18278 ExprCleanupObjects.end());
18279 Cleanup.reset();
18280 MaybeODRUseExprs.clear();
18281}
18282
18285 if (Result.isInvalid())
18286 return ExprError();
18287 E = Result.get();
18288 if (!E->getType()->isVariablyModifiedType())
18289 return E;
18291}
18292
18293/// Are we in a context that is potentially constant evaluated per C++20
18294/// [expr.const]p12?
18296 /// C++2a [expr.const]p12:
18297 // An expression or conversion is potentially constant evaluated if it is
18298 switch (SemaRef.ExprEvalContexts.back().Context) {
18301
18302 // -- a manifestly constant-evaluated expression,
18306 // -- a potentially-evaluated expression,
18308 // -- an immediate subexpression of a braced-init-list,
18309
18310 // -- [FIXME] an expression of the form & cast-expression that occurs
18311 // within a templated entity
18312 // -- a subexpression of one of the above that is not a subexpression of
18313 // a nested unevaluated operand.
18314 return true;
18315
18318 // Expressions in this context are never evaluated.
18319 return false;
18320 }
18321 llvm_unreachable("Invalid context");
18322}
18323
18324/// Return true if this function has a calling convention that requires mangling
18325/// in the size of the parameter pack.
18327 // These manglings are only applicable for targets whcih use Microsoft
18328 // mangling scheme for C.
18330 return false;
18331
18332 // If this is C++ and this isn't an extern "C" function, parameters do not
18333 // need to be complete. In this case, C++ mangling will apply, which doesn't
18334 // use the size of the parameters.
18335 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18336 return false;
18337
18338 // Stdcall, fastcall, and vectorcall need this special treatment.
18339 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18340 switch (CC) {
18341 case CC_X86StdCall:
18342 case CC_X86FastCall:
18343 case CC_X86VectorCall:
18344 return true;
18345 default:
18346 break;
18347 }
18348 return false;
18349}
18350
18351/// Require that all of the parameter types of function be complete. Normally,
18352/// parameter types are only required to be complete when a function is called
18353/// or defined, but to mangle functions with certain calling conventions, the
18354/// mangler needs to know the size of the parameter list. In this situation,
18355/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18356/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18357/// result in a linker error. Clang doesn't implement this behavior, and instead
18358/// attempts to error at compile time.
18360 SourceLocation Loc) {
18361 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18362 FunctionDecl *FD;
18363 ParmVarDecl *Param;
18364
18365 public:
18366 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18367 : FD(FD), Param(Param) {}
18368
18369 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18370 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18371 StringRef CCName;
18372 switch (CC) {
18373 case CC_X86StdCall:
18374 CCName = "stdcall";
18375 break;
18376 case CC_X86FastCall:
18377 CCName = "fastcall";
18378 break;
18379 case CC_X86VectorCall:
18380 CCName = "vectorcall";
18381 break;
18382 default:
18383 llvm_unreachable("CC does not need mangling");
18384 }
18385
18386 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18387 << Param->getDeclName() << FD->getDeclName() << CCName;
18388 }
18389 };
18390
18391 for (ParmVarDecl *Param : FD->parameters()) {
18392 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18393 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18394 }
18395}
18396
18397namespace {
18398enum class OdrUseContext {
18399 /// Declarations in this context are not odr-used.
18400 None,
18401 /// Declarations in this context are formally odr-used, but this is a
18402 /// dependent context.
18403 Dependent,
18404 /// Declarations in this context are odr-used but not actually used (yet).
18405 FormallyOdrUsed,
18406 /// Declarations in this context are used.
18407 Used
18408};
18409}
18410
18411/// Are we within a context in which references to resolved functions or to
18412/// variables result in odr-use?
18413static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18416
18417 if (Context.isUnevaluated())
18418 return OdrUseContext::None;
18419
18421 return OdrUseContext::Dependent;
18422
18423 if (Context.isDiscardedStatementContext())
18424 return OdrUseContext::FormallyOdrUsed;
18425
18426 else if (Context.Context ==
18428 return OdrUseContext::FormallyOdrUsed;
18429
18430 return OdrUseContext::Used;
18431}
18432
18434 if (!Func->isConstexpr())
18435 return false;
18436
18437 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18438 return true;
18439
18440 // Lambda conversion operators are never user provided.
18441 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))
18442 return isLambdaConversionOperator(Conv);
18443
18444 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18445 return CCD && CCD->getInheritedConstructor();
18446}
18447
18449 bool MightBeOdrUse) {
18450 assert(Func && "No function?");
18451
18452 Func->setReferenced();
18453
18454 // Recursive functions aren't really used until they're used from some other
18455 // context.
18456 bool IsRecursiveCall = CurContext == Func;
18457
18458 // C++11 [basic.def.odr]p3:
18459 // A function whose name appears as a potentially-evaluated expression is
18460 // odr-used if it is the unique lookup result or the selected member of a
18461 // set of overloaded functions [...].
18462 //
18463 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18464 // can just check that here.
18465 OdrUseContext OdrUse =
18466 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18467 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18468 OdrUse = OdrUseContext::FormallyOdrUsed;
18469
18470 // Trivial default constructors and destructors are never actually used.
18471 // FIXME: What about other special members?
18472 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18473 OdrUse == OdrUseContext::Used) {
18474 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18475 if (Constructor->isDefaultConstructor())
18476 OdrUse = OdrUseContext::FormallyOdrUsed;
18478 OdrUse = OdrUseContext::FormallyOdrUsed;
18479 }
18480
18481 // C++20 [expr.const]p12:
18482 // A function [...] is needed for constant evaluation if it is [...] a
18483 // constexpr function that is named by an expression that is potentially
18484 // constant evaluated
18485 bool NeededForConstantEvaluation =
18488
18489 // Determine whether we require a function definition to exist, per
18490 // C++11 [temp.inst]p3:
18491 // Unless a function template specialization has been explicitly
18492 // instantiated or explicitly specialized, the function template
18493 // specialization is implicitly instantiated when the specialization is
18494 // referenced in a context that requires a function definition to exist.
18495 // C++20 [temp.inst]p7:
18496 // The existence of a definition of a [...] function is considered to
18497 // affect the semantics of the program if the [...] function is needed for
18498 // constant evaluation by an expression
18499 // C++20 [basic.def.odr]p10:
18500 // Every program shall contain exactly one definition of every non-inline
18501 // function or variable that is odr-used in that program outside of a
18502 // discarded statement
18503 // C++20 [special]p1:
18504 // The implementation will implicitly define [defaulted special members]
18505 // if they are odr-used or needed for constant evaluation.
18506 //
18507 // Note that we skip the implicit instantiation of templates that are only
18508 // used in unused default arguments or by recursive calls to themselves.
18509 // This is formally non-conforming, but seems reasonable in practice.
18510 bool NeedDefinition =
18511 !IsRecursiveCall &&
18512 (OdrUse == OdrUseContext::Used ||
18513 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18514
18515 // C++14 [temp.expl.spec]p6:
18516 // If a template [...] is explicitly specialized then that specialization
18517 // shall be declared before the first use of that specialization that would
18518 // cause an implicit instantiation to take place, in every translation unit
18519 // in which such a use occurs
18520 if (NeedDefinition &&
18521 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18522 Func->getMemberSpecializationInfo()))
18524
18525 if (getLangOpts().CUDA)
18526 CUDA().CheckCall(Loc, Func);
18527
18528 // If we need a definition, try to create one.
18529 if (NeedDefinition && !Func->getBody()) {
18532 dyn_cast<CXXConstructorDecl>(Func)) {
18534 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18535 if (Constructor->isDefaultConstructor()) {
18536 if (Constructor->isTrivial() &&
18537 !Constructor->hasAttr<DLLExportAttr>())
18538 return;
18540 } else if (Constructor->isCopyConstructor()) {
18542 } else if (Constructor->isMoveConstructor()) {
18544 }
18545 } else if (Constructor->getInheritedConstructor()) {
18547 }
18548 } else if (CXXDestructorDecl *Destructor =
18549 dyn_cast<CXXDestructorDecl>(Func)) {
18551 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18552 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18553 return;
18555 }
18556 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18557 MarkVTableUsed(Loc, Destructor->getParent());
18558 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18559 if (MethodDecl->isOverloadedOperator() &&
18560 MethodDecl->getOverloadedOperator() == OO_Equal) {
18561 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18562 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18563 if (MethodDecl->isCopyAssignmentOperator())
18564 DefineImplicitCopyAssignment(Loc, MethodDecl);
18565 else if (MethodDecl->isMoveAssignmentOperator())
18566 DefineImplicitMoveAssignment(Loc, MethodDecl);
18567 }
18568 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18569 MethodDecl->getParent()->isLambda()) {
18570 CXXConversionDecl *Conversion =
18571 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18572 if (Conversion->isLambdaToBlockPointerConversion())
18574 else
18576 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18577 MarkVTableUsed(Loc, MethodDecl->getParent());
18578 }
18579
18580 if (Func->isDefaulted() && !Func->isDeleted()) {
18584 }
18585
18586 // Implicit instantiation of function templates and member functions of
18587 // class templates.
18588 if (Func->isImplicitlyInstantiable()) {
18590 Func->getTemplateSpecializationKindForInstantiation();
18591 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18592 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18593 if (FirstInstantiation) {
18594 PointOfInstantiation = Loc;
18595 if (auto *MSI = Func->getMemberSpecializationInfo())
18596 MSI->setPointOfInstantiation(Loc);
18597 // FIXME: Notify listener.
18598 else
18599 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18600 } else if (TSK != TSK_ImplicitInstantiation) {
18601 // Use the point of use as the point of instantiation, instead of the
18602 // point of explicit instantiation (which we track as the actual point
18603 // of instantiation). This gives better backtraces in diagnostics.
18604 PointOfInstantiation = Loc;
18605 }
18606
18607 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18608 Func->isConstexpr()) {
18609 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18610 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18611 CodeSynthesisContexts.size())
18613 std::make_pair(Func, PointOfInstantiation));
18614 else if (Func->isConstexpr())
18615 // Do not defer instantiations of constexpr functions, to avoid the
18616 // expression evaluator needing to call back into Sema if it sees a
18617 // call to such a function.
18618 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18619 else {
18620 Func->setInstantiationIsPending(true);
18621 PendingInstantiations.push_back(
18622 std::make_pair(Func, PointOfInstantiation));
18623 if (llvm::isTimeTraceVerbose()) {
18624 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
18625 std::string Name;
18626 llvm::raw_string_ostream OS(Name);
18627 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
18628 /*Qualified=*/true);
18629 return Name;
18630 });
18631 }
18632 // Notify the consumer that a function was implicitly instantiated.
18633 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
18634 }
18635 }
18636 } else {
18637 // Walk redefinitions, as some of them may be instantiable.
18638 for (auto *i : Func->redecls()) {
18639 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18640 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18641 }
18642 }
18643 });
18644 }
18645
18646 // If a constructor was defined in the context of a default parameter
18647 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18648 // context), its initializers may not be referenced yet.
18649 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18651 *this,
18652 Constructor->isImmediateFunction()
18655 Constructor);
18656 for (CXXCtorInitializer *Init : Constructor->inits()) {
18657 if (Init->isInClassMemberInitializer())
18658 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18659 MarkDeclarationsReferencedInExpr(Init->getInit());
18660 });
18661 }
18662 }
18663
18664 // C++14 [except.spec]p17:
18665 // An exception-specification is considered to be needed when:
18666 // - the function is odr-used or, if it appears in an unevaluated operand,
18667 // would be odr-used if the expression were potentially-evaluated;
18668 //
18669 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18670 // function is a pure virtual function we're calling, and in that case the
18671 // function was selected by overload resolution and we need to resolve its
18672 // exception specification for a different reason.
18673 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18675 ResolveExceptionSpec(Loc, FPT);
18676
18677 // A callee could be called by a host function then by a device function.
18678 // If we only try recording once, we will miss recording the use on device
18679 // side. Therefore keep trying until it is recorded.
18680 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18681 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
18683
18684 // If this is the first "real" use, act on that.
18685 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18686 // Keep track of used but undefined functions.
18687 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
18688 if (mightHaveNonExternalLinkage(Func))
18689 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18690 else if (Func->getMostRecentDecl()->isInlined() &&
18691 !LangOpts.GNUInline &&
18692 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18693 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18695 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18696 }
18697
18698 // Some x86 Windows calling conventions mangle the size of the parameter
18699 // pack into the name. Computing the size of the parameters requires the
18700 // parameter types to be complete. Check that now.
18703
18704 // In the MS C++ ABI, the compiler emits destructor variants where they are
18705 // used. If the destructor is used here but defined elsewhere, mark the
18706 // virtual base destructors referenced. If those virtual base destructors
18707 // are inline, this will ensure they are defined when emitting the complete
18708 // destructor variant. This checking may be redundant if the destructor is
18709 // provided later in this TU.
18710 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18711 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18712 CXXRecordDecl *Parent = Dtor->getParent();
18713 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18715 }
18716 }
18717
18718 Func->markUsed(Context);
18719 }
18720}
18721
18722/// Directly mark a variable odr-used. Given a choice, prefer to use
18723/// MarkVariableReferenced since it does additional checks and then
18724/// calls MarkVarDeclODRUsed.
18725/// If the variable must be captured:
18726/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18727/// - else capture it in the DeclContext that maps to the
18728/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18729static void
18731 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18732 // Keep track of used but undefined variables.
18733 // FIXME: We shouldn't suppress this warning for static data members.
18734 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18735 assert(Var && "expected a capturable variable");
18736
18738 (!Var->isExternallyVisible() || Var->isInline() ||
18740 !(Var->isStaticDataMember() && Var->hasInit())) {
18742 if (old.isInvalid())
18743 old = Loc;
18744 }
18745 QualType CaptureType, DeclRefType;
18746 if (SemaRef.LangOpts.OpenMP)
18749 /*EllipsisLoc*/ SourceLocation(),
18750 /*BuildAndDiagnose*/ true, CaptureType,
18751 DeclRefType, FunctionScopeIndexToStopAt);
18752
18753 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18754 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18755 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18756 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18757 if (VarTarget == SemaCUDA::CVT_Host &&
18758 (UserTarget == CUDAFunctionTarget::Device ||
18759 UserTarget == CUDAFunctionTarget::HostDevice ||
18760 UserTarget == CUDAFunctionTarget::Global)) {
18761 // Diagnose ODR-use of host global variables in device functions.
18762 // Reference of device global variables in host functions is allowed
18763 // through shadow variables therefore it is not diagnosed.
18764 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18765 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18766 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
18768 Var->getType().isConstQualified()
18769 ? diag::note_cuda_const_var_unpromoted
18770 : diag::note_cuda_host_var);
18771 }
18772 } else if (VarTarget == SemaCUDA::CVT_Device &&
18773 !Var->hasAttr<CUDASharedAttr>() &&
18774 (UserTarget == CUDAFunctionTarget::Host ||
18775 UserTarget == CUDAFunctionTarget::HostDevice)) {
18776 // Record a CUDA/HIP device side variable if it is ODR-used
18777 // by host code. This is done conservatively, when the variable is
18778 // referenced in any of the following contexts:
18779 // - a non-function context
18780 // - a host function
18781 // - a host device function
18782 // This makes the ODR-use of the device side variable by host code to
18783 // be visible in the device compilation for the compiler to be able to
18784 // emit template variables instantiated by host code only and to
18785 // externalize the static device side variable ODR-used by host code.
18786 if (!Var->hasExternalStorage())
18788 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18789 (!FD || (!FD->getDescribedFunctionTemplate() &&
18793 }
18794 }
18795
18796 V->markUsed(SemaRef.Context);
18797}
18798
18800 SourceLocation Loc,
18801 unsigned CapturingScopeIndex) {
18802 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18803}
18804
18806 SourceLocation loc,
18807 ValueDecl *var) {
18808 DeclContext *VarDC = var->getDeclContext();
18809
18810 // If the parameter still belongs to the translation unit, then
18811 // we're actually just using one parameter in the declaration of
18812 // the next.
18813 if (isa<ParmVarDecl>(var) &&
18815 return;
18816
18817 // For C code, don't diagnose about capture if we're not actually in code
18818 // right now; it's impossible to write a non-constant expression outside of
18819 // function context, so we'll get other (more useful) diagnostics later.
18820 //
18821 // For C++, things get a bit more nasty... it would be nice to suppress this
18822 // diagnostic for certain cases like using a local variable in an array bound
18823 // for a member of a local class, but the correct predicate is not obvious.
18824 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18825 return;
18826
18827 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18828 unsigned ContextKind = 3; // unknown
18829 if (isa<CXXMethodDecl>(VarDC) &&
18830 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18831 ContextKind = 2;
18832 } else if (isa<FunctionDecl>(VarDC)) {
18833 ContextKind = 0;
18834 } else if (isa<BlockDecl>(VarDC)) {
18835 ContextKind = 1;
18836 }
18837
18838 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18839 << var << ValueKind << ContextKind << VarDC;
18840 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18841 << var;
18842
18843 // FIXME: Add additional diagnostic info about class etc. which prevents
18844 // capture.
18845}
18846
18848 ValueDecl *Var,
18849 bool &SubCapturesAreNested,
18850 QualType &CaptureType,
18851 QualType &DeclRefType) {
18852 // Check whether we've already captured it.
18853 if (CSI->CaptureMap.count(Var)) {
18854 // If we found a capture, any subcaptures are nested.
18855 SubCapturesAreNested = true;
18856
18857 // Retrieve the capture type for this variable.
18858 CaptureType = CSI->getCapture(Var).getCaptureType();
18859
18860 // Compute the type of an expression that refers to this variable.
18861 DeclRefType = CaptureType.getNonReferenceType();
18862
18863 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18864 // are mutable in the sense that user can change their value - they are
18865 // private instances of the captured declarations.
18866 const Capture &Cap = CSI->getCapture(Var);
18867 // C++ [expr.prim.lambda]p10:
18868 // The type of such a data member is [...] an lvalue reference to the
18869 // referenced function type if the entity is a reference to a function.
18870 // [...]
18871 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
18872 !(isa<LambdaScopeInfo>(CSI) &&
18873 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
18875 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18876 DeclRefType.addConst();
18877 return true;
18878 }
18879 return false;
18880}
18881
18882// Only block literals, captured statements, and lambda expressions can
18883// capture; other scopes don't work.
18885 ValueDecl *Var,
18886 SourceLocation Loc,
18887 const bool Diagnose,
18888 Sema &S) {
18891
18892 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18893 if (Underlying) {
18894 if (Underlying->hasLocalStorage() && Diagnose)
18896 }
18897 return nullptr;
18898}
18899
18900// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18901// certain types of variables (unnamed, variably modified types etc.)
18902// so check for eligibility.
18904 SourceLocation Loc, const bool Diagnose,
18905 Sema &S) {
18906
18907 assert((isa<VarDecl, BindingDecl>(Var)) &&
18908 "Only variables and structured bindings can be captured");
18909
18910 bool IsBlock = isa<BlockScopeInfo>(CSI);
18911 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18912
18913 // Lambdas are not allowed to capture unnamed variables
18914 // (e.g. anonymous unions).
18915 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18916 // assuming that's the intent.
18917 if (IsLambda && !Var->getDeclName()) {
18918 if (Diagnose) {
18919 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18920 S.Diag(Var->getLocation(), diag::note_declared_at);
18921 }
18922 return false;
18923 }
18924
18925 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18926 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18927 if (Diagnose) {
18928 S.Diag(Loc, diag::err_ref_vm_type);
18929 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18930 }
18931 return false;
18932 }
18933 // Prohibit structs with flexible array members too.
18934 // We cannot capture what is in the tail end of the struct.
18935 if (const auto *VTD = Var->getType()->getAsRecordDecl();
18936 VTD && VTD->hasFlexibleArrayMember()) {
18937 if (Diagnose) {
18938 if (IsBlock)
18939 S.Diag(Loc, diag::err_ref_flexarray_type);
18940 else
18941 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18942 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18943 }
18944 return false;
18945 }
18946 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18947 // Lambdas and captured statements are not allowed to capture __block
18948 // variables; they don't support the expected semantics.
18949 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18950 if (Diagnose) {
18951 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18952 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18953 }
18954 return false;
18955 }
18956 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18957 if (S.getLangOpts().OpenCL && IsBlock &&
18958 Var->getType()->isBlockPointerType()) {
18959 if (Diagnose)
18960 S.Diag(Loc, diag::err_opencl_block_ref_block);
18961 return false;
18962 }
18963
18964 if (isa<BindingDecl>(Var)) {
18965 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18966 if (Diagnose)
18968 return false;
18969 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18970 S.Diag(Loc, S.LangOpts.CPlusPlus20
18971 ? diag::warn_cxx17_compat_capture_binding
18972 : diag::ext_capture_binding)
18973 << Var;
18974 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18975 }
18976 }
18977
18978 return true;
18979}
18980
18981// Returns true if the capture by block was successful.
18983 SourceLocation Loc, const bool BuildAndDiagnose,
18984 QualType &CaptureType, QualType &DeclRefType,
18985 const bool Nested, Sema &S, bool Invalid) {
18986 bool ByRef = false;
18987
18988 // Blocks are not allowed to capture arrays, excepting OpenCL.
18989 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18990 // (decayed to pointers).
18991 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18992 if (BuildAndDiagnose) {
18993 S.Diag(Loc, diag::err_ref_array_type);
18994 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18995 Invalid = true;
18996 } else {
18997 return false;
18998 }
18999 }
19000
19001 // Forbid the block-capture of autoreleasing variables.
19002 if (!Invalid &&
19004 if (BuildAndDiagnose) {
19005 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19006 << /*block*/ 0;
19007 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19008 Invalid = true;
19009 } else {
19010 return false;
19011 }
19012 }
19013
19014 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19015 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19016 QualType PointeeTy = PT->getPointeeType();
19017
19018 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19020 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19021 if (BuildAndDiagnose) {
19022 SourceLocation VarLoc = Var->getLocation();
19023 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19024 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19025 }
19026 }
19027 }
19028
19029 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19030 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19031 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
19032 // Block capture by reference does not change the capture or
19033 // declaration reference types.
19034 ByRef = true;
19035 } else {
19036 // Block capture by copy introduces 'const'.
19037 CaptureType = CaptureType.getNonReferenceType().withConst();
19038 DeclRefType = CaptureType;
19039 }
19040
19041 // Actually capture the variable.
19042 if (BuildAndDiagnose)
19043 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19044 CaptureType, Invalid);
19045
19046 return !Invalid;
19047}
19048
19049/// Capture the given variable in the captured region.
19052 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19053 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19054 Sema &S, bool Invalid) {
19055 // By default, capture variables by reference.
19056 bool ByRef = true;
19057 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19058 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19059 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19060 // Using an LValue reference type is consistent with Lambdas (see below).
19061 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
19062 bool HasConst = DeclRefType.isConstQualified();
19063 DeclRefType = DeclRefType.getUnqualifiedType();
19064 // Don't lose diagnostics about assignments to const.
19065 if (HasConst)
19066 DeclRefType.addConst();
19067 }
19068 // Do not capture firstprivates in tasks.
19069 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
19070 RSI->OpenMPCaptureLevel) != OMPC_unknown)
19071 return true;
19072 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19073 RSI->OpenMPCaptureLevel);
19074 }
19075
19076 if (ByRef)
19077 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19078 else
19079 CaptureType = DeclRefType;
19080
19081 // Actually capture the variable.
19082 if (BuildAndDiagnose)
19083 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19084 Loc, SourceLocation(), CaptureType, Invalid);
19085
19086 return !Invalid;
19087}
19088
19089/// Capture the given variable in the lambda.
19091 SourceLocation Loc, const bool BuildAndDiagnose,
19092 QualType &CaptureType, QualType &DeclRefType,
19093 const bool RefersToCapturedVariable,
19094 const TryCaptureKind Kind,
19095 SourceLocation EllipsisLoc, const bool IsTopScope,
19096 Sema &S, bool Invalid) {
19097 // Determine whether we are capturing by reference or by value.
19098 bool ByRef = false;
19099 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19100 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19101 } else {
19102 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19103 }
19104
19105 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19107 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19108 Invalid = true;
19109 }
19110
19111 // Compute the type of the field that will capture this variable.
19112 if (ByRef) {
19113 // C++11 [expr.prim.lambda]p15:
19114 // An entity is captured by reference if it is implicitly or
19115 // explicitly captured but not captured by copy. It is
19116 // unspecified whether additional unnamed non-static data
19117 // members are declared in the closure type for entities
19118 // captured by reference.
19119 //
19120 // FIXME: It is not clear whether we want to build an lvalue reference
19121 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19122 // to do the former, while EDG does the latter. Core issue 1249 will
19123 // clarify, but for now we follow GCC because it's a more permissive and
19124 // easily defensible position.
19125 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19126 } else {
19127 // C++11 [expr.prim.lambda]p14:
19128 // For each entity captured by copy, an unnamed non-static
19129 // data member is declared in the closure type. The
19130 // declaration order of these members is unspecified. The type
19131 // of such a data member is the type of the corresponding
19132 // captured entity if the entity is not a reference to an
19133 // object, or the referenced type otherwise. [Note: If the
19134 // captured entity is a reference to a function, the
19135 // corresponding data member is also a reference to a
19136 // function. - end note ]
19137 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19138 if (!RefType->getPointeeType()->isFunctionType())
19139 CaptureType = RefType->getPointeeType();
19140 }
19141
19142 // Forbid the lambda copy-capture of autoreleasing variables.
19143 if (!Invalid &&
19145 if (BuildAndDiagnose) {
19146 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19147 S.Diag(Var->getLocation(), diag::note_previous_decl)
19148 << Var->getDeclName();
19149 Invalid = true;
19150 } else {
19151 return false;
19152 }
19153 }
19154
19155 // Make sure that by-copy captures are of a complete and non-abstract type.
19156 if (!Invalid && BuildAndDiagnose) {
19157 if (!CaptureType->isDependentType() &&
19159 Loc, CaptureType,
19160 diag::err_capture_of_incomplete_or_sizeless_type,
19161 Var->getDeclName()))
19162 Invalid = true;
19163 else if (S.RequireNonAbstractType(Loc, CaptureType,
19164 diag::err_capture_of_abstract_type))
19165 Invalid = true;
19166 }
19167 }
19168
19169 // Compute the type of a reference to this captured variable.
19170 if (ByRef)
19171 DeclRefType = CaptureType.getNonReferenceType();
19172 else {
19173 // C++ [expr.prim.lambda]p5:
19174 // The closure type for a lambda-expression has a public inline
19175 // function call operator [...]. This function call operator is
19176 // declared const (9.3.1) if and only if the lambda-expression's
19177 // parameter-declaration-clause is not followed by mutable.
19178 DeclRefType = CaptureType.getNonReferenceType();
19179 bool Const = LSI->lambdaCaptureShouldBeConst();
19180 // C++ [expr.prim.lambda]p10:
19181 // The type of such a data member is [...] an lvalue reference to the
19182 // referenced function type if the entity is a reference to a function.
19183 // [...]
19184 if (Const && !CaptureType->isReferenceType() &&
19185 !DeclRefType->isFunctionType())
19186 DeclRefType.addConst();
19187 }
19188
19189 // Add the capture.
19190 if (BuildAndDiagnose)
19191 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19192 Loc, EllipsisLoc, CaptureType, Invalid);
19193
19194 return !Invalid;
19195}
19196
19198 const ASTContext &Context) {
19199 // Offer a Copy fix even if the type is dependent.
19200 if (Var->getType()->isDependentType())
19201 return true;
19203 if (T.isTriviallyCopyableType(Context))
19204 return true;
19205 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19206
19207 if (!(RD = RD->getDefinition()))
19208 return false;
19209 if (RD->hasSimpleCopyConstructor())
19210 return true;
19211 if (RD->hasUserDeclaredCopyConstructor())
19212 for (CXXConstructorDecl *Ctor : RD->ctors())
19213 if (Ctor->isCopyConstructor())
19214 return !Ctor->isDeleted();
19215 }
19216 return false;
19217}
19218
19219/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19220/// default capture. Fixes may be omitted if they aren't allowed by the
19221/// standard, for example we can't emit a default copy capture fix-it if we
19222/// already explicitly copy capture capture another variable.
19224 ValueDecl *Var) {
19226 // Don't offer Capture by copy of default capture by copy fixes if Var is
19227 // known not to be copy constructible.
19228 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19229
19230 SmallString<32> FixBuffer;
19231 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19232 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19233 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19234 if (ShouldOfferCopyFix) {
19235 // Offer fixes to insert an explicit capture for the variable.
19236 // [] -> [VarName]
19237 // [OtherCapture] -> [OtherCapture, VarName]
19238 FixBuffer.assign({Separator, Var->getName()});
19239 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19240 << Var << /*value*/ 0
19241 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19242 }
19243 // As above but capture by reference.
19244 FixBuffer.assign({Separator, "&", Var->getName()});
19245 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19246 << Var << /*reference*/ 1
19247 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19248 }
19249
19250 // Only try to offer default capture if there are no captures excluding this
19251 // and init captures.
19252 // [this]: OK.
19253 // [X = Y]: OK.
19254 // [&A, &B]: Don't offer.
19255 // [A, B]: Don't offer.
19256 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19257 return !C.isThisCapture() && !C.isInitCapture();
19258 }))
19259 return;
19260
19261 // The default capture specifiers, '=' or '&', must appear first in the
19262 // capture body.
19263 SourceLocation DefaultInsertLoc =
19265
19266 if (ShouldOfferCopyFix) {
19267 bool CanDefaultCopyCapture = true;
19268 // [=, *this] OK since c++17
19269 // [=, this] OK since c++20
19270 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19271 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19273 : false;
19274 // We can't use default capture by copy if any captures already specified
19275 // capture by copy.
19276 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19277 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19278 })) {
19279 FixBuffer.assign({"=", Separator});
19280 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19281 << /*value*/ 0
19282 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19283 }
19284 }
19285
19286 // We can't use default capture by reference if any captures already specified
19287 // capture by reference.
19288 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19289 return !C.isInitCapture() && C.isReferenceCapture() &&
19290 !C.isThisCapture();
19291 })) {
19292 FixBuffer.assign({"&", Separator});
19293 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19294 << /*reference*/ 1
19295 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19296 }
19297}
19298
19300 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19301 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19302 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19303 // An init-capture is notionally from the context surrounding its
19304 // declaration, but its parent DC is the lambda class.
19305 DeclContext *VarDC = Var->getDeclContext();
19306 DeclContext *DC = CurContext;
19307
19308 // Skip past RequiresExprBodys because they don't constitute function scopes.
19309 while (DC->isRequiresExprBody())
19310 DC = DC->getParent();
19311
19312 // tryCaptureVariable is called every time a DeclRef is formed,
19313 // it can therefore have non-negigible impact on performances.
19314 // For local variables and when there is no capturing scope,
19315 // we can bailout early.
19316 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19317 return true;
19318
19319 // Exception: Function parameters are not tied to the function's DeclContext
19320 // until we enter the function definition. Capturing them anyway would result
19321 // in an out-of-bounds error while traversing DC and its parents.
19322 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
19323 return true;
19324
19325 const auto *VD = dyn_cast<VarDecl>(Var);
19326 if (VD) {
19327 if (VD->isInitCapture())
19328 VarDC = VarDC->getParent();
19329 } else {
19331 }
19332 assert(VD && "Cannot capture a null variable");
19333
19334 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19335 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19336 // We need to sync up the Declaration Context with the
19337 // FunctionScopeIndexToStopAt
19338 if (FunctionScopeIndexToStopAt) {
19339 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19340 unsigned FSIndex = FunctionScopes.size() - 1;
19341 // When we're parsing the lambda parameter list, the current DeclContext is
19342 // NOT the lambda but its parent. So move away the current LSI before
19343 // aligning DC and FunctionScopeIndexToStopAt.
19344 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
19345 FSIndex && LSI && !LSI->AfterParameterList)
19346 --FSIndex;
19347 assert(MaxFunctionScopesIndex <= FSIndex &&
19348 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19349 "FunctionScopes.");
19350 while (FSIndex != MaxFunctionScopesIndex) {
19352 --FSIndex;
19353 }
19354 }
19355
19356 // Capture global variables if it is required to use private copy of this
19357 // variable.
19358 bool IsGlobal = !VD->hasLocalStorage();
19359 if (IsGlobal && !(LangOpts.OpenMP &&
19360 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19361 MaxFunctionScopesIndex)))
19362 return true;
19363
19364 if (isa<VarDecl>(Var))
19365 Var = cast<VarDecl>(Var->getCanonicalDecl());
19366
19367 // Walk up the stack to determine whether we can capture the variable,
19368 // performing the "simple" checks that don't depend on type. We stop when
19369 // we've either hit the declared scope of the variable or find an existing
19370 // capture of that variable. We start from the innermost capturing-entity
19371 // (the DC) and ensure that all intervening capturing-entities
19372 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19373 // declcontext can either capture the variable or have already captured
19374 // the variable.
19375 CaptureType = Var->getType();
19376 DeclRefType = CaptureType.getNonReferenceType();
19377 bool Nested = false;
19378 bool Explicit = (Kind != TryCaptureKind::Implicit);
19379 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19380 do {
19381
19382 LambdaScopeInfo *LSI = nullptr;
19383 if (!FunctionScopes.empty())
19384 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19385 FunctionScopes[FunctionScopesIndex]);
19386
19387 bool IsInScopeDeclarationContext =
19388 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19389
19390 if (LSI && !LSI->AfterParameterList) {
19391 // This allows capturing parameters from a default value which does not
19392 // seems correct
19393 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19394 return true;
19395 }
19396 // If the variable is declared in the current context, there is no need to
19397 // capture it.
19398 if (IsInScopeDeclarationContext &&
19399 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19400 return true;
19401
19402 // Only block literals, captured statements, and lambda expressions can
19403 // capture; other scopes don't work.
19404 DeclContext *ParentDC =
19405 !IsInScopeDeclarationContext
19406 ? DC->getParent()
19407 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19408 BuildAndDiagnose, *this);
19409 // We need to check for the parent *first* because, if we *have*
19410 // private-captured a global variable, we need to recursively capture it in
19411 // intermediate blocks, lambdas, etc.
19412 if (!ParentDC) {
19413 if (IsGlobal) {
19414 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19415 break;
19416 }
19417 return true;
19418 }
19419
19420 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19422
19423 // Check whether we've already captured it.
19424 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19425 DeclRefType)) {
19426 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19427 break;
19428 }
19429
19430 // When evaluating some attributes (like enable_if) we might refer to a
19431 // function parameter appertaining to the same declaration as that
19432 // attribute.
19433 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19434 Parm && Parm->getDeclContext() == DC)
19435 return true;
19436
19437 // If we are instantiating a generic lambda call operator body,
19438 // we do not want to capture new variables. What was captured
19439 // during either a lambdas transformation or initial parsing
19440 // should be used.
19442 if (BuildAndDiagnose) {
19445 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19446 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19447 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19448 buildLambdaCaptureFixit(*this, LSI, Var);
19449 } else
19451 }
19452 return true;
19453 }
19454
19455 // Try to capture variable-length arrays types.
19456 if (Var->getType()->isVariablyModifiedType()) {
19457 // We're going to walk down into the type and look for VLA
19458 // expressions.
19459 QualType QTy = Var->getType();
19460 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19461 QTy = PVD->getOriginalType();
19463 }
19464
19465 if (getLangOpts().OpenMP) {
19466 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19467 // OpenMP private variables should not be captured in outer scope, so
19468 // just break here. Similarly, global variables that are captured in a
19469 // target region should not be captured outside the scope of the region.
19470 if (RSI->CapRegionKind == CR_OpenMP) {
19471 // FIXME: We should support capturing structured bindings in OpenMP.
19472 if (isa<BindingDecl>(Var)) {
19473 if (BuildAndDiagnose) {
19474 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19475 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19476 }
19477 return true;
19478 }
19479 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19480 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19481 // If the variable is private (i.e. not captured) and has variably
19482 // modified type, we still need to capture the type for correct
19483 // codegen in all regions, associated with the construct. Currently,
19484 // it is captured in the innermost captured region only.
19485 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19486 Var->getType()->isVariablyModifiedType()) {
19487 QualType QTy = Var->getType();
19488 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19489 QTy = PVD->getOriginalType();
19490 for (int I = 1,
19491 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19492 I < E; ++I) {
19493 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19494 FunctionScopes[FunctionScopesIndex - I]);
19495 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19496 "Wrong number of captured regions associated with the "
19497 "OpenMP construct.");
19498 captureVariablyModifiedType(Context, QTy, OuterRSI);
19499 }
19500 }
19501 bool IsTargetCap =
19502 IsOpenMPPrivateDecl != OMPC_private &&
19503 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19504 RSI->OpenMPCaptureLevel);
19505 // Do not capture global if it is not privatized in outer regions.
19506 bool IsGlobalCap =
19507 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19508 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19509
19510 // When we detect target captures we are looking from inside the
19511 // target region, therefore we need to propagate the capture from the
19512 // enclosing region. Therefore, the capture is not initially nested.
19513 if (IsTargetCap)
19514 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19515 RSI->OpenMPLevel);
19516
19517 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19518 (IsGlobal && !IsGlobalCap)) {
19519 Nested = !IsTargetCap;
19520 bool HasConst = DeclRefType.isConstQualified();
19521 DeclRefType = DeclRefType.getUnqualifiedType();
19522 // Don't lose diagnostics about assignments to const.
19523 if (HasConst)
19524 DeclRefType.addConst();
19525 CaptureType = Context.getLValueReferenceType(DeclRefType);
19526 break;
19527 }
19528 }
19529 }
19530 }
19532 // No capture-default, and this is not an explicit capture
19533 // so cannot capture this variable.
19534 if (BuildAndDiagnose) {
19535 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19536 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19537 auto *LSI = cast<LambdaScopeInfo>(CSI);
19538 if (LSI->Lambda) {
19539 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19540 buildLambdaCaptureFixit(*this, LSI, Var);
19541 }
19542 // FIXME: If we error out because an outer lambda can not implicitly
19543 // capture a variable that an inner lambda explicitly captures, we
19544 // should have the inner lambda do the explicit capture - because
19545 // it makes for cleaner diagnostics later. This would purely be done
19546 // so that the diagnostic does not misleadingly claim that a variable
19547 // can not be captured by a lambda implicitly even though it is captured
19548 // explicitly. Suggestion:
19549 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19550 // at the function head
19551 // - cache the StartingDeclContext - this must be a lambda
19552 // - captureInLambda in the innermost lambda the variable.
19553 }
19554 return true;
19555 }
19556 Explicit = false;
19557 FunctionScopesIndex--;
19558 if (IsInScopeDeclarationContext)
19559 DC = ParentDC;
19560 } while (!VarDC->Equals(DC));
19561
19562 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19563 // computing the type of the capture at each step, checking type-specific
19564 // requirements, and adding captures if requested.
19565 // If the variable had already been captured previously, we start capturing
19566 // at the lambda nested within that one.
19567 bool Invalid = false;
19568 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19569 ++I) {
19571
19572 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19573 // certain types of variables (unnamed, variably modified types etc.)
19574 // so check for eligibility.
19575 if (!Invalid)
19576 Invalid =
19577 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19578
19579 // After encountering an error, if we're actually supposed to capture, keep
19580 // capturing in nested contexts to suppress any follow-on diagnostics.
19581 if (Invalid && !BuildAndDiagnose)
19582 return true;
19583
19584 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19585 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19586 DeclRefType, Nested, *this, Invalid);
19587 Nested = true;
19588 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19590 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19591 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19592 Nested = true;
19593 } else {
19595 Invalid =
19596 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19597 DeclRefType, Nested, Kind, EllipsisLoc,
19598 /*IsTopScope*/ I == N - 1, *this, Invalid);
19599 Nested = true;
19600 }
19601
19602 if (Invalid && !BuildAndDiagnose)
19603 return true;
19604 }
19605 return Invalid;
19606}
19607
19609 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19610 QualType CaptureType;
19611 QualType DeclRefType;
19612 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19613 /*BuildAndDiagnose=*/true, CaptureType,
19614 DeclRefType, nullptr);
19615}
19616
19618 QualType CaptureType;
19619 QualType DeclRefType;
19620 return !tryCaptureVariable(
19622 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);
19623}
19624
19626 assert(Var && "Null value cannot be captured");
19627
19628 QualType CaptureType;
19629 QualType DeclRefType;
19630
19631 // Determine whether we can capture this variable.
19633 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
19634 nullptr))
19635 return QualType();
19636
19637 return DeclRefType;
19638}
19639
19640namespace {
19641// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19642// The produced TemplateArgumentListInfo* points to data stored within this
19643// object, so should only be used in contexts where the pointer will not be
19644// used after the CopiedTemplateArgs object is destroyed.
19645class CopiedTemplateArgs {
19646 bool HasArgs;
19647 TemplateArgumentListInfo TemplateArgStorage;
19648public:
19649 template<typename RefExpr>
19650 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19651 if (HasArgs)
19652 E->copyTemplateArgumentsInto(TemplateArgStorage);
19653 }
19654 operator TemplateArgumentListInfo*()
19655#ifdef __has_cpp_attribute
19656#if __has_cpp_attribute(clang::lifetimebound)
19657 [[clang::lifetimebound]]
19658#endif
19659#endif
19660 {
19661 return HasArgs ? &TemplateArgStorage : nullptr;
19662 }
19663};
19664}
19665
19666/// Walk the set of potential results of an expression and mark them all as
19667/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19668///
19669/// \return A new expression if we found any potential results, ExprEmpty() if
19670/// not, and ExprError() if we diagnosed an error.
19672 NonOdrUseReason NOUR) {
19673 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19674 // an object that satisfies the requirements for appearing in a
19675 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19676 // is immediately applied." This function handles the lvalue-to-rvalue
19677 // conversion part.
19678 //
19679 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19680 // transform it into the relevant kind of non-odr-use node and rebuild the
19681 // tree of nodes leading to it.
19682 //
19683 // This is a mini-TreeTransform that only transforms a restricted subset of
19684 // nodes (and only certain operands of them).
19685
19686 // Rebuild a subexpression.
19687 auto Rebuild = [&](Expr *Sub) {
19688 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19689 };
19690
19691 // Check whether a potential result satisfies the requirements of NOUR.
19692 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19693 // Any entity other than a VarDecl is always odr-used whenever it's named
19694 // in a potentially-evaluated expression.
19695 auto *VD = dyn_cast<VarDecl>(D);
19696 if (!VD)
19697 return true;
19698
19699 // C++2a [basic.def.odr]p4:
19700 // A variable x whose name appears as a potentially-evalauted expression
19701 // e is odr-used by e unless
19702 // -- x is a reference that is usable in constant expressions, or
19703 // -- x is a variable of non-reference type that is usable in constant
19704 // expressions and has no mutable subobjects, and e is an element of
19705 // the set of potential results of an expression of
19706 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19707 // conversion is applied, or
19708 // -- x is a variable of non-reference type, and e is an element of the
19709 // set of potential results of a discarded-value expression to which
19710 // the lvalue-to-rvalue conversion is not applied
19711 //
19712 // We check the first bullet and the "potentially-evaluated" condition in
19713 // BuildDeclRefExpr. We check the type requirements in the second bullet
19714 // in CheckLValueToRValueConversionOperand below.
19715 switch (NOUR) {
19716 case NOUR_None:
19717 case NOUR_Unevaluated:
19718 llvm_unreachable("unexpected non-odr-use-reason");
19719
19720 case NOUR_Constant:
19721 // Constant references were handled when they were built.
19722 if (VD->getType()->isReferenceType())
19723 return true;
19724 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19725 if (RD->hasDefinition() && RD->hasMutableFields())
19726 return true;
19727 if (!VD->isUsableInConstantExpressions(S.Context))
19728 return true;
19729 break;
19730
19731 case NOUR_Discarded:
19732 if (VD->getType()->isReferenceType())
19733 return true;
19734 break;
19735 }
19736 return false;
19737 };
19738
19739 // Check whether this expression may be odr-used in CUDA/HIP.
19740 auto MaybeCUDAODRUsed = [&]() -> bool {
19741 if (!S.LangOpts.CUDA)
19742 return false;
19743 LambdaScopeInfo *LSI = S.getCurLambda();
19744 if (!LSI)
19745 return false;
19746 auto *DRE = dyn_cast<DeclRefExpr>(E);
19747 if (!DRE)
19748 return false;
19749 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
19750 if (!VD)
19751 return false;
19752 return LSI->CUDAPotentialODRUsedVars.count(VD);
19753 };
19754
19755 // Mark that this expression does not constitute an odr-use.
19756 auto MarkNotOdrUsed = [&] {
19757 if (!MaybeCUDAODRUsed()) {
19758 S.MaybeODRUseExprs.remove(E);
19759 if (LambdaScopeInfo *LSI = S.getCurLambda())
19760 LSI->markVariableExprAsNonODRUsed(E);
19761 }
19762 };
19763
19764 // C++2a [basic.def.odr]p2:
19765 // The set of potential results of an expression e is defined as follows:
19766 switch (E->getStmtClass()) {
19767 // -- If e is an id-expression, ...
19768 case Expr::DeclRefExprClass: {
19769 auto *DRE = cast<DeclRefExpr>(E);
19770 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19771 break;
19772
19773 // Rebuild as a non-odr-use DeclRefExpr.
19774 MarkNotOdrUsed();
19775 return DeclRefExpr::Create(
19776 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19777 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19778 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19779 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19780 }
19781
19782 case Expr::FunctionParmPackExprClass: {
19783 auto *FPPE = cast<FunctionParmPackExpr>(E);
19784 // If any of the declarations in the pack is odr-used, then the expression
19785 // as a whole constitutes an odr-use.
19786 for (ValueDecl *D : *FPPE)
19787 if (IsPotentialResultOdrUsed(D))
19788 return ExprEmpty();
19789
19790 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19791 // nothing cares about whether we marked this as an odr-use, but it might
19792 // be useful for non-compiler tools.
19793 MarkNotOdrUsed();
19794 break;
19795 }
19796
19797 // -- If e is a subscripting operation with an array operand...
19798 case Expr::ArraySubscriptExprClass: {
19799 auto *ASE = cast<ArraySubscriptExpr>(E);
19800 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19801 if (!OldBase->getType()->isArrayType())
19802 break;
19803 ExprResult Base = Rebuild(OldBase);
19804 if (!Base.isUsable())
19805 return Base;
19806 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19807 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19808 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19809 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19810 ASE->getRBracketLoc());
19811 }
19812
19813 case Expr::MemberExprClass: {
19814 auto *ME = cast<MemberExpr>(E);
19815 // -- If e is a class member access expression [...] naming a non-static
19816 // data member...
19817 if (isa<FieldDecl>(ME->getMemberDecl())) {
19818 ExprResult Base = Rebuild(ME->getBase());
19819 if (!Base.isUsable())
19820 return Base;
19821 return MemberExpr::Create(
19822 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19823 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19824 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19825 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19826 ME->getObjectKind(), ME->isNonOdrUse());
19827 }
19828
19829 if (ME->getMemberDecl()->isCXXInstanceMember())
19830 break;
19831
19832 // -- If e is a class member access expression naming a static data member,
19833 // ...
19834 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19835 break;
19836
19837 // Rebuild as a non-odr-use MemberExpr.
19838 MarkNotOdrUsed();
19839 return MemberExpr::Create(
19840 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19841 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19842 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19843 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19844 }
19845
19846 case Expr::BinaryOperatorClass: {
19847 auto *BO = cast<BinaryOperator>(E);
19848 Expr *LHS = BO->getLHS();
19849 Expr *RHS = BO->getRHS();
19850 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19851 if (BO->getOpcode() == BO_PtrMemD) {
19852 ExprResult Sub = Rebuild(LHS);
19853 if (!Sub.isUsable())
19854 return Sub;
19855 BO->setLHS(Sub.get());
19856 // -- If e is a comma expression, ...
19857 } else if (BO->getOpcode() == BO_Comma) {
19858 ExprResult Sub = Rebuild(RHS);
19859 if (!Sub.isUsable())
19860 return Sub;
19861 BO->setRHS(Sub.get());
19862 } else {
19863 break;
19864 }
19865 return ExprResult(BO);
19866 }
19867
19868 // -- If e has the form (e1)...
19869 case Expr::ParenExprClass: {
19870 auto *PE = cast<ParenExpr>(E);
19871 ExprResult Sub = Rebuild(PE->getSubExpr());
19872 if (!Sub.isUsable())
19873 return Sub;
19874 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19875 }
19876
19877 // -- If e is a glvalue conditional expression, ...
19878 // We don't apply this to a binary conditional operator. FIXME: Should we?
19879 case Expr::ConditionalOperatorClass: {
19880 auto *CO = cast<ConditionalOperator>(E);
19881 ExprResult LHS = Rebuild(CO->getLHS());
19882 if (LHS.isInvalid())
19883 return ExprError();
19884 ExprResult RHS = Rebuild(CO->getRHS());
19885 if (RHS.isInvalid())
19886 return ExprError();
19887 if (!LHS.isUsable() && !RHS.isUsable())
19888 return ExprEmpty();
19889 if (!LHS.isUsable())
19890 LHS = CO->getLHS();
19891 if (!RHS.isUsable())
19892 RHS = CO->getRHS();
19893 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19894 CO->getCond(), LHS.get(), RHS.get());
19895 }
19896
19897 // [Clang extension]
19898 // -- If e has the form __extension__ e1...
19899 case Expr::UnaryOperatorClass: {
19900 auto *UO = cast<UnaryOperator>(E);
19901 if (UO->getOpcode() != UO_Extension)
19902 break;
19903 ExprResult Sub = Rebuild(UO->getSubExpr());
19904 if (!Sub.isUsable())
19905 return Sub;
19906 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19907 Sub.get());
19908 }
19909
19910 // [Clang extension]
19911 // -- If e has the form _Generic(...), the set of potential results is the
19912 // union of the sets of potential results of the associated expressions.
19913 case Expr::GenericSelectionExprClass: {
19914 auto *GSE = cast<GenericSelectionExpr>(E);
19915
19916 SmallVector<Expr *, 4> AssocExprs;
19917 bool AnyChanged = false;
19918 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19919 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19920 if (AssocExpr.isInvalid())
19921 return ExprError();
19922 if (AssocExpr.isUsable()) {
19923 AssocExprs.push_back(AssocExpr.get());
19924 AnyChanged = true;
19925 } else {
19926 AssocExprs.push_back(OrigAssocExpr);
19927 }
19928 }
19929
19930 void *ExOrTy = nullptr;
19931 bool IsExpr = GSE->isExprPredicate();
19932 if (IsExpr)
19933 ExOrTy = GSE->getControllingExpr();
19934 else
19935 ExOrTy = GSE->getControllingType();
19936 return AnyChanged ? S.CreateGenericSelectionExpr(
19937 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19938 GSE->getRParenLoc(), IsExpr, ExOrTy,
19939 GSE->getAssocTypeSourceInfos(), AssocExprs)
19940 : ExprEmpty();
19941 }
19942
19943 // [Clang extension]
19944 // -- If e has the form __builtin_choose_expr(...), the set of potential
19945 // results is the union of the sets of potential results of the
19946 // second and third subexpressions.
19947 case Expr::ChooseExprClass: {
19948 auto *CE = cast<ChooseExpr>(E);
19949
19950 ExprResult LHS = Rebuild(CE->getLHS());
19951 if (LHS.isInvalid())
19952 return ExprError();
19953
19954 ExprResult RHS = Rebuild(CE->getLHS());
19955 if (RHS.isInvalid())
19956 return ExprError();
19957
19958 if (!LHS.get() && !RHS.get())
19959 return ExprEmpty();
19960 if (!LHS.isUsable())
19961 LHS = CE->getLHS();
19962 if (!RHS.isUsable())
19963 RHS = CE->getRHS();
19964
19965 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19966 RHS.get(), CE->getRParenLoc());
19967 }
19968
19969 // Step through non-syntactic nodes.
19970 case Expr::ConstantExprClass: {
19971 auto *CE = cast<ConstantExpr>(E);
19972 ExprResult Sub = Rebuild(CE->getSubExpr());
19973 if (!Sub.isUsable())
19974 return Sub;
19975 return ConstantExpr::Create(S.Context, Sub.get());
19976 }
19977
19978 // We could mostly rely on the recursive rebuilding to rebuild implicit
19979 // casts, but not at the top level, so rebuild them here.
19980 case Expr::ImplicitCastExprClass: {
19981 auto *ICE = cast<ImplicitCastExpr>(E);
19982 // Only step through the narrow set of cast kinds we expect to encounter.
19983 // Anything else suggests we've left the region in which potential results
19984 // can be found.
19985 switch (ICE->getCastKind()) {
19986 case CK_NoOp:
19987 case CK_DerivedToBase:
19988 case CK_UncheckedDerivedToBase: {
19989 ExprResult Sub = Rebuild(ICE->getSubExpr());
19990 if (!Sub.isUsable())
19991 return Sub;
19992 CXXCastPath Path(ICE->path());
19993 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19994 ICE->getValueKind(), &Path);
19995 }
19996
19997 default:
19998 break;
19999 }
20000 break;
20001 }
20002
20003 default:
20004 break;
20005 }
20006
20007 // Can't traverse through this node. Nothing to do.
20008 return ExprEmpty();
20009}
20010
20012 // Check whether the operand is or contains an object of non-trivial C union
20013 // type.
20014 if (E->getType().isVolatileQualified() &&
20020
20021 // C++2a [basic.def.odr]p4:
20022 // [...] an expression of non-volatile-qualified non-class type to which
20023 // the lvalue-to-rvalue conversion is applied [...]
20024 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20025 return E;
20026
20029 if (Result.isInvalid())
20030 return ExprError();
20031 return Result.get() ? Result : E;
20032}
20033
20035 if (!Res.isUsable())
20036 return Res;
20037
20038 // If a constant-expression is a reference to a variable where we delay
20039 // deciding whether it is an odr-use, just assume we will apply the
20040 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20041 // (a non-type template argument), we have special handling anyway.
20043}
20044
20046 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20047 // call.
20048 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20049 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20050
20051 for (Expr *E : LocalMaybeODRUseExprs) {
20052 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20053 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20054 DRE->getLocation(), *this);
20055 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20056 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20057 *this);
20058 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20059 for (ValueDecl *VD : *FP)
20060 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20061 } else {
20062 llvm_unreachable("Unexpected expression");
20063 }
20064 }
20065
20066 assert(MaybeODRUseExprs.empty() &&
20067 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20068}
20069
20071 ValueDecl *Var, Expr *E) {
20073 if (!VD)
20074 return;
20075
20076 const bool RefersToEnclosingScope =
20077 (SemaRef.CurContext != VD->getDeclContext() &&
20079 if (RefersToEnclosingScope) {
20080 LambdaScopeInfo *const LSI =
20081 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20082 if (LSI && (!LSI->CallOperator ||
20083 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20084 // If a variable could potentially be odr-used, defer marking it so
20085 // until we finish analyzing the full expression for any
20086 // lvalue-to-rvalue
20087 // or discarded value conversions that would obviate odr-use.
20088 // Add it to the list of potential captures that will be analyzed
20089 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20090 // unless the variable is a reference that was initialized by a constant
20091 // expression (this will never need to be captured or odr-used).
20092 //
20093 // FIXME: We can simplify this a lot after implementing P0588R1.
20094 assert(E && "Capture variable should be used in an expression.");
20095 if (!Var->getType()->isReferenceType() ||
20098 }
20099 }
20100}
20101
20103 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20104 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20105 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20107 "Invalid Expr argument to DoMarkVarDeclReferenced");
20108 Var->setReferenced();
20109
20110 if (Var->isInvalidDecl())
20111 return;
20112
20113 auto *MSI = Var->getMemberSpecializationInfo();
20114 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20116
20117 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20118 bool UsableInConstantExpr =
20120
20121 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
20122 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
20123 }
20124
20125 // C++20 [expr.const]p12:
20126 // A variable [...] is needed for constant evaluation if it is [...] a
20127 // variable whose name appears as a potentially constant evaluated
20128 // expression that is either a contexpr variable or is of non-volatile
20129 // const-qualified integral type or of reference type
20130 bool NeededForConstantEvaluation =
20131 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20132
20133 bool NeedDefinition =
20134 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20135 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20136 Var->getType()->isUndeducedType());
20137
20139 "Can't instantiate a partial template specialization.");
20140
20141 // If this might be a member specialization of a static data member, check
20142 // the specialization is visible. We already did the checks for variable
20143 // template specializations when we created them.
20144 if (NeedDefinition && TSK != TSK_Undeclared &&
20147
20148 // Perform implicit instantiation of static data members, static data member
20149 // templates of class templates, and variable template specializations. Delay
20150 // instantiations of variable templates, except for those that could be used
20151 // in a constant expression.
20152 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20153 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20154 // instantiation declaration if a variable is usable in a constant
20155 // expression (among other cases).
20156 bool TryInstantiating =
20158 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20159
20160 if (TryInstantiating) {
20161 SourceLocation PointOfInstantiation =
20162 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20163 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20164 if (FirstInstantiation) {
20165 PointOfInstantiation = Loc;
20166 if (MSI)
20167 MSI->setPointOfInstantiation(PointOfInstantiation);
20168 // FIXME: Notify listener.
20169 else
20170 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20171 }
20172
20173 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20174 // Do not defer instantiations of variables that could be used in a
20175 // constant expression.
20176 // The type deduction also needs a complete initializer.
20177 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20178 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20179 });
20180
20181 // The size of an incomplete array type can be updated by
20182 // instantiating the initializer. The DeclRefExpr's type should be
20183 // updated accordingly too, or users of it would be confused!
20184 if (E)
20186
20187 // Re-set the member to trigger a recomputation of the dependence bits
20188 // for the expression.
20189 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20190 DRE->setDecl(DRE->getDecl());
20191 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20192 ME->setMemberDecl(ME->getMemberDecl());
20193 } else if (FirstInstantiation) {
20195 .push_back(std::make_pair(Var, PointOfInstantiation));
20196 } else {
20197 bool Inserted = false;
20198 for (auto &I : SemaRef.SavedPendingInstantiations) {
20199 auto Iter = llvm::find_if(
20200 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20201 return P.first == Var;
20202 });
20203 if (Iter != I.end()) {
20204 SemaRef.PendingInstantiations.push_back(*Iter);
20205 I.erase(Iter);
20206 Inserted = true;
20207 break;
20208 }
20209 }
20210
20211 // FIXME: For a specialization of a variable template, we don't
20212 // distinguish between "declaration and type implicitly instantiated"
20213 // and "implicit instantiation of definition requested", so we have
20214 // no direct way to avoid enqueueing the pending instantiation
20215 // multiple times.
20216 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20218 .push_back(std::make_pair(Var, PointOfInstantiation));
20219 }
20220 }
20221 }
20222
20223 // C++2a [basic.def.odr]p4:
20224 // A variable x whose name appears as a potentially-evaluated expression e
20225 // is odr-used by e unless
20226 // -- x is a reference that is usable in constant expressions
20227 // -- x is a variable of non-reference type that is usable in constant
20228 // expressions and has no mutable subobjects [FIXME], and e is an
20229 // element of the set of potential results of an expression of
20230 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20231 // conversion is applied
20232 // -- x is a variable of non-reference type, and e is an element of the set
20233 // of potential results of a discarded-value expression to which the
20234 // lvalue-to-rvalue conversion is not applied [FIXME]
20235 //
20236 // We check the first part of the second bullet here, and
20237 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20238 // FIXME: To get the third bullet right, we need to delay this even for
20239 // variables that are not usable in constant expressions.
20240
20241 // If we already know this isn't an odr-use, there's nothing more to do.
20242 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20243 if (DRE->isNonOdrUse())
20244 return;
20245 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20246 if (ME->isNonOdrUse())
20247 return;
20248
20249 switch (OdrUse) {
20250 case OdrUseContext::None:
20251 // In some cases, a variable may not have been marked unevaluated, if it
20252 // appears in a defaukt initializer.
20253 assert((!E || isa<FunctionParmPackExpr>(E) ||
20255 "missing non-odr-use marking for unevaluated decl ref");
20256 break;
20257
20258 case OdrUseContext::FormallyOdrUsed:
20259 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20260 // behavior.
20261 break;
20262
20263 case OdrUseContext::Used:
20264 // If we might later find that this expression isn't actually an odr-use,
20265 // delay the marking.
20267 SemaRef.MaybeODRUseExprs.insert(E);
20268 else
20269 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20270 break;
20271
20272 case OdrUseContext::Dependent:
20273 // If this is a dependent context, we don't need to mark variables as
20274 // odr-used, but we may still need to track them for lambda capture.
20275 // FIXME: Do we also need to do this inside dependent typeid expressions
20276 // (which are modeled as unevaluated at this point)?
20277 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20278 break;
20279 }
20280}
20281
20283 BindingDecl *BD, Expr *E) {
20284 BD->setReferenced();
20285
20286 if (BD->isInvalidDecl())
20287 return;
20288
20289 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20290 if (OdrUse == OdrUseContext::Used) {
20291 QualType CaptureType, DeclRefType;
20293 /*EllipsisLoc*/ SourceLocation(),
20294 /*BuildAndDiagnose*/ true, CaptureType,
20295 DeclRefType,
20296 /*FunctionScopeIndexToStopAt*/ nullptr);
20297 } else if (OdrUse == OdrUseContext::Dependent) {
20298 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20299 }
20300}
20301
20303 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20304}
20305
20306// C++ [temp.dep.expr]p3:
20307// An id-expression is type-dependent if it contains:
20308// - an identifier associated by name lookup with an entity captured by copy
20309// in a lambda-expression that has an explicit object parameter whose type
20310// is dependent ([dcl.fct]),
20312 Sema &SemaRef, ValueDecl *D, Expr *E) {
20313 auto *ID = dyn_cast<DeclRefExpr>(E);
20314 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20315 return;
20316
20317 // If any enclosing lambda with a dependent explicit object parameter either
20318 // explicitly captures the variable by value, or has a capture default of '='
20319 // and does not capture the variable by reference, then the type of the DRE
20320 // is dependent on the type of that lambda's explicit object parameter.
20321 auto IsDependent = [&]() {
20322 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
20323 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
20324 if (!LSI)
20325 continue;
20326
20327 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
20328 LSI->AfterParameterList)
20329 return false;
20330
20331 const auto *MD = LSI->CallOperator;
20332 if (MD->getType().isNull())
20333 continue;
20334
20335 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20336 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20337 !Ty->getParamType(0)->isDependentType())
20338 continue;
20339
20340 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
20341 if (C->isCopyCapture())
20342 return true;
20343 continue;
20344 }
20345
20346 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20347 return true;
20348 }
20349 return false;
20350 }();
20351
20352 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20353 IsDependent, SemaRef.getASTContext());
20354}
20355
20356static void
20358 bool MightBeOdrUse,
20359 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20362
20363 if (SemaRef.getLangOpts().OpenACC)
20364 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20365
20366 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20368 if (SemaRef.getLangOpts().CPlusPlus)
20370 Var, E);
20371 return;
20372 }
20373
20374 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20376 if (SemaRef.getLangOpts().CPlusPlus)
20378 Decl, E);
20379 return;
20380 }
20381 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20382
20383 // If this is a call to a method via a cast, also mark the method in the
20384 // derived class used in case codegen can devirtualize the call.
20385 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20386 if (!ME)
20387 return;
20388 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20389 if (!MD)
20390 return;
20391 // Only attempt to devirtualize if this is truly a virtual call.
20392 bool IsVirtualCall = MD->isVirtual() &&
20394 if (!IsVirtualCall)
20395 return;
20396
20397 // If it's possible to devirtualize the call, mark the called function
20398 // referenced.
20400 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20401 if (DM)
20402 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20403}
20404
20406 // [basic.def.odr] (CWG 1614)
20407 // A function is named by an expression or conversion [...]
20408 // unless it is a pure virtual function and either the expression is not an
20409 // id-expression naming the function with an explicitly qualified name or
20410 // the expression forms a pointer to member
20411 bool OdrUse = true;
20412 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20413 if (Method->isVirtual() &&
20414 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20415 OdrUse = false;
20416
20417 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20421 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20422 !FD->isDependentContext())
20423 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20424 }
20425 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20427}
20428
20430 // C++11 [basic.def.odr]p2:
20431 // A non-overloaded function whose name appears as a potentially-evaluated
20432 // expression or a member of a set of candidate functions, if selected by
20433 // overload resolution when referred to from a potentially-evaluated
20434 // expression, is odr-used, unless it is a pure virtual function and its
20435 // name is not explicitly qualified.
20436 bool MightBeOdrUse = true;
20438 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20439 if (Method->isPureVirtual())
20440 MightBeOdrUse = false;
20441 }
20442 SourceLocation Loc =
20443 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20444 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20446}
20447
20453
20454/// Perform marking for a reference to an arbitrary declaration. It
20455/// marks the declaration referenced, and performs odr-use checking for
20456/// functions and variables. This method should not be used when building a
20457/// normal expression which refers to a variable.
20459 bool MightBeOdrUse) {
20460 if (MightBeOdrUse) {
20461 if (auto *VD = dyn_cast<VarDecl>(D)) {
20462 MarkVariableReferenced(Loc, VD);
20463 return;
20464 }
20465 }
20466 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20467 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20468 return;
20469 }
20470 D->setReferenced();
20471}
20472
20473namespace {
20474 // Mark all of the declarations used by a type as referenced.
20475 // FIXME: Not fully implemented yet! We need to have a better understanding
20476 // of when we're entering a context we should not recurse into.
20477 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20478 // TreeTransforms rebuilding the type in a new context. Rather than
20479 // duplicating the TreeTransform logic, we should consider reusing it here.
20480 // Currently that causes problems when rebuilding LambdaExprs.
20481class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20482 Sema &S;
20483 SourceLocation Loc;
20484
20485public:
20486 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20487
20488 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20489};
20490}
20491
20492bool MarkReferencedDecls::TraverseTemplateArgument(
20493 const TemplateArgument &Arg) {
20494 {
20495 // A non-type template argument is a constant-evaluated context.
20496 EnterExpressionEvaluationContext Evaluated(
20499 if (Decl *D = Arg.getAsDecl())
20500 S.MarkAnyDeclReferenced(Loc, D, true);
20501 } else if (Arg.getKind() == TemplateArgument::Expression) {
20503 }
20504 }
20505
20507}
20508
20510 MarkReferencedDecls Marker(*this, Loc);
20511 Marker.TraverseType(T);
20512}
20513
20514namespace {
20515/// Helper class that marks all of the declarations referenced by
20516/// potentially-evaluated subexpressions as "referenced".
20517class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20518public:
20519 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20520 bool SkipLocalVariables;
20522
20523 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20525 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20526
20527 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20529 }
20530
20531 void Visit(Expr *E) {
20532 if (llvm::is_contained(StopAt, E))
20533 return;
20534 Inherited::Visit(E);
20535 }
20536
20537 void VisitConstantExpr(ConstantExpr *E) {
20538 // Don't mark declarations within a ConstantExpression, as this expression
20539 // will be evaluated and folded to a value.
20540 }
20541
20542 void VisitDeclRefExpr(DeclRefExpr *E) {
20543 // If we were asked not to visit local variables, don't.
20544 if (SkipLocalVariables) {
20545 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20546 if (VD->hasLocalStorage())
20547 return;
20548 }
20549
20550 // FIXME: This can trigger the instantiation of the initializer of a
20551 // variable, which can cause the expression to become value-dependent
20552 // or error-dependent. Do we need to propagate the new dependence bits?
20554 }
20555
20556 void VisitMemberExpr(MemberExpr *E) {
20558 Visit(E->getBase());
20559 }
20560};
20561} // namespace
20562
20564 bool SkipLocalVariables,
20565 ArrayRef<const Expr*> StopAt) {
20566 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20567}
20568
20569/// Emit a diagnostic when statements are reachable.
20570/// FIXME: check for reachability even in expressions for which we don't build a
20571/// CFG (eg, in the initializer of a global or in a constant expression).
20572/// For example,
20573/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20575 const PartialDiagnostic &PD) {
20576 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20577 if (!FunctionScopes.empty())
20578 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20579 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20580 return true;
20581 }
20582
20583 // The initializer of a constexpr variable or of the first declaration of a
20584 // static data member is not syntactically a constant evaluated constant,
20585 // but nonetheless is always required to be a constant expression, so we
20586 // can skip diagnosing.
20587 // FIXME: Using the mangling context here is a hack.
20588 if (auto *VD = dyn_cast_or_null<VarDecl>(
20589 ExprEvalContexts.back().ManglingContextDecl)) {
20590 if (VD->isConstexpr() ||
20591 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20592 return false;
20593 // FIXME: For any other kind of variable, we should build a CFG for its
20594 // initializer and check whether the context in question is reachable.
20595 }
20596
20597 Diag(Loc, PD);
20598 return true;
20599}
20600
20601/// Emit a diagnostic that describes an effect on the run-time behavior
20602/// of the program being compiled.
20603///
20604/// This routine emits the given diagnostic when the code currently being
20605/// type-checked is "potentially evaluated", meaning that there is a
20606/// possibility that the code will actually be executable. Code in sizeof()
20607/// expressions, code used only during overload resolution, etc., are not
20608/// potentially evaluated. This routine will suppress such diagnostics or,
20609/// in the absolutely nutty case of potentially potentially evaluated
20610/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20611/// later.
20612///
20613/// This routine should be used for all diagnostics that describe the run-time
20614/// behavior of a program, such as passing a non-POD value through an ellipsis.
20615/// Failure to do so will likely result in spurious diagnostics or failures
20616/// during overload resolution or within sizeof/alignof/typeof/typeid.
20618 const PartialDiagnostic &PD) {
20619
20620 if (ExprEvalContexts.back().isDiscardedStatementContext())
20621 return false;
20622
20623 switch (ExprEvalContexts.back().Context) {
20628 // The argument will never be evaluated, so don't complain.
20629 break;
20630
20633 // Relevant diagnostics should be produced by constant evaluation.
20634 break;
20635
20638 return DiagIfReachable(Loc, Stmts, PD);
20639 }
20640
20641 return false;
20642}
20643
20645 const PartialDiagnostic &PD) {
20646 return DiagRuntimeBehavior(
20647 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
20648 PD);
20649}
20650
20652 CallExpr *CE, FunctionDecl *FD) {
20653 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20654 return false;
20655
20656 // If we're inside a decltype's expression, don't check for a valid return
20657 // type or construct temporaries until we know whether this is the last call.
20658 if (ExprEvalContexts.back().ExprContext ==
20660 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20661 return false;
20662 }
20663
20664 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20665 FunctionDecl *FD;
20666 CallExpr *CE;
20667
20668 public:
20669 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20670 : FD(FD), CE(CE) { }
20671
20672 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20673 if (!FD) {
20674 S.Diag(Loc, diag::err_call_incomplete_return)
20675 << T << CE->getSourceRange();
20676 return;
20677 }
20678
20679 S.Diag(Loc, diag::err_call_function_incomplete_return)
20680 << CE->getSourceRange() << FD << T;
20681 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20682 << FD->getDeclName();
20683 }
20684 } Diagnoser(FD, CE);
20685
20686 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20687 return true;
20688
20689 return false;
20690}
20691
20692// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20693// will prevent this condition from triggering, which is what we want.
20695 SourceLocation Loc;
20696
20697 unsigned diagnostic = diag::warn_condition_is_assignment;
20698 bool IsOrAssign = false;
20699
20700 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20701 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20702 return;
20703
20704 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20705
20706 // Greylist some idioms by putting them into a warning subcategory.
20707 if (ObjCMessageExpr *ME
20708 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20709 Selector Sel = ME->getSelector();
20710
20711 // self = [<foo> init...]
20712 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20713 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20714
20715 // <foo> = [<bar> nextObject]
20716 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20717 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20718 }
20719
20720 Loc = Op->getOperatorLoc();
20721 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20722 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20723 return;
20724
20725 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20726 Loc = Op->getOperatorLoc();
20727 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20728 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20729 else {
20730 // Not an assignment.
20731 return;
20732 }
20733
20734 Diag(Loc, diagnostic) << E->getSourceRange();
20735
20738 Diag(Loc, diag::note_condition_assign_silence)
20740 << FixItHint::CreateInsertion(Close, ")");
20741
20742 if (IsOrAssign)
20743 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20744 << FixItHint::CreateReplacement(Loc, "!=");
20745 else
20746 Diag(Loc, diag::note_condition_assign_to_comparison)
20747 << FixItHint::CreateReplacement(Loc, "==");
20748}
20749
20751 // Don't warn if the parens came from a macro.
20752 SourceLocation parenLoc = ParenE->getBeginLoc();
20753 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20754 return;
20755 // Don't warn for dependent expressions.
20756 if (ParenE->isTypeDependent())
20757 return;
20758
20759 Expr *E = ParenE->IgnoreParens();
20760 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
20761 return;
20762
20763 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20764 if (opE->getOpcode() == BO_EQ &&
20765 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20766 == Expr::MLV_Valid) {
20767 SourceLocation Loc = opE->getOperatorLoc();
20768
20769 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20770 SourceRange ParenERange = ParenE->getSourceRange();
20771 Diag(Loc, diag::note_equality_comparison_silence)
20772 << FixItHint::CreateRemoval(ParenERange.getBegin())
20773 << FixItHint::CreateRemoval(ParenERange.getEnd());
20774 Diag(Loc, diag::note_equality_comparison_to_assign)
20775 << FixItHint::CreateReplacement(Loc, "=");
20776 }
20777}
20778
20780 bool IsConstexpr) {
20782 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20784
20785 ExprResult result = CheckPlaceholderExpr(E);
20786 if (result.isInvalid()) return ExprError();
20787 E = result.get();
20788
20789 if (!E->isTypeDependent()) {
20790 if (getLangOpts().CPlusPlus)
20791 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20792
20794 if (ERes.isInvalid())
20795 return ExprError();
20796 E = ERes.get();
20797
20798 QualType T = E->getType();
20799 if (!T->isScalarType()) { // C99 6.8.4.1p1
20800 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20801 << T << E->getSourceRange();
20802 return ExprError();
20803 }
20804 CheckBoolLikeConversion(E, Loc);
20805 }
20806
20807 return E;
20808}
20809
20811 Expr *SubExpr, ConditionKind CK,
20812 bool MissingOK) {
20813 // MissingOK indicates whether having no condition expression is valid
20814 // (for loop) or invalid (e.g. while loop).
20815 if (!SubExpr)
20816 return MissingOK ? ConditionResult() : ConditionError();
20817
20819 switch (CK) {
20821 Cond = CheckBooleanCondition(Loc, SubExpr);
20822 break;
20823
20825 // Note: this might produce a FullExpr
20826 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20827 break;
20828
20830 Cond = CheckSwitchCondition(Loc, SubExpr);
20831 break;
20832 }
20833 if (Cond.isInvalid()) {
20834 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20835 {SubExpr}, PreferredConditionType(CK));
20836 if (!Cond.get())
20837 return ConditionError();
20838 } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))
20839 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
20840
20841 if (!Cond.isUsable())
20842 return ConditionError();
20843
20844 return ConditionResult(*this, nullptr, Cond,
20846}
20847
20848namespace {
20849 /// A visitor for rebuilding a call to an __unknown_any expression
20850 /// to have an appropriate type.
20851 struct RebuildUnknownAnyFunction
20852 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20853
20854 Sema &S;
20855
20856 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20857
20858 ExprResult VisitStmt(Stmt *S) {
20859 llvm_unreachable("unexpected statement!");
20860 }
20861
20862 ExprResult VisitExpr(Expr *E) {
20863 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20864 << E->getSourceRange();
20865 return ExprError();
20866 }
20867
20868 /// Rebuild an expression which simply semantically wraps another
20869 /// expression which it shares the type and value kind of.
20870 template <class T> ExprResult rebuildSugarExpr(T *E) {
20871 ExprResult SubResult = Visit(E->getSubExpr());
20872 if (SubResult.isInvalid()) return ExprError();
20873
20874 Expr *SubExpr = SubResult.get();
20875 E->setSubExpr(SubExpr);
20876 E->setType(SubExpr->getType());
20877 E->setValueKind(SubExpr->getValueKind());
20878 assert(E->getObjectKind() == OK_Ordinary);
20879 return E;
20880 }
20881
20882 ExprResult VisitParenExpr(ParenExpr *E) {
20883 return rebuildSugarExpr(E);
20884 }
20885
20886 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20887 return rebuildSugarExpr(E);
20888 }
20889
20890 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20891 ExprResult SubResult = Visit(E->getSubExpr());
20892 if (SubResult.isInvalid()) return ExprError();
20893
20894 Expr *SubExpr = SubResult.get();
20895 E->setSubExpr(SubExpr);
20896 E->setType(S.Context.getPointerType(SubExpr->getType()));
20897 assert(E->isPRValue());
20898 assert(E->getObjectKind() == OK_Ordinary);
20899 return E;
20900 }
20901
20902 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20903 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20904
20905 E->setType(VD->getType());
20906
20907 assert(E->isPRValue());
20908 if (S.getLangOpts().CPlusPlus &&
20909 !(isa<CXXMethodDecl>(VD) &&
20910 cast<CXXMethodDecl>(VD)->isInstance()))
20912
20913 return E;
20914 }
20915
20916 ExprResult VisitMemberExpr(MemberExpr *E) {
20917 return resolveDecl(E, E->getMemberDecl());
20918 }
20919
20920 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20921 return resolveDecl(E, E->getDecl());
20922 }
20923 };
20924}
20925
20926/// Given a function expression of unknown-any type, try to rebuild it
20927/// to have a function type.
20929 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20930 if (Result.isInvalid()) return ExprError();
20931 return S.DefaultFunctionArrayConversion(Result.get());
20932}
20933
20934namespace {
20935 /// A visitor for rebuilding an expression of type __unknown_anytype
20936 /// into one which resolves the type directly on the referring
20937 /// expression. Strict preservation of the original source
20938 /// structure is not a goal.
20939 struct RebuildUnknownAnyExpr
20940 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20941
20942 Sema &S;
20943
20944 /// The current destination type.
20945 QualType DestType;
20946
20947 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20948 : S(S), DestType(CastType) {}
20949
20950 ExprResult VisitStmt(Stmt *S) {
20951 llvm_unreachable("unexpected statement!");
20952 }
20953
20954 ExprResult VisitExpr(Expr *E) {
20955 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20956 << E->getSourceRange();
20957 return ExprError();
20958 }
20959
20960 ExprResult VisitCallExpr(CallExpr *E);
20961 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20962
20963 /// Rebuild an expression which simply semantically wraps another
20964 /// expression which it shares the type and value kind of.
20965 template <class T> ExprResult rebuildSugarExpr(T *E) {
20966 ExprResult SubResult = Visit(E->getSubExpr());
20967 if (SubResult.isInvalid()) return ExprError();
20968 Expr *SubExpr = SubResult.get();
20969 E->setSubExpr(SubExpr);
20970 E->setType(SubExpr->getType());
20971 E->setValueKind(SubExpr->getValueKind());
20972 assert(E->getObjectKind() == OK_Ordinary);
20973 return E;
20974 }
20975
20976 ExprResult VisitParenExpr(ParenExpr *E) {
20977 return rebuildSugarExpr(E);
20978 }
20979
20980 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20981 return rebuildSugarExpr(E);
20982 }
20983
20984 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20985 const PointerType *Ptr = DestType->getAs<PointerType>();
20986 if (!Ptr) {
20987 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20988 << E->getSourceRange();
20989 return ExprError();
20990 }
20991
20992 if (isa<CallExpr>(E->getSubExpr())) {
20993 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20994 << E->getSourceRange();
20995 return ExprError();
20996 }
20997
20998 assert(E->isPRValue());
20999 assert(E->getObjectKind() == OK_Ordinary);
21000 E->setType(DestType);
21001
21002 // Build the sub-expression as if it were an object of the pointee type.
21003 DestType = Ptr->getPointeeType();
21004 ExprResult SubResult = Visit(E->getSubExpr());
21005 if (SubResult.isInvalid()) return ExprError();
21006 E->setSubExpr(SubResult.get());
21007 return E;
21008 }
21009
21010 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21011
21012 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21013
21014 ExprResult VisitMemberExpr(MemberExpr *E) {
21015 return resolveDecl(E, E->getMemberDecl());
21016 }
21017
21018 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21019 return resolveDecl(E, E->getDecl());
21020 }
21021 };
21022}
21023
21024/// Rebuilds a call expression which yielded __unknown_anytype.
21025ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21026 Expr *CalleeExpr = E->getCallee();
21027
21028 enum FnKind {
21029 FK_MemberFunction,
21030 FK_FunctionPointer,
21031 FK_BlockPointer
21032 };
21033
21034 FnKind Kind;
21035 QualType CalleeType = CalleeExpr->getType();
21036 if (CalleeType == S.Context.BoundMemberTy) {
21038 Kind = FK_MemberFunction;
21039 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21040 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21041 CalleeType = Ptr->getPointeeType();
21042 Kind = FK_FunctionPointer;
21043 } else {
21044 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21045 Kind = FK_BlockPointer;
21046 }
21047 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21048
21049 // Verify that this is a legal result type of a function.
21050 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21051 DestType->isFunctionType()) {
21052 unsigned diagID = diag::err_func_returning_array_function;
21053 if (Kind == FK_BlockPointer)
21054 diagID = diag::err_block_returning_array_function;
21055
21056 S.Diag(E->getExprLoc(), diagID)
21057 << DestType->isFunctionType() << DestType;
21058 return ExprError();
21059 }
21060
21061 // Otherwise, go ahead and set DestType as the call's result.
21062 E->setType(DestType.getNonLValueExprType(S.Context));
21064 assert(E->getObjectKind() == OK_Ordinary);
21065
21066 // Rebuild the function type, replacing the result type with DestType.
21067 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21068 if (Proto) {
21069 // __unknown_anytype(...) is a special case used by the debugger when
21070 // it has no idea what a function's signature is.
21071 //
21072 // We want to build this call essentially under the K&R
21073 // unprototyped rules, but making a FunctionNoProtoType in C++
21074 // would foul up all sorts of assumptions. However, we cannot
21075 // simply pass all arguments as variadic arguments, nor can we
21076 // portably just call the function under a non-variadic type; see
21077 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21078 // However, it turns out that in practice it is generally safe to
21079 // call a function declared as "A foo(B,C,D);" under the prototype
21080 // "A foo(B,C,D,...);". The only known exception is with the
21081 // Windows ABI, where any variadic function is implicitly cdecl
21082 // regardless of its normal CC. Therefore we change the parameter
21083 // types to match the types of the arguments.
21084 //
21085 // This is a hack, but it is far superior to moving the
21086 // corresponding target-specific code from IR-gen to Sema/AST.
21087
21088 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21089 SmallVector<QualType, 8> ArgTypes;
21090 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21091 ArgTypes.reserve(E->getNumArgs());
21092 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21093 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21094 }
21095 ParamTypes = ArgTypes;
21096 }
21097 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21098 Proto->getExtProtoInfo());
21099 } else {
21100 DestType = S.Context.getFunctionNoProtoType(DestType,
21101 FnType->getExtInfo());
21102 }
21103
21104 // Rebuild the appropriate pointer-to-function type.
21105 switch (Kind) {
21106 case FK_MemberFunction:
21107 // Nothing to do.
21108 break;
21109
21110 case FK_FunctionPointer:
21111 DestType = S.Context.getPointerType(DestType);
21112 break;
21113
21114 case FK_BlockPointer:
21115 DestType = S.Context.getBlockPointerType(DestType);
21116 break;
21117 }
21118
21119 // Finally, we can recurse.
21120 ExprResult CalleeResult = Visit(CalleeExpr);
21121 if (!CalleeResult.isUsable()) return ExprError();
21122 E->setCallee(CalleeResult.get());
21123
21124 // Bind a temporary if necessary.
21125 return S.MaybeBindToTemporary(E);
21126}
21127
21128ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21129 // Verify that this is a legal result type of a call.
21130 if (DestType->isArrayType() || DestType->isFunctionType()) {
21131 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21132 << DestType->isFunctionType() << DestType;
21133 return ExprError();
21134 }
21135
21136 // Rewrite the method result type if available.
21137 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21138 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21139 Method->setReturnType(DestType);
21140 }
21141
21142 // Change the type of the message.
21143 E->setType(DestType.getNonReferenceType());
21145
21146 return S.MaybeBindToTemporary(E);
21147}
21148
21149ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21150 // The only case we should ever see here is a function-to-pointer decay.
21151 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21152 assert(E->isPRValue());
21153 assert(E->getObjectKind() == OK_Ordinary);
21154
21155 E->setType(DestType);
21156
21157 // Rebuild the sub-expression as the pointee (function) type.
21158 DestType = DestType->castAs<PointerType>()->getPointeeType();
21159
21160 ExprResult Result = Visit(E->getSubExpr());
21161 if (!Result.isUsable()) return ExprError();
21162
21163 E->setSubExpr(Result.get());
21164 return E;
21165 } else if (E->getCastKind() == CK_LValueToRValue) {
21166 assert(E->isPRValue());
21167 assert(E->getObjectKind() == OK_Ordinary);
21168
21169 assert(isa<BlockPointerType>(E->getType()));
21170
21171 E->setType(DestType);
21172
21173 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21174 DestType = S.Context.getLValueReferenceType(DestType);
21175
21176 ExprResult Result = Visit(E->getSubExpr());
21177 if (!Result.isUsable()) return ExprError();
21178
21179 E->setSubExpr(Result.get());
21180 return E;
21181 } else {
21182 llvm_unreachable("Unhandled cast type!");
21183 }
21184}
21185
21186ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21187 ExprValueKind ValueKind = VK_LValue;
21188 QualType Type = DestType;
21189
21190 // We know how to make this work for certain kinds of decls:
21191
21192 // - functions
21193 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21194 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21195 DestType = Ptr->getPointeeType();
21196 ExprResult Result = resolveDecl(E, VD);
21197 if (Result.isInvalid()) return ExprError();
21198 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21199 VK_PRValue);
21200 }
21201
21202 if (!Type->isFunctionType()) {
21203 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21204 << VD << E->getSourceRange();
21205 return ExprError();
21206 }
21207 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21208 // We must match the FunctionDecl's type to the hack introduced in
21209 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21210 // type. See the lengthy commentary in that routine.
21211 QualType FDT = FD->getType();
21212 const FunctionType *FnType = FDT->castAs<FunctionType>();
21213 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21214 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21215 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21216 SourceLocation Loc = FD->getLocation();
21217 FunctionDecl *NewFD = FunctionDecl::Create(
21218 S.Context, FD->getDeclContext(), Loc, Loc,
21219 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21221 false /*isInlineSpecified*/, FD->hasPrototype(),
21222 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21223
21224 if (FD->getQualifier())
21225 NewFD->setQualifierInfo(FD->getQualifierLoc());
21226
21227 SmallVector<ParmVarDecl*, 16> Params;
21228 for (const auto &AI : FT->param_types()) {
21229 ParmVarDecl *Param =
21230 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21231 Param->setScopeInfo(0, Params.size());
21232 Params.push_back(Param);
21233 }
21234 NewFD->setParams(Params);
21235 DRE->setDecl(NewFD);
21236 VD = DRE->getDecl();
21237 }
21238 }
21239
21240 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21241 if (MD->isInstance()) {
21242 ValueKind = VK_PRValue;
21244 }
21245
21246 // Function references aren't l-values in C.
21247 if (!S.getLangOpts().CPlusPlus)
21248 ValueKind = VK_PRValue;
21249
21250 // - variables
21251 } else if (isa<VarDecl>(VD)) {
21252 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21253 Type = RefTy->getPointeeType();
21254 } else if (Type->isFunctionType()) {
21255 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21256 << VD << E->getSourceRange();
21257 return ExprError();
21258 }
21259
21260 // - nothing else
21261 } else {
21262 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21263 << VD << E->getSourceRange();
21264 return ExprError();
21265 }
21266
21267 // Modifying the declaration like this is friendly to IR-gen but
21268 // also really dangerous.
21269 VD->setType(DestType);
21270 E->setType(Type);
21271 E->setValueKind(ValueKind);
21272 return E;
21273}
21274
21277 ExprValueKind &VK, CXXCastPath &Path) {
21278 // The type we're casting to must be either void or complete.
21279 if (!CastType->isVoidType() &&
21281 diag::err_typecheck_cast_to_incomplete))
21282 return ExprError();
21283
21284 // Rewrite the casted expression from scratch.
21285 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21286 if (!result.isUsable()) return ExprError();
21287
21288 CastExpr = result.get();
21290 CastKind = CK_NoOp;
21291
21292 return CastExpr;
21293}
21294
21296 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21297}
21298
21300 Expr *arg, QualType &paramType) {
21301 // If the syntactic form of the argument is not an explicit cast of
21302 // any sort, just do default argument promotion.
21303 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21304 if (!castArg) {
21306 if (result.isInvalid()) return ExprError();
21307 paramType = result.get()->getType();
21308 return result;
21309 }
21310
21311 // Otherwise, use the type that was written in the explicit cast.
21312 assert(!arg->hasPlaceholderType());
21313 paramType = castArg->getTypeAsWritten();
21314
21315 // Copy-initialize a parameter of that type.
21316 InitializedEntity entity =
21318 /*consumed*/ false);
21319 return PerformCopyInitialization(entity, callLoc, arg);
21320}
21321
21323 Expr *orig = E;
21324 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21325 while (true) {
21326 E = E->IgnoreParenImpCasts();
21327 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21328 E = call->getCallee();
21329 diagID = diag::err_uncasted_call_of_unknown_any;
21330 } else {
21331 break;
21332 }
21333 }
21334
21335 SourceLocation loc;
21336 NamedDecl *d;
21337 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21338 loc = ref->getLocation();
21339 d = ref->getDecl();
21340 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21341 loc = mem->getMemberLoc();
21342 d = mem->getMemberDecl();
21343 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21344 diagID = diag::err_uncasted_call_of_unknown_any;
21345 loc = msg->getSelectorStartLoc();
21346 d = msg->getMethodDecl();
21347 if (!d) {
21348 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21349 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21350 << orig->getSourceRange();
21351 return ExprError();
21352 }
21353 } else {
21354 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21355 << E->getSourceRange();
21356 return ExprError();
21357 }
21358
21359 S.Diag(loc, diagID) << d << orig->getSourceRange();
21360
21361 // Never recoverable.
21362 return ExprError();
21363}
21364
21366 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21367 if (!placeholderType) return E;
21368
21369 switch (placeholderType->getKind()) {
21370 case BuiltinType::UnresolvedTemplate: {
21371 auto *ULE = cast<UnresolvedLookupExpr>(E);
21372 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21373 // There's only one FoundDecl for UnresolvedTemplate type. See
21374 // BuildTemplateIdExpr.
21375 NamedDecl *Temp = *ULE->decls_begin();
21376 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
21377
21378 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21379 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21380 // as it models only the unqualified-id case, where this case can clearly be
21381 // qualified. Thus we can't just qualify an assumed template.
21382 TemplateName TN;
21383 if (auto *TD = dyn_cast<TemplateDecl>(Temp))
21384 TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),
21385 TemplateName(TD));
21386 else
21387 TN = Context.getAssumedTemplateName(NameInfo.getName());
21388
21389 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21390 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21391 Diag(Temp->getLocation(), diag::note_referenced_type_template)
21392 << IsTypeAliasTemplateDecl;
21393
21394 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21395 bool HasAnyDependentTA = false;
21396 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21397 HasAnyDependentTA |= Arg.getArgument().isDependent();
21398 TAL.addArgument(Arg);
21399 }
21400
21401 QualType TST;
21402 {
21403 SFINAETrap Trap(*this);
21404 TST = CheckTemplateIdType(
21405 ElaboratedTypeKeyword::None, TN, NameInfo.getBeginLoc(), TAL,
21406 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21407 }
21408 if (TST.isNull())
21409 TST = Context.getTemplateSpecializationType(
21410 ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),
21411 /*CanonicalArgs=*/{},
21412 HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21413 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},
21414 TST);
21415 }
21416
21417 // Overloaded expressions.
21418 case BuiltinType::Overload: {
21419 // Try to resolve a single function template specialization.
21420 // This is obligatory.
21421 ExprResult Result = E;
21423 return Result;
21424
21425 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21426 // leaves Result unchanged on failure.
21427 Result = E;
21429 return Result;
21430
21431 // If that failed, try to recover with a call.
21432 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21433 /*complain*/ true);
21434 return Result;
21435 }
21436
21437 // Bound member functions.
21438 case BuiltinType::BoundMember: {
21439 ExprResult result = E;
21440 const Expr *BME = E->IgnoreParens();
21441 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21442 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21444 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21445 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21446 if (ME->getMemberNameInfo().getName().getNameKind() ==
21448 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21449 }
21450 tryToRecoverWithCall(result, PD,
21451 /*complain*/ true);
21452 return result;
21453 }
21454
21455 // ARC unbridged casts.
21456 case BuiltinType::ARCUnbridgedCast: {
21457 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
21458 ObjC().diagnoseARCUnbridgedCast(realCast);
21459 return realCast;
21460 }
21461
21462 // Expressions of unknown type.
21463 case BuiltinType::UnknownAny:
21464 return diagnoseUnknownAnyExpr(*this, E);
21465
21466 // Pseudo-objects.
21467 case BuiltinType::PseudoObject:
21468 return PseudoObject().checkRValue(E);
21469
21470 case BuiltinType::BuiltinFn: {
21471 // Accept __noop without parens by implicitly converting it to a call expr.
21472 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21473 if (DRE) {
21474 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21475 unsigned BuiltinID = FD->getBuiltinID();
21476 if (BuiltinID == Builtin::BI__noop) {
21477 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21478 CK_BuiltinFnToFnPtr)
21479 .get();
21480 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21483 }
21484
21485 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21486 // Any use of these other than a direct call is ill-formed as of C++20,
21487 // because they are not addressable functions. In earlier language
21488 // modes, warn and force an instantiation of the real body.
21489 Diag(E->getBeginLoc(),
21491 ? diag::err_use_of_unaddressable_function
21492 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21493 if (FD->isImplicitlyInstantiable()) {
21494 // Require a definition here because a normal attempt at
21495 // instantiation for a builtin will be ignored, and we won't try
21496 // again later. We assume that the definition of the template
21497 // precedes this use.
21499 /*Recursive=*/false,
21500 /*DefinitionRequired=*/true,
21501 /*AtEndOfTU=*/false);
21502 }
21503 // Produce a properly-typed reference to the function.
21504 CXXScopeSpec SS;
21505 SS.Adopt(DRE->getQualifierLoc());
21506 TemplateArgumentListInfo TemplateArgs;
21507 DRE->copyTemplateArgumentsInto(TemplateArgs);
21508 return BuildDeclRefExpr(
21509 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21510 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21511 DRE->getTemplateKeywordLoc(),
21512 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21513 }
21514 }
21515
21516 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21517 return ExprError();
21518 }
21519
21520 case BuiltinType::IncompleteMatrixIdx:
21522 ->getRowIdx()
21523 ->getBeginLoc(),
21524 diag::err_matrix_incomplete_index);
21525 return ExprError();
21526
21527 // Expressions of unknown type.
21528 case BuiltinType::ArraySection:
21529 // If we've already diagnosed something on the array section type, we
21530 // shouldn't need to do any further diagnostic here.
21531 if (!E->containsErrors())
21532 Diag(E->getBeginLoc(), diag::err_array_section_use)
21533 << cast<ArraySectionExpr>(E)->isOMPArraySection();
21534 return ExprError();
21535
21536 // Expressions of unknown type.
21537 case BuiltinType::OMPArrayShaping:
21538 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21539
21540 case BuiltinType::OMPIterator:
21541 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21542
21543 // Everything else should be impossible.
21544#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21545 case BuiltinType::Id:
21546#include "clang/Basic/OpenCLImageTypes.def"
21547#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21548 case BuiltinType::Id:
21549#include "clang/Basic/OpenCLExtensionTypes.def"
21550#define SVE_TYPE(Name, Id, SingletonId) \
21551 case BuiltinType::Id:
21552#include "clang/Basic/AArch64ACLETypes.def"
21553#define PPC_VECTOR_TYPE(Name, Id, Size) \
21554 case BuiltinType::Id:
21555#include "clang/Basic/PPCTypes.def"
21556#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21557#include "clang/Basic/RISCVVTypes.def"
21558#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21559#include "clang/Basic/WebAssemblyReferenceTypes.def"
21560#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
21561#include "clang/Basic/AMDGPUTypes.def"
21562#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21563#include "clang/Basic/HLSLIntangibleTypes.def"
21564#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21565#define PLACEHOLDER_TYPE(Id, SingletonId)
21566#include "clang/AST/BuiltinTypes.def"
21567 break;
21568 }
21569
21570 llvm_unreachable("invalid placeholder type!");
21571}
21572
21574 if (E->isTypeDependent())
21575 return true;
21577 return E->getType()->isIntegralOrEnumerationType();
21578 return false;
21579}
21580
21582 ArrayRef<Expr *> SubExprs, QualType T) {
21583 if (!Context.getLangOpts().RecoveryAST)
21584 return ExprError();
21585
21586 if (isSFINAEContext())
21587 return ExprError();
21588
21589 if (T.isNull() || T->isUndeducedType() ||
21590 !Context.getLangOpts().RecoveryASTType)
21591 // We don't know the concrete type, fallback to dependent type.
21592 T = Context.DependentTy;
21593
21594 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21595}
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.
static DeclT * getDefinitionOrSelf(DeclT *D)
Definition Decl.cpp:2691
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
Token Tok
The Token.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis for CUDA constructs.
CastType
Definition SemaCast.cpp:49
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 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)
@ ConstMethod
@ 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:147
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:163
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:557
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 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:582
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:109
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 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:489
bool hasValue() const
Definition APValue.h:465
bool isInt() const
Definition APValue.h:467
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
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:776
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:772
const LangOptions & getLangOpts() const
Definition ASTContext.h:926
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition ASTContext.h:894
bool typesAreBlockPointerCompatible(QualType, QualType)
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
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
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
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:891
std::optional< CharUnits > getTypeSizeInCharsIfKnown(QualType Ty) 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:4484
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2721
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:2776
Wrapper for source info for arrays.
Definition TypeLoc.h:1748
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3722
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3736
QualType getElementType() const
Definition TypeBase.h:3734
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition Expr.h:6619
Attr - This represents one attribute.
Definition Attr.h:45
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4387
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
Expr * getLHS() const
Definition Expr.h:4022
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4066
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2175
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4072
StringRef getOpcodeStr() const
Definition Expr.h:4038
bool isRelationalOp() const
Definition Expr.h:4067
SourceLocation getOperatorLoc() const
Definition Expr.h:4014
bool isMultiplicativeOp() const
Definition Expr.h:4057
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2128
bool isShiftOp() const
Definition Expr.h:4061
Expr * getRHS() const
Definition Expr.h:4024
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:4977
bool isBitwiseOp() const
Definition Expr.h:4064
bool isAdditiveOp() const
Definition Expr.h:4059
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4108
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4113
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:2200
Opcode getOpcode() const
Definition Expr.h:4017
bool isAssignmentOp() const
Definition Expr.h:4111
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2137
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4069
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4063
BinaryOperatorKind Opcode
Definition Expr.h:3977
A binding in a decomposition declaration.
Definition DeclCXX.h:4185
A class which contains all the information about a particular captured value.
Definition Decl.h:4660
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4654
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.cpp:5366
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition Decl.h:4736
void setBlockMissingReturnType(bool val=true)
Definition Decl.h:4793
void setIsVariadic(bool value)
Definition Decl.h:4730
SourceLocation getCaretLocation() const
Definition Decl.h:4727
void setBody(CompoundStmt *B)
Definition Decl.h:4734
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:4740
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition Decl.cpp:5377
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5565
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6558
Pointer to a block type.
Definition TypeBase.h:3542
This class is used for builtin types like 'int'.
Definition TypeBase.h:3164
bool isSVEBool() const
Definition TypeBase.h:3241
Kind getKind() const
Definition TypeBase.h:3212
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:1956
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:1549
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1612
Represents a C++ constructor within a class.
Definition DeclCXX.h:2604
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2943
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition DeclCXX.cpp:3184
Represents a C++ base or member initializer.
Definition DeclCXX.h:2369
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1271
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition ExprCXX.cpp:1039
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1378
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:1093
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1105
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:1550
Represents a C++ destructor within a class.
Definition DeclCXX.h:2869
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
bool isVirtual() const
Definition DeclCXX.h:2184
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
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:2508
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:84
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition ExprCXX.h:152
SourceRange getSourceRange() const
Definition ExprCXX.h:164
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition ExprCXX.cpp:1987
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition ExprCXX.h:2747
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:1225
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition DeclCXX.cpp:600
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
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:2075
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.
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:180
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:185
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:79
SourceLocation getBeginLoc() const
Definition DeclSpec.h:83
bool isSet() const
Deprecated.
Definition DeclSpec.h:198
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:94
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:183
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
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:1155
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2877
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3081
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3094
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:1513
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3060
Expr * getCallee()
Definition Expr.h:3024
void computeDependence()
Compute and set dependence bits.
Definition Expr.h:3100
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3068
void setCallee(Expr *F)
Definition Expr.h:3026
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:3610
CastKind getCastKind() const
Definition Expr.h:3654
const char * getCastKindName() const
Definition Expr.h:3658
void setSubExpr(Expr *E)
Definition Expr.h:3662
Expr * getSubExpr()
Definition Expr.h:3660
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
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:1629
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4782
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3275
QualType getElementType() const
Definition TypeBase.h:3285
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:4999
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3539
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1720
bool body_empty() const
Definition Stmt.h:1764
Stmt * getStmtExprResult()
Definition Stmt.h:1842
ConditionalOperator - The ?
Definition Expr.h:4325
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3760
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3816
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3836
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1082
static ConstantResultStorageKind getStorageKind(const APValue &Value)
Definition Expr.cpp:298
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition Expr.cpp:374
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1132
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:346
bool isImmediateInvocation() const
Definition Expr.h:1154
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4373
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4392
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4389
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:1445
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:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2238
bool isRequiresExprBody() const
Definition DeclBase.h:2194
DeclContextLookupResult lookup_result
Definition DeclBase.h:2577
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:2189
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:2161
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:1270
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition Expr.h:1381
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition Expr.h:1425
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1371
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1474
void setDecl(ValueDecl *NewD)
Definition Expr.cpp:540
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition Expr.h:1429
DeclarationNameInfo getNameInfo() const
Definition Expr.h:1342
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition Expr.h:1397
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:484
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition Expr.h:1359
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1363
ValueDecl * getDecl()
Definition Expr.h:1338
SourceLocation getBeginLoc() const
Definition Expr.h:1349
SourceLocation getLocation() const
Definition Expr.h:1346
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:573
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition DeclBase.cpp:775
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:590
bool isInvalidDecl() const
Definition DeclBase.h:588
SourceLocation getLocation() const
Definition DeclBase.h:439
void setReferenced(bool R=true)
Definition DeclBase.h:623
DeclContext * getDeclContext()
Definition DeclBase.h:448
bool hasAttr() const
Definition DeclBase.h:577
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:978
Kind getKind() const
Definition DeclBase.h:442
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:2000
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition Decl.h:845
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1874
DeclaratorContext getContext() const
Definition DeclSpec.h:2046
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2057
bool isInvalidType() const
Definition DeclSpec.h:2688
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2304
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:544
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:951
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:723
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
Represents a reference to emded data.
Definition Expr.h:5060
RAII object that enters a new expression evaluation context.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4171
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3862
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3889
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1464
This represents one expression.
Definition Expr.h:112
LValueClassification
Definition Expr.h:289
@ LV_ArrayTemporary
Definition Expr.h:299
@ LV_ClassTemporary
Definition Expr.h:298
@ LV_MemberFunction
Definition Expr.h:296
@ 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:3112
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:674
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition Expr.cpp:3041
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:3090
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:444
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:3085
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3073
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition Expr.cpp:3094
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:3081
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:3334
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:831
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:827
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:835
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:451
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:3665
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:3065
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:802
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:811
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:814
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition Expr.h:817
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:804
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:4042
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:262
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:461
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
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:4294
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:464
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:476
isModifiableLvalueResult
Definition Expr.h:304
@ MLV_DuplicateVectorComponents
Definition Expr.h:308
@ MLV_LValueCast
Definition Expr.h:310
@ MLV_InvalidMessageExpression
Definition Expr.h:319
@ MLV_ConstQualifiedField
Definition Expr.h:313
@ MLV_InvalidExpression
Definition Expr.h:309
@ MLV_IncompleteType
Definition Expr.h:311
@ MLV_Valid
Definition Expr.h:305
@ MLV_ConstQualified
Definition Expr.h:312
@ MLV_NoSetterProperty
Definition Expr.h:316
@ MLV_ArrayTemporary
Definition Expr.h:321
@ MLV_SubObjCPropertySetting
Definition Expr.h:318
@ MLV_ConstAddrSpace
Definition Expr.h:314
@ MLV_MemberFunction
Definition Expr.h:317
@ MLV_NotObjectType
Definition Expr.h:306
@ MLV_ArrayType
Definition Expr.h:315
@ MLV_ClassTemporary
Definition Expr.h:320
@ MLV_IncompleteVoidType
Definition Expr.h:307
QualType getType() const
Definition Expr.h:144
bool isOrdinaryOrBitFieldObject() const
Definition Expr.h:455
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:434
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:133
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6498
ExtVectorType - Extended vector type.
Definition TypeBase.h:4267
Represents difference between two FPOptions values.
bool isFPConstrained() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3160
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3263
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3340
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:79
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:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
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:103
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp:993
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1072
const Expr * getSubExpr() const
Definition Expr.h:1062
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:2000
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:2189
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2797
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3836
bool isImmediateFunction() const
Definition Decl.cpp:3329
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4013
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3751
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3854
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2921
QualType getReturnType() const
Definition Decl.h:2845
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2443
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3607
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isImmediateEscalating() const
Definition Decl.cpp:3300
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2933
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4119
bool isConsteval() const
Definition Decl.h:2482
size_t param_size() const
Definition Decl.h:2790
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3188
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition Decl.cpp:4029
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition Decl.h:2881
Represents a reference to a function parameter pack, init-capture pack, or binding pack that has been...
Definition ExprCXX.h:4843
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4872
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5758
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5561
bool isParamConsumed(unsigned I) const
Definition TypeBase.h:5772
unsigned getNumParams() const
Definition TypeBase.h:5532
QualType getParamType(unsigned i) const
Definition TypeBase.h:5534
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5658
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5543
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5539
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5694
Declaration of a template function.
unsigned getNumParams() const
Definition TypeLoc.h:1687
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1693
SourceLocation getLocalRangeEnd() const
Definition TypeLoc.h:1639
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1696
SourceLocation getLocalRangeBegin() const
Definition TypeLoc.h:1631
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4561
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4632
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4489
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4450
ExtInfo getExtInfo() const
Definition TypeBase.h:4806
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:4798
bool getCFIUncheckedCalleeAttr() const
Determine whether this is a function prototype that includes the cfi_unchecked_callee attribute.
Definition Type.cpp:3571
QualType getReturnType() const
Definition TypeBase.h:4790
bool getCmseNSCallAttr() const
Definition TypeBase.h:4804
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4818
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4857
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:4599
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:1731
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3787
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2068
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:615
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3467
Describes an C or C++ initializer list.
Definition Expr.h:5233
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:971
Represents the declaration of a label.
Definition Decl.h:524
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1970
CXXMethodDecl * getCallOperator() const
Retrieve the function call operator associated with this lambda expression.
Definition ExprCXX.cpp:1404
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:1020
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token,...
Definition Lexer.h:399
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping '\' and " characters and ii) ...
Definition Lexer.cpp:309
Represents the results of name lookup.
Definition Lookup.h:147
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition Lookup.h:495
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
DeclClass * getAsSingle() const
Definition Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition Lookup.h:569
bool isAmbiguous() const
Definition Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition Lookup.h:331
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition Lookup.h:452
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
void setNamingClass(CXXRecordDecl *Record)
Sets the 'naming class' for this lookup.
Definition Lookup.h:457
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition Lookup.h:576
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition Lookup.h:265
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition Lookup.h:255
A global _GUID constant.
Definition DeclCXX.h:4398
MS property subscript expression.
Definition ExprCXX.h:1007
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition Expr.h:2799
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4337
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4351
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3298
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3487
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3381
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:1746
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3516
Expr * getBase() const
Definition Expr.h:3375
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1790
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:1680
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
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:7840
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition ExprObjC.h:1498
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:548
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprObjC.h:594
SourceLocation getLocation() const
Definition ExprObjC.h:591
SourceLocation getOpLoc() const
Definition ExprObjC.h:599
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:578
bool isArrow() const
Definition ExprObjC.h:586
SourceLocation getEndLoc() const LLVM_READONLY
Definition ExprObjC.h:597
const Expr * getBase() const
Definition ExprObjC.h:582
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:940
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1364
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:7896
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1840
qual_range quals() const
Definition TypeBase.h:8015
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:1649
Helper class for OffsetOfExpr.
Definition Expr.h:2421
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:1178
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1153
@ CSK_Normal
Normal lookup.
Definition Overload.h:1157
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1369
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:3130
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3191
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2182
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2203
const Expr * getSubExpr() const
Definition Expr.h:2199
bool isProducedByFoldExpansion() const
Definition Expr.h:2224
Expr * getExpr(unsigned Init)
Definition Expr.h:6046
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:4849
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition Expr.h:6044
SourceLocation getLParenLoc() const
Definition Expr.h:6059
SourceLocation getRParenLoc() const
Definition Expr.h:6060
Represents a parameter to a function.
Definition Decl.h:1790
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1823
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:2946
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3328
QualType getPointeeType() const
Definition TypeBase.h:3338
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition Expr.cpp:629
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition Expr.cpp:669
bool isMacroDefined(StringRef Id)
IdentifierTable & getIdentifierTable()
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6690
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8362
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8367
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:3555
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:2920
bool isAddressSpaceOverlapping(QualType T, const ASTContext &Ctx) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition TypeBase.h:1416
QualType withConst() const
Definition TypeBase.h:1159
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1156
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:8278
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8404
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:8318
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:2702
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1438
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:8463
QualType getCanonicalType() const
Definition TypeBase.h:8330
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8372
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition Type.cpp:2939
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1179
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C.
Definition TypeBase.h:8470
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8351
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1670
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1545
bool isCanonical() const
Definition TypeBase.h:8335
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1309
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2694
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:8443
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8310
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:4312
bool hasFlexibleArrayMember() const
Definition Decl.h:4345
field_iterator field_end() const
Definition Decl.h:4518
field_range fields() const
Definition Decl.h:4515
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition Expr.cpp:5331
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:3573
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:428
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition Scope.h:271
bool isInCFunctionScope() const
isInObjcMethodScope - Return true if this scope is, or is contained, in an C function body.
Definition Scope.h:448
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:487
@ ContinueScope
This is a while, do, for, which can have continue statements embedded into it.
Definition Scope.h:59
@ ControlScope
The controlling scope in a if/switch/while/for statement.
Definition Scope.h:66
@ BreakScope
This is a while, do, switch, for, etc that can have break statements embedded into it.
Definition Scope.h:55
@ DeclScope
This is a scope that can contain a declaration.
Definition Scope.h:63
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isUnarySelector() const
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h: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:90
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:726
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:134
bool CheckCall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition SemaCUDA.cpp:902
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition SemaCUDA.h:120
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)
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures.
Definition SemaObjC.h:855
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.
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:377
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
const ValueDecl * getOpenMPDeclareMapperVarName() const
ExprResult checkAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS)
ExprResult checkIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op)
Check an increment or decrement of a pseudo-object expression.
ExprResult checkRValue(Expr *E)
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8407
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12395
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12437
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7682
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:854
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.
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:8160
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13522
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1120
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:8210
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
bool isAlwaysConstantEvaluatedContext() const
Definition Sema.h:8128
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:934
bool isAttrContext() const
Definition Sema.h:6918
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
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:8203
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9297
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9336
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9305
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:411
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:1501
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:1230
SemaCUDA & CUDA()
Definition Sema.h:1441
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:7803
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7805
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7804
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
bool needsRebuildOfDefaultArgOrInit() const
Definition Sema.h:8148
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:8290
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1223
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2444
Preprocessor & getPreprocessor() const
Definition Sema.h:924
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:6896
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2313
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:8279
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition Sema.h:8191
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:6730
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:2045
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 BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:6908
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:1650
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:833
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:1283
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:8115
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...
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
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:1486
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:2823
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:754
bool isImmediateFunctionContext() const
Definition Sema.h:8140
ASTContext & getASTContext() const
Definition Sema.h:925
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1059
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition SemaExpr.cpp:764
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:755
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition SemaExpr.cpp:883
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:6048
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6050
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1191
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1655
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:11373
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:506
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:8175
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition SemaStmt.cpp:405
FPOptions & getCurFPFeatures()
Definition Sema.h:920
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8273
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
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:83
@ UPPC_Block
Block expression.
Definition Sema.h:14385
const LangOptions & getLangOpts() const
Definition Sema.h:918
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)
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:1491
ReuseLambdaContextDecl_t
Definition Sema.h:6984
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.
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:1282
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:2116
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
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:1281
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2559
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:952
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6474
SemaHLSL & HLSL()
Definition Sema.h:1451
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:15594
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:213
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
Definition Sema.h:5210
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition SemaExpr.cpp:75
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:6929
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6504
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition Sema.cpp:1662
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:13947
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:848
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:1314
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:6926
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2296
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:639
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:8144
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:8011
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2514
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1414
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:12461
SemaOpenCL & OpenCL()
Definition Sema.h:1496
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:13956
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:8136
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1630
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:6733
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:13891
SourceManager & getSourceManager() const
Definition Sema.h:923
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:7436
@ NTCUK_Destruct
Definition Sema.h:4071
@ NTCUK_Copy
Definition Sema.h:4072
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition Sema.h:8289
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:2344
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:6731
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:224
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....
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15369
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:2499
bool isConstantEvaluatedContext() const
Definition Sema.h:2587
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:1284
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4628
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:6933
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:123
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1319
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:13939
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:6675
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6697
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6687
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6702
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6692
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6712
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6681
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6707
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6722
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:1246
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:8126
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:8276
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:1286
@ TemplateNameIsRequired
Definition Sema.h:11350
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:783
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:1285
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:919
FPOptions CurFPFeatures
Definition Sema.h:1279
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:515
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 ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
friend class InitializationSequence
Definition Sema.h:1556
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:6508
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:626
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:2099
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)
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
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:7934
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9350
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9356
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9348
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9353
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9364
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9360
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:6389
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition Sema.h:13935
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:7789
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 ...
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
SemaPseudoObject & PseudoObject()
Definition Sema.h:1511
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2490
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:8152
SemaARM & ARM()
Definition Sema.h:1421
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8615
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:4951
SourceLocation getBeginLoc() const
Definition Expr.h:4996
const DeclContext * getParentContext() const
If the SourceLocExpr has been resolved return the subexpression representing the resolved value.
Definition Expr.h:4992
SourceLocation getEndLoc() const
Definition Expr.h:4997
SourceLocIdentKind getIdentKind() const
Definition Expr.h:4971
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:292
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:303
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition Overload.h:390
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:4529
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:362
StmtClass getStmtClass() const
Definition Stmt.h:1472
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
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:1799
unsigned getLength() const
Definition Expr.h:1909
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:1184
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1882
StringRef getString() const
Definition Expr.h:1867
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3812
bool isUnion() const
Definition Decl.h:3922
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool hasLongDoubleType() const
Determine whether the long double type is supported on this target.
Definition TargetInfo.h:730
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:332
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
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:98
void startToken()
Reset all flags to cleared.
Definition Token.h:179
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
EnsureImmediateInvocationInDefaultArgs & getDerived()
Represents a declaration of a type.
Definition Decl.h:3513
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3547
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:2706
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8249
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:8260
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2485
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition TypeBase.h:8935
bool isBlockPointerType() const
Definition TypeBase.h:8535
bool isVoidType() const
Definition TypeBase.h:8871
bool isBooleanType() const
Definition TypeBase.h:9001
bool isObjCBuiltinType() const
Definition TypeBase.h:8735
bool isMFloat8Type() const
Definition TypeBase.h:8896
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:1951
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9051
bool isIncompleteArrayType() const
Definition TypeBase.h:8622
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:8847
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:724
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2115
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:9031
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:2066
bool isVoidPointerType() const
Definition Type.cpp:712
const ComplexType * getAsComplexIntegerType() const
Definition Type.cpp:745
bool isArrayType() const
Definition TypeBase.h:8614
bool isCharType() const
Definition Type.cpp:2132
bool isFunctionPointerType() const
Definition TypeBase.h:8582
bool isArithmeticType() const
Definition Type.cpp:2337
bool isConstantMatrixType() const
Definition TypeBase.h:8676
bool isPointerType() const
Definition TypeBase.h:8515
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8915
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2573
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9158
bool isReferenceType() const
Definition TypeBase.h:8539
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:8955
bool isEnumeralType() const
Definition TypeBase.h:8646
bool isScalarType() const
Definition TypeBase.h:8973
bool isVariableArrayType() const
Definition TypeBase.h:8626
bool isSizelessBuiltinType() const
Definition Type.cpp:2531
bool isClkEventT() const
Definition TypeBase.h:8757
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2607
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2103
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8705
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:8989
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition Type.cpp:2291
bool isExtVectorType() const
Definition TypeBase.h:8658
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2168
bool isExtVectorBoolType() const
Definition TypeBase.h:8662
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2646
bool isImageType() const
Definition TypeBase.h:8769
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition TypeBase.h:8865
bool isPipeType() const
Definition TypeBase.h:8776
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2790
bool isBitIntType() const
Definition TypeBase.h:8780
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8840
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8638
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2782
bool isAnyComplexType() const
Definition TypeBase.h:8650
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8927
bool isHalfType() const
Definition TypeBase.h:8875
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8943
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2405
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition Type.cpp:2364
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:8853
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2243
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2557
bool isQueueT() const
Definition TypeBase.h:8761
bool isMemberPointerType() const
Definition TypeBase.h:8596
bool isAtomicType() const
Definition TypeBase.h:8697
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9014
bool isObjCIdType() const
Definition TypeBase.h:8717
bool isMatrixType() const
Definition TypeBase.h:8672
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:2800
bool isComplexIntegerType() const
Definition Type.cpp:730
bool isUnscopedEnumerationType() const
Definition Type.cpp:2125
bool isObjCObjectType() const
Definition TypeBase.h:8688
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition Type.cpp:5213
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9144
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5302
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9007
bool isHLSLResourceRecord() const
Definition Type.cpp:5362
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isDoubleType() const
Definition TypeBase.h:8888
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2435
bool isFunctionType() const
Definition TypeBase.h:8511
bool isObjCObjectPointerType() const
Definition TypeBase.h:8684
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2312
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:8969
bool isVectorType() const
Definition TypeBase.h:8654
bool isObjCQualifiedClassType() const
Definition TypeBase.h:8711
bool isObjCClassType() const
Definition TypeBase.h:8723
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2320
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2594
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2921
@ STK_FloatingComplex
Definition TypeBase.h:2764
@ STK_ObjCObjectPointer
Definition TypeBase.h:2758
@ STK_IntegralComplex
Definition TypeBase.h:2763
@ STK_MemberPointer
Definition TypeBase.h:2759
bool isFloatingType() const
Definition Type.cpp:2304
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:2253
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2928
bool isAnyPointerType() const
Definition TypeBase.h:8523
bool isRealType() const
Definition Type.cpp:2326
TypeClass getTypeClass() const
Definition TypeBase.h:2385
bool isSubscriptableVectorType() const
Definition TypeBase.h:8668
bool isSamplerT() const
Definition TypeBase.h:8749
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
bool isNullPtrType() const
Definition TypeBase.h:8908
bool isRecordType() const
Definition TypeBase.h:8642
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5366
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5014
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition Type.cpp:735
bool isUnicodeCharacterType() const
Definition Type.cpp:2188
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Definition Type.cpp:2354
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:2625
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2244
void setSubExpr(Expr *E)
Definition Expr.h:2286
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition Expr.h:2289
Expr * getSubExpr() const
Definition Expr.h:2285
Opcode getOpcode() const
Definition Expr.h:2280
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1426
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2340
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:5034
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4455
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:998
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1086
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1080
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1050
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3392
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:432
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4128
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition ExprCXX.cpp:1683
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:1645
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:640
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:4891
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:5501
VarDecl * getPotentiallyDecomposedVarDecl()
Definition DeclCXX.cpp:3582
QualType getType() const
Definition Value.cpp:237
Represents a variable declaration or definition.
Definition Decl.h:926
bool hasInit() const
Definition Decl.cpp:2398
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2257
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1578
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1226
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:2486
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:2907
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1551
const Expr * getInit() const
Definition Decl.h:1368
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1217
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1184
@ TLS_None
Not a TLS variable.
Definition Decl.h:946
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1295
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2375
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:2528
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:2800
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1262
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:2779
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2898
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3966
Expr * getSizeExpr() const
Definition TypeBase.h:3980
Represents a GCC generic vector type.
Definition TypeBase.h:4175
unsigned getNumElements() const
Definition TypeBase.h:4190
VectorKind getVectorKind() const
Definition TypeBase.h:4195
QualType getElementType() const
Definition TypeBase.h:4189
Retains information about a block that is currently being parsed.
Definition ScopeInfo.h:790
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition ScopeInfo.h:796
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition ScopeInfo.h:800
ValueDecl * getVariable() const
Definition ScopeInfo.h:675
bool isBlockCapture() const
Definition ScopeInfo.h:656
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:686
void markUsed(bool IsODRUse)
Definition ScopeInfo.h:668
bool isInvalid() const
Definition ScopeInfo.h:661
bool isThisCapture() const
Definition ScopeInfo.h:649
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition ScopeInfo.h:695
bool isCopyCapture() const
Definition ScopeInfo.h:654
bool isNested() const
Definition ScopeInfo.h:659
Retains information about a captured region.
Definition ScopeInfo.h:816
unsigned short CapRegionKind
The kind of captured region.
Definition ScopeInfo.h:831
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:745
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:732
bool ContainsUnexpandedParameterPack
Whether this contains an unexpanded parameter pack.
Definition ScopeInfo.h:728
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:708
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of 'this'; zero if 'this' is not captured.
Definition ScopeInfo.h:718
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition ScopeInfo.h:758
llvm::DenseMap< ValueDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition ScopeInfo.h:714
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:755
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:737
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition ScopeInfo.h:771
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:1090
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:493
llvm::SmallVector< AddrLabelExpr *, 4 > AddrLabels
The set of GNU address of label extension "&&label".
Definition ScopeInfo.h:246
bool HasOMPDeclareReductionCombiner
True if current scope is for OpenMP declare reduction combiner.
Definition ScopeInfo.h:135
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:884
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:992
void addPotentialThisCapture(SourceLocation Loc)
Definition ScopeInfo.h:998
llvm::SmallPtrSet< VarDecl *, 4 > CUDAPotentialODRUsedVars
Variables that are potentially ODR-used in CUDA/HIP.
Definition ScopeInfo.h:953
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:871
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition ScopeInfo.h:892
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:874
#define bool
Definition gpuintrin.h:32
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:89
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
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:212
@ 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:511
bool isTargetAddressSpace(LangAS AS)
CUDAFunctionTarget
Definition Cuda.h:60
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
TryCaptureKind
Definition Sema.h:651
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition Sema.h:659
@ BitwiseOp
A bitwise operation.
Definition Sema.h:663
@ Arithmetic
An arithmetic operation.
Definition Sema.h:661
@ Conditional
A conditional (?:) operator.
Definition Sema.h:667
@ CompAssign
A compound assignment expression.
Definition Sema.h:669
@ Comparison
A comparison.
Definition Sema.h:665
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:348
@ Nullable
Values of this type can be null.
Definition Specifiers.h:352
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:357
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:149
@ OK_VectorComponent
A vector component is an element or range of elements on a vector.
Definition Specifiers.h:157
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition Specifiers.h:161
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition Specifiers.h:154
@ OK_MatrixComponent
A matrix component is a single element of a matrix.
Definition Specifiers.h:169
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:992
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:990
@ AS_none
Definition Specifiers.h:127
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:251
@ SC_Register
Definition Specifiers.h:257
@ SC_None
Definition Specifiers.h:250
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
const FunctionProtoType * T
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:202
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_Identity
Identity conversion (no conversion)
Definition Overload.h:106
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition Overload.h:136
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition Overload.h:115
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:687
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:710
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition Sema.h:773
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition Sema.h:702
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition Sema.h:752
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition Sema.h:742
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition Sema.h:769
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition Sema.h:756
@ CompatibleVoidPtrToNonVoidPtr
CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because a void * can implicitly convert...
Definition Sema.h:694
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition Sema.h:736
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:731
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition Sema.h:765
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:689
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition Sema.h:721
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition Sema.h:698
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition Sema.h:706
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition Sema.h:748
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition Sema.h:715
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:727
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition Sema.h:760
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:562
@ 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:653
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
VarArgKind
Definition Sema.h:674
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition ASTLambda.h:69
AssignmentAction
Definition Sema.h:214
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:519
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:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
const char * getTraitSpelling(ExpressionTrait T) LLVM_READONLY
Return the spelling of the type trait TT. Never null.
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:149
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:270
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:276
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:284
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:273
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:280
StringLiteralKind
Definition Expr.h:1763
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_X86VectorCall
Definition Specifiers.h:283
@ CC_X86StdCall
Definition Specifiers.h:280
@ CC_X86FastCall
Definition Specifiers.h:281
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4145
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4154
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4139
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4142
@ Neon
is ARM Neon vector
Definition TypeBase.h:4148
@ Generic
not a target-specific vector type
Definition TypeBase.h:4136
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4160
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4163
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4157
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:4938
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5874
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:1746
PredefinedIdentKind
Definition Expr.h:1989
@ Implicit
An implicit conversion.
Definition Sema.h:438
CharacterLiteralKind
Definition Expr.h:1603
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:173
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition Specifiers.h:183
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:177
@ NOUR_None
This is an odr-use.
Definition Specifiers.h:175
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition Specifiers.h:180
#define false
Definition stdbool.h:26
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.
SourceRange getSourceRange() const LLVM_READONLY
getSourceRange - The range of the declaration name.
SourceLocation getEndLoc() const LLVM_READONLY
Stores data related to a single embed directive.
Definition Expr.h:5027
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
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:633
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition Expr.h:617
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:612
Extra information about a function prototype.
Definition TypeBase.h:5339
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13052
Data structure used to record current or nested expression evaluation contexts.
Definition Sema.h:6737
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition Sema.h:6767
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6818
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition Sema.h:6757
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition Sema.h:6772
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:6780
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition Sema.h:6776
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6786
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:6752
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:6794
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition Sema.h:6742
ExpressionEvaluationContext Context
The expression evaluation context.
Definition Sema.h:6739
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition Sema.h:6746
Abstract class used to diagnose incomplete types.
Definition Sema.h:8217
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.