clang 23.0.0git
SemaExpr.cpp
Go to the documentation of this file.
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "TreeTransform.h"
15#include "UsedDeclVisitor.h"
19#include "clang/AST/ASTLambda.h"
21#include "clang/AST/Attr.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclObjC.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/ExprCXX.h"
30#include "clang/AST/ExprObjC.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
46#include "clang/Sema/DeclSpec.h"
51#include "clang/Sema/Lookup.h"
52#include "clang/Sema/Overload.h"
54#include "clang/Sema/Scope.h"
56#include "clang/Sema/SemaARM.h"
57#include "clang/Sema/SemaCUDA.h"
59#include "clang/Sema/SemaHLSL.h"
60#include "clang/Sema/SemaObjC.h"
63#include "clang/Sema/Template.h"
64#include "llvm/ADT/STLExtras.h"
65#include "llvm/ADT/StringExtras.h"
66#include "llvm/Support/ConvertUTF.h"
67#include "llvm/Support/SaveAndRestore.h"
68#include "llvm/Support/TimeProfiler.h"
69#include "llvm/Support/TypeSize.h"
70#include <limits>
71#include <optional>
72
73using namespace clang;
74using namespace sema;
75
76bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
77 // See if this is an auto-typed variable whose initializer we are parsing.
78 if (ParsingInitForAutoVars.count(D))
79 return false;
80
81 // See if this is a deleted function.
82 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
83 if (FD->isDeleted())
84 return false;
85
86 // If the function has a deduced return type, and we can't deduce it,
87 // then we can't use it either.
88 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
89 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
90 return false;
91
92 // See if this is an aligned allocation/deallocation function that is
93 // unavailable.
94 if (TreatUnavailableAsInvalid &&
96 return false;
97 }
98
99 // See if this function is unavailable.
100 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
101 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
102 return false;
103
105 return false;
106
107 return true;
108}
109
111 // Warn if this is used but marked unused.
112 if (const auto *A = D->getAttr<UnusedAttr>()) {
113 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
114 // should diagnose them.
115 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
116 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
117 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
118 if (DC && !DC->hasAttr<UnusedAttr>())
119 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
120 }
121 }
122}
123
125 assert(Decl && Decl->isDeleted());
126
127 if (Decl->isDefaulted()) {
128 // If the method was explicitly defaulted, point at that declaration.
129 if (!Decl->isImplicit())
130 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
131
132 // Try to diagnose why this special member function was implicitly
133 // deleted. This might fail, if that reason no longer applies.
135 return;
136 }
137
138 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
139 if (Ctor && Ctor->isInheritingConstructor())
141
142 Diag(Decl->getLocation(), diag::note_availability_specified_here)
143 << Decl << 1;
144}
145
146/// Determine whether a FunctionDecl was ever declared with an
147/// explicit storage class.
149 for (auto *I : D->redecls()) {
150 if (I->getStorageClass() != SC_None)
151 return true;
152 }
153 return false;
154}
155
156/// Check whether we're in an extern inline function and referring to a
157/// variable or function with internal linkage (C11 6.7.4p3).
158///
159/// This is only a warning because we used to silently accept this code, but
160/// in many cases it will not behave correctly. This is not enabled in C++ mode
161/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
162/// and so while there may still be user mistakes, most of the time we can't
163/// prove that there are errors.
165 const NamedDecl *D,
166 SourceLocation Loc) {
167 // This is disabled under C++; there are too many ways for this to fire in
168 // contexts where the warning is a false positive, or where it is technically
169 // correct but benign.
170 //
171 // WG14 N3622 which removed the constraint entirely in C2y. It is left
172 // enabled in earlier language modes because this is a constraint in those
173 // language modes. But in C2y mode, we still want to issue the "incompatible
174 // with previous standards" diagnostic, too.
175 if (S.getLangOpts().CPlusPlus)
176 return;
177
178 // Check if this is an inlined function or method.
179 FunctionDecl *Current = S.getCurFunctionDecl();
180 if (!Current)
181 return;
182 if (!Current->isInlined())
183 return;
184 if (!Current->isExternallyVisible())
185 return;
186
187 // Check if the decl has internal linkage.
189 return;
190
191 // Downgrade from ExtWarn to Extension if
192 // (1) the supposedly external inline function is in the main file,
193 // and probably won't be included anywhere else.
194 // (2) the thing we're referencing is a pure function.
195 // (3) the thing we're referencing is another inline function.
196 // This last can give us false negatives, but it's better than warning on
197 // wrappers for simple C library functions.
198 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
199 unsigned DiagID;
200 if (S.getLangOpts().C2y)
201 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
202 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
204 DiagID = diag::ext_internal_in_extern_inline_quiet;
205 else
206 DiagID = diag::ext_internal_in_extern_inline;
207
208 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
210 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
211 << D;
212}
213
215 const FunctionDecl *First = Cur->getFirstDecl();
216
217 // Suggest "static" on the function, if possible.
219 SourceLocation DeclBegin = First->getSourceRange().getBegin();
220 Diag(DeclBegin, diag::note_convert_inline_to_static)
221 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
222 }
223}
224
226 const ObjCInterfaceDecl *UnknownObjCClass,
227 bool ObjCPropertyAccess,
228 bool AvoidPartialAvailabilityChecks,
229 ObjCInterfaceDecl *ClassReceiver,
230 bool SkipTrailingRequiresClause) {
231 SourceLocation Loc = Locs.front();
233 // If there were any diagnostics suppressed by template argument deduction,
234 // emit them now.
235 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
236 if (Pos != SuppressedDiagnostics.end()) {
237 for (const auto &[DiagLoc, PD] : Pos->second) {
238 DiagnosticBuilder Builder(Diags.Report(DiagLoc, PD.getDiagID()));
239 PD.Emit(Builder);
240 }
241 // Clear out the list of suppressed diagnostics, so that we don't emit
242 // them again for this specialization. However, we don't obsolete this
243 // entry from the table, because we want to avoid ever emitting these
244 // diagnostics again.
245 Pos->second.clear();
246 }
247
248 // C++ [basic.start.main]p3:
249 // The function 'main' shall not be used within a program.
250 if (cast<FunctionDecl>(D)->isMain())
251 Diag(Loc, diag::ext_main_used);
252
254 }
255
256 // See if this is an auto-typed variable whose initializer we are parsing.
257 if (ParsingInitForAutoVars.count(D)) {
258 if (isa<BindingDecl>(D)) {
259 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
260 << D->getDeclName();
261 } else {
262 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
263 << diag::ParsingInitFor::Var << D->getDeclName()
264 << cast<VarDecl>(D)->getType();
265 }
266 return true;
267 }
268
269 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
270 // See if this is a deleted function.
271 if (FD->isDeleted()) {
272 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
273 if (Ctor && Ctor->isInheritingConstructor())
274 Diag(Loc, diag::err_deleted_inherited_ctor_use)
275 << Ctor->getParent()
276 << Ctor->getInheritedConstructor().getConstructor()->getParent();
277 else {
278 StringLiteral *Msg = FD->getDeletedMessage();
279 Diag(Loc, diag::err_deleted_function_use)
280 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
281 }
283 return true;
284 }
285
286 // [expr.prim.id]p4
287 // A program that refers explicitly or implicitly to a function with a
288 // trailing requires-clause whose constraint-expression is not satisfied,
289 // other than to declare it, is ill-formed. [...]
290 //
291 // See if this is a function with constraints that need to be satisfied.
292 // Check this before deducing the return type, as it might instantiate the
293 // definition.
294 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
295 ConstraintSatisfaction Satisfaction;
296 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
297 /*ForOverloadResolution*/ true))
298 // A diagnostic will have already been generated (non-constant
299 // constraint expression, for example)
300 return true;
301 if (!Satisfaction.IsSatisfied) {
302 Diag(Loc,
303 diag::err_reference_to_function_with_unsatisfied_constraints)
304 << D;
305 DiagnoseUnsatisfiedConstraint(Satisfaction);
306 return true;
307 }
308 }
309
310 // If the function has a deduced return type, and we can't deduce it,
311 // then we can't use it either.
312 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
313 DeduceReturnType(FD, Loc))
314 return true;
315
316 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
317 return true;
318
319 }
320
321 if (auto *Concept = dyn_cast<ConceptDecl>(D);
323 return true;
324
325 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
326 // Lambdas are only default-constructible or assignable in C++2a onwards.
327 if (MD->getParent()->isLambda() &&
329 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
330 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
331 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
333 }
334 }
335
336 auto getReferencedObjCProp = [](const NamedDecl *D) ->
337 const ObjCPropertyDecl * {
338 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
339 return MD->findPropertyDecl();
340 return nullptr;
341 };
342 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
343 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
344 return true;
345 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
346 return true;
347 }
348
349 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
350 // Only the variables omp_in and omp_out are allowed in the combiner.
351 // Only the variables omp_priv and omp_orig are allowed in the
352 // initializer-clause.
353 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
354 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
355 isa<VarDecl>(D)) {
356 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
358 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
359 return true;
360 }
361
362 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
363 // List-items in map clauses on this construct may only refer to the declared
364 // variable var and entities that could be referenced by a procedure defined
365 // at the same location.
366 // [OpenMP 5.2] Also allow iterator declared variables.
367 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
368 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
369 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
371 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
372 return true;
373 }
374
375 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
376 Diag(Loc, diag::err_use_of_empty_using_if_exists);
377 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
378 return true;
379 }
380
381 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
382 AvoidPartialAvailabilityChecks, ClassReceiver);
383
384 DiagnoseUnusedOfDecl(*this, D, Loc);
385
387
388 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
389 if (getLangOpts().getFPEvalMethod() !=
391 PP.getLastFPEvalPragmaLocation().isValid() &&
392 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
393 Diag(D->getLocation(),
394 diag::err_type_available_only_in_default_eval_method)
395 << D->getName();
396 }
397
398 if (auto *VD = dyn_cast<ValueDecl>(D))
399 checkTypeSupport(VD->getType(), Loc, VD);
400
401 if (LangOpts.SYCLIsDevice ||
402 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
403 if (!Context.getTargetInfo().isTLSSupported())
404 if (const auto *VD = dyn_cast<VarDecl>(D))
405 if (VD->getTLSKind() != VarDecl::TLS_None)
406 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
407 }
408
409 if (LangOpts.SYCLIsDevice && isa<FunctionDecl>(D))
410 SYCL().CheckDeviceUseOfDecl(D, Loc);
411
412 return false;
413}
414
416 ArrayRef<Expr *> Args) {
417 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
418 if (!Attr)
419 return;
420
421 // The number of formal parameters of the declaration.
422 unsigned NumFormalParams;
423
424 // The kind of declaration. This is also an index into a %select in
425 // the diagnostic.
426 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
427
428 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
429 NumFormalParams = MD->param_size();
430 CalleeKind = CK_Method;
431 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
432 NumFormalParams = FD->param_size();
433 CalleeKind = CK_Function;
434 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
435 QualType Ty = VD->getType();
436 const FunctionType *Fn = nullptr;
437 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
438 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
439 if (!Fn)
440 return;
441 CalleeKind = CK_Function;
442 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
443 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
444 CalleeKind = CK_Block;
445 } else {
446 return;
447 }
448
449 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
450 NumFormalParams = proto->getNumParams();
451 else
452 NumFormalParams = 0;
453 } else {
454 return;
455 }
456
457 // "NullPos" is the number of formal parameters at the end which
458 // effectively count as part of the variadic arguments. This is
459 // useful if you would prefer to not have *any* formal parameters,
460 // but the language forces you to have at least one.
461 unsigned NullPos = Attr->getNullPos();
462 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
463 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
464
465 // The number of arguments which should follow the sentinel.
466 unsigned NumArgsAfterSentinel = Attr->getSentinel();
467
468 // If there aren't enough arguments for all the formal parameters,
469 // the sentinel, and the args after the sentinel, complain.
470 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
471 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
472 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
473 return;
474 }
475
476 // Otherwise, find the sentinel expression.
477 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
478 if (!SentinelExpr)
479 return;
480 if (SentinelExpr->isValueDependent())
481 return;
482 if (Context.isSentinelNullExpr(SentinelExpr))
483 return;
484
485 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
486 // or 'NULL' if those are actually defined in the context. Only use
487 // 'nil' for ObjC methods, where it's much more likely that the
488 // variadic arguments form a list of object pointers.
489 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
490 std::string NullValue;
491 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
492 NullValue = "nil";
493 else if (getLangOpts().CPlusPlus11)
494 NullValue = "nullptr";
495 else if (PP.isMacroDefined("NULL"))
496 NullValue = "NULL";
497 else
498 NullValue = "(void*) 0";
499
500 if (MissingNilLoc.isInvalid())
501 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
502 else
503 Diag(MissingNilLoc, diag::warn_missing_sentinel)
504 << int(CalleeKind)
505 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
506 Diag(D->getLocation(), diag::note_sentinel_here)
507 << int(CalleeKind) << Attr->getRange();
508}
509
511 return E ? E->getSourceRange() : SourceRange();
512}
513
514//===----------------------------------------------------------------------===//
515// Standard Promotions and Conversions
516//===----------------------------------------------------------------------===//
517
518/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
520 // Handle any placeholder expressions which made it here.
521 if (E->hasPlaceholderType()) {
523 if (result.isInvalid()) return ExprError();
524 E = result.get();
525 }
526
527 QualType Ty = E->getType();
528 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
529
530 if (Ty->isFunctionType()) {
531 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
532 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
534 return ExprError();
535
536 E = ImpCastExprToType(E, Context.getPointerType(Ty),
537 CK_FunctionToPointerDecay).get();
538 } else if (Ty->isArrayType()) {
539 // In C90 mode, arrays only promote to pointers if the array expression is
540 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
541 // type 'array of type' is converted to an expression that has type 'pointer
542 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
543 // that has type 'array of type' ...". The relevant change is "an lvalue"
544 // (C90) to "an expression" (C99).
545 //
546 // C++ 4.2p1:
547 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
548 // T" can be converted to an rvalue of type "pointer to T".
549 //
550 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
551 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
552 CK_ArrayToPointerDecay);
553 if (Res.isInvalid())
554 return ExprError();
555 E = Res.get();
556 }
557 }
558 return E;
559}
560
562 // Check to see if we are dereferencing a null pointer. If so,
563 // and if not volatile-qualified, this is undefined behavior that the
564 // optimizer will delete, so warn about it. People sometimes try to use this
565 // to get a deterministic trap and are surprised by clang's behavior. This
566 // only handles the pattern "*null", which is a very syntactic check.
567 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
568 if (UO && UO->getOpcode() == UO_Deref &&
569 UO->getSubExpr()->getType()->isPointerType()) {
570 const LangAS AS =
571 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
572 if ((!isTargetAddressSpace(AS) ||
573 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
574 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
576 !UO->getType().isVolatileQualified()) {
577 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
578 S.PDiag(diag::warn_indirection_through_null)
579 << UO->getSubExpr()->getSourceRange());
580 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
581 S.PDiag(diag::note_indirection_through_null));
582 }
583 }
584}
585
586static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
587 SourceLocation AssignLoc,
588 const Expr* RHS) {
589 const ObjCIvarDecl *IV = OIRE->getDecl();
590 if (!IV)
591 return;
592
593 DeclarationName MemberName = IV->getDeclName();
595 if (!Member || !Member->isStr("isa"))
596 return;
597
598 const Expr *Base = OIRE->getBase();
599 QualType BaseType = Base->getType();
600 if (OIRE->isArrow())
601 BaseType = BaseType->getPointeeType();
602 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
603 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
604 ObjCInterfaceDecl *ClassDeclared = nullptr;
605 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
606 if (!ClassDeclared->getSuperClass()
607 && (*ClassDeclared->ivar_begin()) == IV) {
608 if (RHS) {
609 NamedDecl *ObjectSetClass =
611 &S.Context.Idents.get("object_setClass"),
613 if (ObjectSetClass) {
614 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
615 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
617 "object_setClass(")
619 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
620 << FixItHint::CreateInsertion(RHSLocEnd, ")");
621 }
622 else
623 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
624 } else {
625 NamedDecl *ObjectGetClass =
627 &S.Context.Idents.get("object_getClass"),
629 if (ObjectGetClass)
630 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
632 "object_getClass(")
634 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
635 else
636 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
637 }
638 S.Diag(IV->getLocation(), diag::note_ivar_decl);
639 }
640 }
641}
642
644 // Handle any placeholder expressions which made it here.
645 if (E->hasPlaceholderType()) {
647 if (result.isInvalid()) return ExprError();
648 E = result.get();
649 }
650
651 // C++ [conv.lval]p1:
652 // A glvalue of a non-function, non-array type T can be
653 // converted to a prvalue.
654 if (!E->isGLValue()) return E;
655
656 QualType T = E->getType();
657 assert(!T.isNull() && "r-value conversion on typeless expression?");
658
659 // lvalue-to-rvalue conversion cannot be applied to types that decay to
660 // pointers (i.e. function or array types).
661 if (T->canDecayToPointerType())
662 return E;
663
664 // We don't want to throw lvalue-to-rvalue casts on top of
665 // expressions of certain types in C++.
666 if (getLangOpts().CPlusPlus) {
667 if (T == Context.OverloadTy || T->isRecordType() ||
668 (T->isDependentType() && !T->isAnyPointerType() &&
669 !T->isMemberPointerType()))
670 return E;
671 }
672
673 // The C standard is actually really unclear on this point, and
674 // DR106 tells us what the result should be but not why. It's
675 // generally best to say that void types just doesn't undergo
676 // lvalue-to-rvalue at all. Note that expressions of unqualified
677 // 'void' type are never l-values, but qualified void can be.
678 if (T->isVoidType())
679 return E;
680
681 // OpenCL usually rejects direct accesses to values of 'half' type.
682 if (getLangOpts().OpenCL &&
683 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
684 T->isHalfType()) {
685 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
686 << 0 << T;
687 return ExprError();
688 }
689
691 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
692 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
693 &Context.Idents.get("object_getClass"),
695 if (ObjectGetClass)
696 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
697 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
699 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
700 else
701 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
702 }
703 else if (const ObjCIvarRefExpr *OIRE =
704 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
705 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
706
707 // C++ [conv.lval]p1:
708 // [...] If T is a non-class type, the type of the prvalue is the
709 // cv-unqualified version of T. Otherwise, the type of the
710 // rvalue is T.
711 //
712 // C99 6.3.2.1p2:
713 // If the lvalue has qualified type, the value has the unqualified
714 // version of the type of the lvalue; otherwise, the value has the
715 // type of the lvalue.
716 if (T.hasQualifiers())
717 T = T.getUnqualifiedType();
718
719 // Under the MS ABI, lock down the inheritance model now.
720 if (T->isMemberPointerType() &&
721 Context.getTargetInfo().getCXXABI().isMicrosoft())
722 (void)isCompleteType(E->getExprLoc(), T);
723
725 if (Res.isInvalid())
726 return Res;
727 E = Res.get();
728
729 // Loading a __weak object implicitly retains the value, so we need a cleanup to
730 // balance that.
732 Cleanup.setExprNeedsCleanups(true);
733
735 Cleanup.setExprNeedsCleanups(true);
736
738 return ExprError();
739
740 // C++ [conv.lval]p3:
741 // If T is cv std::nullptr_t, the result is a null pointer constant.
742 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
743 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
745
746 // C11 6.3.2.1p2:
747 // ... if the lvalue has atomic type, the value has the non-atomic version
748 // of the type of the lvalue ...
749 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
750 T = Atomic->getValueType().getUnqualifiedType();
751 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
752 nullptr, VK_PRValue, FPOptionsOverride());
753 }
754
755 return Res;
756}
757
760 if (Res.isInvalid())
761 return ExprError();
762 Res = DefaultLvalueConversion(Res.get());
763 if (Res.isInvalid())
764 return ExprError();
765 return Res;
766}
767
769 QualType Ty = E->getType();
770 ExprResult Res = E;
771 // Only do implicit cast for a function type, but not for a pointer
772 // to function type.
773 if (Ty->isFunctionType()) {
774 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
775 CK_FunctionToPointerDecay);
776 if (Res.isInvalid())
777 return ExprError();
778 }
779 Res = DefaultLvalueConversion(Res.get());
780 if (Res.isInvalid())
781 return ExprError();
782 return Res.get();
783}
784
785/// UsualUnaryFPConversions - Promotes floating-point types according to the
786/// current language semantics.
788 QualType Ty = E->getType();
789 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
790
791 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
792 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
793 (getLangOpts().getFPEvalMethod() !=
795 PP.getLastFPEvalPragmaLocation().isValid())) {
796 switch (EvalMethod) {
797 default:
798 llvm_unreachable("Unrecognized float evaluation method");
799 break;
801 llvm_unreachable("Float evaluation method should be set by now");
802 break;
804 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
805 // Widen the expression to double.
806 return Ty->isComplexType()
808 Context.getComplexType(Context.DoubleTy),
809 CK_FloatingComplexCast)
810 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
811 break;
813 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
814 // Widen the expression to long double.
815 return Ty->isComplexType()
817 E, Context.getComplexType(Context.LongDoubleTy),
818 CK_FloatingComplexCast)
819 : ImpCastExprToType(E, Context.LongDoubleTy,
820 CK_FloatingCast);
821 break;
822 }
823 }
824
825 // Half FP have to be promoted to float unless it is natively supported
826 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
827 return ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast);
828
829 return E;
830}
831
832/// UsualUnaryConversions - Performs various conversions that are common to most
833/// operators (C99 6.3). The conversions of array and function types are
834/// sometimes suppressed. For example, the array->pointer conversion doesn't
835/// apply if the array is an argument to the sizeof or address (&) operators.
836/// In these instances, this routine should *not* be called.
838 // First, convert to an r-value.
840 if (Res.isInvalid())
841 return ExprError();
842
843 // Promote floating-point types.
844 Res = UsualUnaryFPConversions(Res.get());
845 if (Res.isInvalid())
846 return ExprError();
847 E = Res.get();
848
849 QualType Ty = E->getType();
850 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
851
852 // Try to perform integral promotions if the object has a theoretically
853 // promotable type.
855 // C99 6.3.1.1p2:
856 //
857 // The following may be used in an expression wherever an int or
858 // unsigned int may be used:
859 // - an object or expression with an integer type whose integer
860 // conversion rank is less than or equal to the rank of int
861 // and unsigned int.
862 // - A bit-field of type _Bool, int, signed int, or unsigned int.
863 //
864 // If an int can represent all values of the original type, the
865 // value is converted to an int; otherwise, it is converted to an
866 // unsigned int. These are called the integer promotions. All
867 // other types are unchanged by the integer promotions.
868
869 QualType PTy = Context.isPromotableBitField(E);
870 if (!PTy.isNull()) {
871 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
872 return E;
873 }
874 if (Context.isPromotableIntegerType(Ty)) {
875 QualType PT = Context.getPromotedIntegerType(Ty);
876 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
877 return E;
878 }
879 }
880 return E;
881}
882
883/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
884/// do not have a prototype. Arguments that have type float or __fp16
885/// are promoted to double. All other argument types are converted by
886/// UsualUnaryConversions().
888 QualType Ty = E->getType();
889 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
890
892 if (Res.isInvalid())
893 return ExprError();
894 E = Res.get();
895
896 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
897 // promote to double.
898 // Note that default argument promotion applies only to float (and
899 // half/fp16); it does not apply to _Float16.
900 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
901 if (BTy && (BTy->getKind() == BuiltinType::Half ||
902 BTy->getKind() == BuiltinType::Float)) {
903 if (getLangOpts().OpenCL &&
904 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
905 if (BTy->getKind() == BuiltinType::Half) {
906 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
907 }
908 } else {
909 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
910 }
911 }
912 if (BTy &&
913 getLangOpts().getExtendIntArgs() ==
915 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
916 Context.getTypeSizeInChars(BTy) <
917 Context.getTypeSizeInChars(Context.LongLongTy)) {
918 E = (Ty->isUnsignedIntegerType())
919 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
920 .get()
921 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
922 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
923 "Unexpected typesize for LongLongTy");
924 }
925
926 // C++ performs lvalue-to-rvalue conversion as a default argument
927 // promotion, even on class types, but note:
928 // C++11 [conv.lval]p2:
929 // When an lvalue-to-rvalue conversion occurs in an unevaluated
930 // operand or a subexpression thereof the value contained in the
931 // referenced object is not accessed. Otherwise, if the glvalue
932 // has a class type, the conversion copy-initializes a temporary
933 // of type T from the glvalue and the result of the conversion
934 // is a prvalue for the temporary.
935 // FIXME: add some way to gate this entire thing for correctness in
936 // potentially potentially evaluated contexts.
940 E->getExprLoc(), E);
941 if (Temp.isInvalid())
942 return ExprError();
943 E = Temp.get();
944 }
945
946 // C++ [expr.call]p7, per CWG722:
947 // An argument that has (possibly cv-qualified) type std::nullptr_t is
948 // converted to void* ([conv.ptr]).
949 // (This does not apply to C23 nullptr)
951 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
952
953 return E;
954}
955
957 if (Ty->isIncompleteType()) {
958 // C++11 [expr.call]p7:
959 // After these conversions, if the argument does not have arithmetic,
960 // enumeration, pointer, pointer to member, or class type, the program
961 // is ill-formed.
962 //
963 // Since we've already performed null pointer conversion, array-to-pointer
964 // decay and function-to-pointer decay, the only such type in C++ is cv
965 // void. This also handles initializer lists as variadic arguments.
966 if (Ty->isVoidType())
967 return VarArgKind::Invalid;
968
969 if (Ty->isObjCObjectType())
970 return VarArgKind::Invalid;
971 return VarArgKind::Valid;
972 }
973
975 return VarArgKind::Invalid;
976
977 if (Context.getTargetInfo().getTriple().isWasm() &&
979 return VarArgKind::Invalid;
980 }
981
982 if (Ty.isCXX98PODType(Context))
983 return VarArgKind::Valid;
984
985 // C++11 [expr.call]p7:
986 // Passing a potentially-evaluated argument of class type (Clause 9)
987 // having a non-trivial copy constructor, a non-trivial move constructor,
988 // or a non-trivial destructor, with no corresponding parameter,
989 // is conditionally-supported with implementation-defined semantics.
992 if (!Record->hasNonTrivialCopyConstructor() &&
993 !Record->hasNonTrivialMoveConstructor() &&
994 !Record->hasNonTrivialDestructor())
996
997 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
998 return VarArgKind::Valid;
999
1000 if (Ty->isObjCObjectType())
1001 return VarArgKind::Invalid;
1002
1003 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1004 return VarArgKind::Valid;
1005
1006 if (getLangOpts().MSVCCompat)
1008
1009 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1010 return VarArgKind::Valid;
1011
1012 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1013 // permitted to reject them. We should consider doing so.
1014 return VarArgKind::Undefined;
1015}
1016
1018 // Don't allow one to pass an Objective-C interface to a vararg.
1019 const QualType &Ty = E->getType();
1020 VarArgKind VAK = isValidVarArgType(Ty);
1021
1022 // Complain about passing non-POD types through varargs.
1023 switch (VAK) {
1026 E->getBeginLoc(), nullptr,
1027 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1028 [[fallthrough]];
1029 case VarArgKind::Valid:
1030 if (Ty->isRecordType()) {
1031 // This is unlikely to be what the user intended. If the class has a
1032 // 'c_str' member function, the user probably meant to call that.
1033 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1034 PDiag(diag::warn_pass_class_arg_to_vararg)
1035 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1036 }
1037 break;
1038
1041 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1042 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1043 << getLangOpts().CPlusPlus11 << Ty << CT);
1044 break;
1045
1048 Diag(E->getBeginLoc(),
1049 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1050 << Ty << CT;
1051 else if (Ty->isObjCObjectType())
1052 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1053 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1054 << Ty << CT);
1055 else
1056 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1057 << isa<InitListExpr>(E) << Ty << CT;
1058 break;
1059 }
1060}
1061
1063 FunctionDecl *FDecl) {
1064 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1065 // Strip the unbridged-cast placeholder expression off, if applicable.
1066 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1067 (CT == VariadicCallType::Method ||
1068 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1069 E = ObjC().stripARCUnbridgedCast(E);
1070
1071 // Otherwise, do normal placeholder checking.
1072 } else {
1073 ExprResult ExprRes = CheckPlaceholderExpr(E);
1074 if (ExprRes.isInvalid())
1075 return ExprError();
1076 E = ExprRes.get();
1077 }
1078 }
1079
1081 if (ExprRes.isInvalid())
1082 return ExprError();
1083
1084 // Copy blocks to the heap.
1085 if (ExprRes.get()->getType()->isBlockPointerType())
1086 maybeExtendBlockObject(ExprRes);
1087
1088 E = ExprRes.get();
1089
1090 // Diagnostics regarding non-POD argument types are
1091 // emitted along with format string checking in Sema::CheckFunctionCall().
1093 // Turn this into a trap.
1094 CXXScopeSpec SS;
1095 SourceLocation TemplateKWLoc;
1096 UnqualifiedId Name;
1097 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1098 E->getBeginLoc());
1099 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1100 /*HasTrailingLParen=*/true,
1101 /*IsAddressOfOperand=*/false);
1102 if (TrapFn.isInvalid())
1103 return ExprError();
1104
1105 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1106 E->getEndLoc());
1107 if (Call.isInvalid())
1108 return ExprError();
1109
1110 ExprResult Comma =
1111 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1112 if (Comma.isInvalid())
1113 return ExprError();
1114 return Comma.get();
1115 }
1116
1117 if (!getLangOpts().CPlusPlus &&
1119 diag::err_call_incomplete_argument))
1120 return ExprError();
1121
1122 return E;
1123}
1124
1125/// Convert complex integers to complex floats and real integers to
1126/// real floats as required for complex arithmetic. Helper function of
1127/// UsualArithmeticConversions()
1128///
1129/// \return false if the integer expression is an integer type and is
1130/// successfully converted to the (complex) float type.
1132 ExprResult &ComplexExpr,
1133 QualType IntTy,
1134 QualType ComplexTy,
1135 bool SkipCast) {
1136 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1137 if (SkipCast) return false;
1138 if (IntTy->isIntegerType()) {
1139 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1140 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1141 } else {
1142 assert(IntTy->isComplexIntegerType());
1143 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1144 CK_IntegralComplexToFloatingComplex);
1145 }
1146 return false;
1147}
1148
1149// This handles complex/complex, complex/float, or float/complex.
1150// When both operands are complex, the shorter operand is converted to the
1151// type of the longer, and that is the type of the result. This corresponds
1152// to what is done when combining two real floating-point operands.
1153// The fun begins when size promotion occur across type domains.
1154// From H&S 6.3.4: When one operand is complex and the other is a real
1155// floating-point type, the less precise type is converted, within it's
1156// real or complex domain, to the precision of the other type. For example,
1157// when combining a "long double" with a "double _Complex", the
1158// "double _Complex" is promoted to "long double _Complex".
1160 QualType ShorterType,
1161 QualType LongerType,
1162 bool PromotePrecision) {
1163 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1164 QualType Result =
1165 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1166
1167 if (PromotePrecision) {
1168 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1169 Shorter =
1170 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1171 } else {
1172 if (LongerIsComplex)
1173 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1174 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1175 }
1176 }
1177 return Result;
1178}
1179
1180/// Handle arithmetic conversion with complex types. Helper function of
1181/// UsualArithmeticConversions()
1183 ExprResult &RHS, QualType LHSType,
1184 QualType RHSType, bool IsCompAssign) {
1185 // Handle (complex) integer types.
1186 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1187 /*SkipCast=*/false))
1188 return LHSType;
1189 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1190 /*SkipCast=*/IsCompAssign))
1191 return RHSType;
1192
1193 // Compute the rank of the two types, regardless of whether they are complex.
1194 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1195 if (Order < 0)
1196 // Promote the precision of the LHS if not an assignment.
1197 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1198 /*PromotePrecision=*/!IsCompAssign);
1199 // Promote the precision of the RHS unless it is already the same as the LHS.
1200 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1201 /*PromotePrecision=*/Order > 0);
1202}
1203
1204/// Handle arithmetic conversion from integer to float. Helper function
1205/// of UsualArithmeticConversions()
1207 ExprResult &IntExpr,
1208 QualType FloatTy, QualType IntTy,
1209 bool ConvertFloat, bool ConvertInt) {
1210 if (IntTy->isIntegerType()) {
1211 if (ConvertInt)
1212 // Convert intExpr to the lhs floating point type.
1213 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1214 CK_IntegralToFloating);
1215 return FloatTy;
1216 }
1217
1218 // Convert both sides to the appropriate complex float.
1219 assert(IntTy->isComplexIntegerType());
1220 QualType result = S.Context.getComplexType(FloatTy);
1221
1222 // _Complex int -> _Complex float
1223 if (ConvertInt)
1224 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1225 CK_IntegralComplexToFloatingComplex);
1226
1227 // float -> _Complex float
1228 if (ConvertFloat)
1229 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1230 CK_FloatingRealToComplex);
1231
1232 return result;
1233}
1234
1235/// Handle arithmethic conversion with floating point types. Helper
1236/// function of UsualArithmeticConversions()
1238 ExprResult &RHS, QualType LHSType,
1239 QualType RHSType, bool IsCompAssign) {
1240 bool LHSFloat = LHSType->isRealFloatingType();
1241 bool RHSFloat = RHSType->isRealFloatingType();
1242
1243 // N1169 4.1.4: If one of the operands has a floating type and the other
1244 // operand has a fixed-point type, the fixed-point operand
1245 // is converted to the floating type [...]
1246 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1247 if (LHSFloat)
1248 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1249 else if (!IsCompAssign)
1250 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1251 return LHSFloat ? LHSType : RHSType;
1252 }
1253
1254 // If we have two real floating types, convert the smaller operand
1255 // to the bigger result.
1256 if (LHSFloat && RHSFloat) {
1257 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1258 if (order > 0) {
1259 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1260 return LHSType;
1261 }
1262
1263 assert(order < 0 && "illegal float comparison");
1264 if (!IsCompAssign)
1265 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1266 return RHSType;
1267 }
1268
1269 if (LHSFloat) {
1270 // Half FP has to be promoted to float unless it is natively supported
1271 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1272 LHSType = S.Context.FloatTy;
1273
1274 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1275 /*ConvertFloat=*/!IsCompAssign,
1276 /*ConvertInt=*/ true);
1277 }
1278 assert(RHSFloat);
1279 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1280 /*ConvertFloat=*/ true,
1281 /*ConvertInt=*/!IsCompAssign);
1282}
1283
1284/// Diagnose attempts to convert between __float128, __ibm128 and
1285/// long double if there is no support for such conversion.
1286/// Helper function of UsualArithmeticConversions().
1287static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1288 QualType RHSType) {
1289 // No issue if either is not a floating point type.
1290 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1291 return false;
1292
1293 // No issue if both have the same 128-bit float semantics.
1294 auto *LHSComplex = LHSType->getAs<ComplexType>();
1295 auto *RHSComplex = RHSType->getAs<ComplexType>();
1296
1297 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1298 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1299
1300 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1301 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1302
1303 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1304 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1305 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1306 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1307 return false;
1308
1309 return true;
1310}
1311
1312typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1313
1314namespace {
1315/// These helper callbacks are placed in an anonymous namespace to
1316/// permit their use as function template parameters.
1317ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1318 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1319}
1320
1321ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1322 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1323 CK_IntegralComplexCast);
1324}
1325}
1326
1327/// Handle integer arithmetic conversions. Helper function of
1328/// UsualArithmeticConversions()
1329template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1331 ExprResult &RHS, QualType LHSType,
1332 QualType RHSType, bool IsCompAssign) {
1333 // The rules for this case are in C99 6.3.1.8
1334 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1335 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1336 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1337 if (LHSSigned == RHSSigned) {
1338 // Same signedness; use the higher-ranked type
1339 if (order >= 0) {
1340 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1341 return LHSType;
1342 } else if (!IsCompAssign)
1343 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1344 return RHSType;
1345 } else if (order != (LHSSigned ? 1 : -1)) {
1346 // The unsigned type has greater than or equal rank to the
1347 // signed type, so use the unsigned type
1348 if (RHSSigned) {
1349 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1350 return LHSType;
1351 } else if (!IsCompAssign)
1352 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1353 return RHSType;
1354 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1355 // The two types are different widths; if we are here, that
1356 // means the signed type is larger than the unsigned type, so
1357 // use the signed type.
1358 if (LHSSigned) {
1359 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1360 return LHSType;
1361 } else if (!IsCompAssign)
1362 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1363 return RHSType;
1364 } else {
1365 // The signed type is higher-ranked than the unsigned type,
1366 // but isn't actually any bigger (like unsigned int and long
1367 // on most 32-bit systems). Use the unsigned type corresponding
1368 // to the signed type.
1369 QualType result =
1370 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1371 RHS = (*doRHSCast)(S, RHS.get(), result);
1372 if (!IsCompAssign)
1373 LHS = (*doLHSCast)(S, LHS.get(), result);
1374 return result;
1375 }
1376}
1377
1378/// Handle conversions with GCC complex int extension. Helper function
1379/// of UsualArithmeticConversions()
1381 ExprResult &RHS, QualType LHSType,
1382 QualType RHSType,
1383 bool IsCompAssign) {
1384 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1385 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1386
1387 if (LHSComplexInt && RHSComplexInt) {
1388 QualType LHSEltType = LHSComplexInt->getElementType();
1389 QualType RHSEltType = RHSComplexInt->getElementType();
1390 QualType ScalarType =
1392 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1393
1394 return S.Context.getComplexType(ScalarType);
1395 }
1396
1397 if (LHSComplexInt) {
1398 QualType LHSEltType = LHSComplexInt->getElementType();
1399 QualType ScalarType =
1401 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1403 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1404 CK_IntegralRealToComplex);
1405
1406 return ComplexType;
1407 }
1408
1409 assert(RHSComplexInt);
1410
1411 QualType RHSEltType = RHSComplexInt->getElementType();
1412 QualType ScalarType =
1414 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1416
1417 if (!IsCompAssign)
1418 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1419 CK_IntegralRealToComplex);
1420 return ComplexType;
1421}
1422
1424 ExprResult &RHS,
1425 QualType LHSType,
1426 QualType RHSType,
1427 bool IsCompAssign) {
1428
1429 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1430 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1431
1432 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1433 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1434
1435 bool LHSHasTrap =
1436 LhsOBT && LhsOBT->getBehaviorKind() ==
1437 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1438 bool RHSHasTrap =
1439 RhsOBT && RhsOBT->getBehaviorKind() ==
1440 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1441 bool LHSHasWrap =
1442 LhsOBT && LhsOBT->getBehaviorKind() ==
1443 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1444 bool RHSHasWrap =
1445 RhsOBT && RhsOBT->getBehaviorKind() ==
1446 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1447
1448 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1449 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1450
1451 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1452 if (LHSHasTrap || RHSHasTrap)
1453 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1454 else if (LHSHasWrap || RHSHasWrap)
1455 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1456
1457 QualType LHSConvType = LHSUnderlyingType;
1458 QualType RHSConvType = RHSUnderlyingType;
1459 if (DominantBehavior) {
1460 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1461 LHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1462 LHSUnderlyingType);
1463 else
1464 LHSConvType = LHSType;
1465
1466 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1467 RHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1468 RHSUnderlyingType);
1469 else
1470 RHSConvType = RHSType;
1471 }
1472
1474 S, LHS, RHS, LHSConvType, RHSConvType, IsCompAssign);
1475}
1476
1477/// Return the rank of a given fixed point or integer type. The value itself
1478/// doesn't matter, but the values must be increasing with proper increasing
1479/// rank as described in N1169 4.1.1.
1480static unsigned GetFixedPointRank(QualType Ty) {
1481 const auto *BTy = Ty->getAs<BuiltinType>();
1482 assert(BTy && "Expected a builtin type.");
1483
1484 switch (BTy->getKind()) {
1485 case BuiltinType::ShortFract:
1486 case BuiltinType::UShortFract:
1487 case BuiltinType::SatShortFract:
1488 case BuiltinType::SatUShortFract:
1489 return 1;
1490 case BuiltinType::Fract:
1491 case BuiltinType::UFract:
1492 case BuiltinType::SatFract:
1493 case BuiltinType::SatUFract:
1494 return 2;
1495 case BuiltinType::LongFract:
1496 case BuiltinType::ULongFract:
1497 case BuiltinType::SatLongFract:
1498 case BuiltinType::SatULongFract:
1499 return 3;
1500 case BuiltinType::ShortAccum:
1501 case BuiltinType::UShortAccum:
1502 case BuiltinType::SatShortAccum:
1503 case BuiltinType::SatUShortAccum:
1504 return 4;
1505 case BuiltinType::Accum:
1506 case BuiltinType::UAccum:
1507 case BuiltinType::SatAccum:
1508 case BuiltinType::SatUAccum:
1509 return 5;
1510 case BuiltinType::LongAccum:
1511 case BuiltinType::ULongAccum:
1512 case BuiltinType::SatLongAccum:
1513 case BuiltinType::SatULongAccum:
1514 return 6;
1515 default:
1516 if (BTy->isInteger())
1517 return 0;
1518 llvm_unreachable("Unexpected fixed point or integer type");
1519 }
1520}
1521
1522/// handleFixedPointConversion - Fixed point operations between fixed
1523/// point types and integers or other fixed point types do not fall under
1524/// usual arithmetic conversion since these conversions could result in loss
1525/// of precsision (N1169 4.1.4). These operations should be calculated with
1526/// the full precision of their result type (N1169 4.1.6.2.1).
1528 QualType RHSTy) {
1529 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1530 "Expected at least one of the operands to be a fixed point type");
1531 assert((LHSTy->isFixedPointOrIntegerType() ||
1532 RHSTy->isFixedPointOrIntegerType()) &&
1533 "Special fixed point arithmetic operation conversions are only "
1534 "applied to ints or other fixed point types");
1535
1536 // If one operand has signed fixed-point type and the other operand has
1537 // unsigned fixed-point type, then the unsigned fixed-point operand is
1538 // converted to its corresponding signed fixed-point type and the resulting
1539 // type is the type of the converted operand.
1540 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1542 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1544
1545 // The result type is the type with the highest rank, whereby a fixed-point
1546 // conversion rank is always greater than an integer conversion rank; if the
1547 // type of either of the operands is a saturating fixedpoint type, the result
1548 // type shall be the saturating fixed-point type corresponding to the type
1549 // with the highest rank; the resulting value is converted (taking into
1550 // account rounding and overflow) to the precision of the resulting type.
1551 // Same ranks between signed and unsigned types are resolved earlier, so both
1552 // types are either signed or both unsigned at this point.
1553 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1554 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1555
1556 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1557
1559 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1560
1561 return ResultTy;
1562}
1563
1564/// Check that the usual arithmetic conversions can be performed on this pair of
1565/// expressions that might be of enumeration type.
1567 SourceLocation Loc,
1568 ArithConvKind ACK) {
1569 // C++2a [expr.arith.conv]p1:
1570 // If one operand is of enumeration type and the other operand is of a
1571 // different enumeration type or a floating-point type, this behavior is
1572 // deprecated ([depr.arith.conv.enum]).
1573 //
1574 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1575 // Eventually we will presumably reject these cases (in C++23 onwards?).
1577 R = RHS->getEnumCoercedType(Context);
1578 bool LEnum = L->isUnscopedEnumerationType(),
1579 REnum = R->isUnscopedEnumerationType();
1580 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1581 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1582 (REnum && L->isFloatingType())) {
1583 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1585 ? diag::warn_arith_conv_enum_float_cxx20
1586 : diag::warn_arith_conv_enum_float)
1587 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1588 << L << R;
1589 } else if (!IsCompAssign && LEnum && REnum &&
1590 !Context.hasSameUnqualifiedType(L, R)) {
1591 unsigned DiagID;
1592 // In C++ 26, usual arithmetic conversions between 2 different enum types
1593 // are ill-formed.
1595 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1596 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1597 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1598 // If either enumeration type is unnamed, it's less likely that the
1599 // user cares about this, but this situation is still deprecated in
1600 // C++2a. Use a different warning group.
1601 DiagID = getLangOpts().CPlusPlus20
1602 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1603 : diag::warn_arith_conv_mixed_anon_enum_types;
1604 } else if (ACK == ArithConvKind::Conditional) {
1605 // Conditional expressions are separated out because they have
1606 // historically had a different warning flag.
1607 DiagID = getLangOpts().CPlusPlus20
1608 ? diag::warn_conditional_mixed_enum_types_cxx20
1609 : diag::warn_conditional_mixed_enum_types;
1610 } else if (ACK == ArithConvKind::Comparison) {
1611 // Comparison expressions are separated out because they have
1612 // historically had a different warning flag.
1613 DiagID = getLangOpts().CPlusPlus20
1614 ? diag::warn_comparison_mixed_enum_types_cxx20
1615 : diag::warn_comparison_mixed_enum_types;
1616 } else {
1617 DiagID = getLangOpts().CPlusPlus20
1618 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1619 : diag::warn_arith_conv_mixed_enum_types;
1620 }
1621 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1622 << (int)ACK << L << R;
1623 }
1624}
1625
1627 Expr *RHS, SourceLocation Loc,
1628 ArithConvKind ACK) {
1629 QualType LHSType = LHS->getType().getUnqualifiedType();
1630 QualType RHSType = RHS->getType().getUnqualifiedType();
1631
1632 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1633 !RHSType->isUnicodeCharacterType())
1634 return;
1635
1636 if (ACK == ArithConvKind::Comparison) {
1637 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1638 return;
1639
1640 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1641 if (T->isChar8Type())
1642 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1643 if (T->isChar16Type())
1644 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1645 assert(T->isChar32Type());
1646 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1647 };
1648
1649 Expr::EvalResult LHSRes, RHSRes;
1650 bool LHSSuccess = LHS->EvaluateAsInt(LHSRes, SemaRef.getASTContext(),
1652 SemaRef.isConstantEvaluatedContext());
1653 bool RHSuccess = RHS->EvaluateAsInt(RHSRes, SemaRef.getASTContext(),
1655 SemaRef.isConstantEvaluatedContext());
1656
1657 // Don't warn if the one known value is a representable
1658 // in the type of both expressions.
1659 if (LHSSuccess != RHSuccess) {
1660 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1661 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1662 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1663 return;
1664 }
1665
1666 if (!LHSSuccess || !RHSuccess) {
1667 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types)
1668 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1669 << RHSType;
1670 return;
1671 }
1672
1673 llvm::APSInt LHSValue(32);
1674 LHSValue = LHSRes.Val.getInt();
1675 llvm::APSInt RHSValue(32);
1676 RHSValue = RHSRes.Val.getInt();
1677
1678 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1679 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1680 if (LHSSafe && RHSSafe)
1681 return;
1682
1683 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types_constant)
1684 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1685 << FormatUTFCodeUnitAsCodepoint(LHSValue.getExtValue(), LHSType)
1686 << FormatUTFCodeUnitAsCodepoint(RHSValue.getExtValue(), RHSType);
1687 return;
1688 }
1689
1690 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1691 return;
1692
1693 SemaRef.Diag(Loc, diag::warn_arith_conv_mixed_unicode_types)
1694 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1695 << RHSType;
1696}
1697
1698/// UsualArithmeticConversions - Performs various conversions that are common to
1699/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1700/// routine returns the first non-arithmetic type found. The client is
1701/// responsible for emitting appropriate error diagnostics.
1703 SourceLocation Loc,
1704 ArithConvKind ACK) {
1705
1706 checkEnumArithmeticConversions(LHS.get(), RHS.get(), Loc, ACK);
1707
1708 CheckUnicodeArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1709
1710 if (ACK != ArithConvKind::CompAssign) {
1711 LHS = UsualUnaryConversions(LHS.get());
1712 if (LHS.isInvalid())
1713 return QualType();
1714 }
1715
1716 RHS = UsualUnaryConversions(RHS.get());
1717 if (RHS.isInvalid())
1718 return QualType();
1719
1720 // For conversion purposes, we ignore any qualifiers.
1721 // For example, "const float" and "float" are equivalent.
1722 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1723 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1724
1725 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1726 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1727 LHSType = AtomicLHS->getValueType();
1728
1729 // If both types are identical, no conversion is needed.
1730 if (Context.hasSameType(LHSType, RHSType))
1731 return Context.getCommonSugaredType(LHSType, RHSType);
1732
1733 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1734 // The caller can deal with this (e.g. pointer + int).
1735 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1736 return QualType();
1737
1738 // Apply unary and bitfield promotions to the LHS's type.
1739 QualType LHSUnpromotedType = LHSType;
1740 if (Context.isPromotableIntegerType(LHSType))
1741 LHSType = Context.getPromotedIntegerType(LHSType);
1742 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1743 if (!LHSBitfieldPromoteTy.isNull())
1744 LHSType = LHSBitfieldPromoteTy;
1745 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1746 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1747
1748 // If both types are identical, no conversion is needed.
1749 if (Context.hasSameType(LHSType, RHSType))
1750 return Context.getCommonSugaredType(LHSType, RHSType);
1751
1752 // At this point, we have two different arithmetic types.
1753
1754 // Diagnose attempts to convert between __ibm128, __float128 and long double
1755 // where such conversions currently can't be handled.
1756 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1757 return QualType();
1758
1759 // Handle complex types first (C99 6.3.1.8p1).
1760 if (LHSType->isComplexType() || RHSType->isComplexType())
1761 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1763
1764 // Now handle "real" floating types (i.e. float, double, long double).
1765 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1766 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1768
1769 // Handle GCC complex int extension.
1770 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1771 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1773
1774 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1775 return handleFixedPointConversion(*this, LHSType, RHSType);
1776
1777 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1779 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1780
1781 // Finally, we have two differing integer types.
1783 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1784}
1785
1786//===----------------------------------------------------------------------===//
1787// Semantic Analysis for various Expression Types
1788//===----------------------------------------------------------------------===//
1789
1790
1792 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1793 bool PredicateIsExpr, void *ControllingExprOrType,
1794 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1795 unsigned NumAssocs = ArgTypes.size();
1796 assert(NumAssocs == ArgExprs.size());
1797
1798 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1799 for (unsigned i = 0; i < NumAssocs; ++i) {
1800 if (ArgTypes[i])
1801 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1802 else
1803 Types[i] = nullptr;
1804 }
1805
1806 // If we have a controlling type, we need to convert it from a parsed type
1807 // into a semantic type and then pass that along.
1808 if (!PredicateIsExpr) {
1809 TypeSourceInfo *ControllingType;
1810 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1811 &ControllingType);
1812 assert(ControllingType && "couldn't get the type out of the parser");
1813 ControllingExprOrType = ControllingType;
1814 }
1815
1817 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1818 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1819 delete [] Types;
1820 return ER;
1821}
1822
1823// Helper function to determine type compatibility for C _Generic expressions.
1824// Multiple compatible types within the same _Generic expression is ambiguous
1825// and not valid.
1827 QualType U) {
1828 // Try to handle special types like OverflowBehaviorTypes
1829 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1830 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1831
1832 if (TOBT || UOBT) {
1833 if (TOBT && UOBT) {
1834 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1835 return Ctx.typesAreCompatible(TOBT->getUnderlyingType(),
1836 UOBT->getUnderlyingType());
1837 return false;
1838 }
1839 return false;
1840 }
1841
1842 // We're dealing with types that don't require special handling.
1843 return Ctx.typesAreCompatible(T, U);
1844}
1845
1847 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1848 bool PredicateIsExpr, void *ControllingExprOrType,
1850 unsigned NumAssocs = Types.size();
1851 assert(NumAssocs == Exprs.size());
1852 assert(ControllingExprOrType &&
1853 "Must have either a controlling expression or a controlling type");
1854
1855 Expr *ControllingExpr = nullptr;
1856 TypeSourceInfo *ControllingType = nullptr;
1857 if (PredicateIsExpr) {
1858 // Decay and strip qualifiers for the controlling expression type, and
1859 // handle placeholder type replacement. See committee discussion from WG14
1860 // DR423.
1864 reinterpret_cast<Expr *>(ControllingExprOrType));
1865 if (R.isInvalid())
1866 return ExprError();
1867 ControllingExpr = R.get();
1868 } else {
1869 // The extension form uses the type directly rather than converting it.
1870 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1871 if (!ControllingType)
1872 return ExprError();
1873 }
1874
1875 bool TypeErrorFound = false,
1876 IsResultDependent = ControllingExpr
1877 ? ControllingExpr->isTypeDependent()
1878 : ControllingType->getType()->isDependentType(),
1879 ContainsUnexpandedParameterPack =
1880 ControllingExpr
1881 ? ControllingExpr->containsUnexpandedParameterPack()
1882 : ControllingType->getType()->containsUnexpandedParameterPack();
1883
1884 // The controlling expression is an unevaluated operand, so side effects are
1885 // likely unintended.
1886 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1887 ControllingExpr->HasSideEffects(Context, false))
1888 Diag(ControllingExpr->getExprLoc(),
1889 diag::warn_side_effects_unevaluated_context);
1890
1891 for (unsigned i = 0; i < NumAssocs; ++i) {
1892 if (Exprs[i]->containsUnexpandedParameterPack())
1893 ContainsUnexpandedParameterPack = true;
1894
1895 if (Types[i]) {
1896 if (Types[i]->getType()->containsUnexpandedParameterPack())
1897 ContainsUnexpandedParameterPack = true;
1898
1899 if (Types[i]->getType()->isDependentType()) {
1900 IsResultDependent = true;
1901 } else {
1902 // We relax the restriction on use of incomplete types and non-object
1903 // types with the type-based extension of _Generic. Allowing incomplete
1904 // objects means those can be used as "tags" for a type-safe way to map
1905 // to a value. Similarly, matching on function types rather than
1906 // function pointer types can be useful. However, the restriction on VM
1907 // types makes sense to retain as there are open questions about how
1908 // the selection can be made at compile time.
1909 //
1910 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1911 // complete object type other than a variably modified type."
1912 // C2y removed the requirement that an expression form must
1913 // use a complete type, though it's still as-if the type has undergone
1914 // lvalue conversion. We support this as an extension in C23 and
1915 // earlier because GCC does so.
1916 unsigned D = 0;
1917 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1918 D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete
1919 : diag::ext_assoc_type_incomplete;
1920 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1921 D = diag::err_assoc_type_nonobject;
1922 else if (Types[i]->getType()->isVariablyModifiedType())
1923 D = diag::err_assoc_type_variably_modified;
1924 else if (ControllingExpr) {
1925 // Because the controlling expression undergoes lvalue conversion,
1926 // array conversion, and function conversion, an association which is
1927 // of array type, function type, or is qualified can never be
1928 // reached. We will warn about this so users are less surprised by
1929 // the unreachable association. However, we don't have to handle
1930 // function types; that's not an object type, so it's handled above.
1931 //
1932 // The logic is somewhat different for C++ because C++ has different
1933 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1934 // If T is a non-class type, the type of the prvalue is the cv-
1935 // unqualified version of T. Otherwise, the type of the prvalue is T.
1936 // The result of these rules is that all qualified types in an
1937 // association in C are unreachable, and in C++, only qualified non-
1938 // class types are unreachable.
1939 //
1940 // NB: this does not apply when the first operand is a type rather
1941 // than an expression, because the type form does not undergo
1942 // conversion.
1943 unsigned Reason = 0;
1944 QualType QT = Types[i]->getType();
1945 if (QT->isArrayType())
1946 Reason = 1;
1947 else if (QT.hasQualifiers() &&
1948 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1949 Reason = 2;
1950
1951 if (Reason)
1952 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1953 diag::warn_unreachable_association)
1954 << QT << (Reason - 1);
1955 }
1956
1957 if (D != 0) {
1958 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1959 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1960 if (getDiagnostics().getDiagnosticLevel(
1961 D, Types[i]->getTypeLoc().getBeginLoc()) >=
1963 TypeErrorFound = true;
1964 }
1965
1966 // C11 6.5.1.1p2 "No two generic associations in the same generic
1967 // selection shall specify compatible types."
1968 for (unsigned j = i+1; j < NumAssocs; ++j)
1969 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1971 Types[j]->getType())) {
1972 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1973 diag::err_assoc_compatible_types)
1974 << Types[j]->getTypeLoc().getSourceRange()
1975 << Types[j]->getType()
1976 << Types[i]->getType();
1977 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1978 diag::note_compat_assoc)
1979 << Types[i]->getTypeLoc().getSourceRange()
1980 << Types[i]->getType();
1981 TypeErrorFound = true;
1982 }
1983 }
1984 }
1985 }
1986 if (TypeErrorFound)
1987 return ExprError();
1988
1989 // If we determined that the generic selection is result-dependent, don't
1990 // try to compute the result expression.
1991 if (IsResultDependent) {
1992 if (ControllingExpr)
1993 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1994 Types, Exprs, DefaultLoc, RParenLoc,
1995 ContainsUnexpandedParameterPack);
1996 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1997 Exprs, DefaultLoc, RParenLoc,
1998 ContainsUnexpandedParameterPack);
1999 }
2000
2001 SmallVector<unsigned, 1> CompatIndices;
2002 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2003 // Look at the canonical type of the controlling expression in case it was a
2004 // deduced type like __auto_type. However, when issuing diagnostics, use the
2005 // type the user wrote in source rather than the canonical one.
2006 for (unsigned i = 0; i < NumAssocs; ++i) {
2007 if (!Types[i])
2008 DefaultIndex = i;
2009 else {
2010 bool Compatible;
2011 QualType ControllingQT =
2012 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2013 : ControllingType->getType().getCanonicalType();
2014 QualType AssocQT = Types[i]->getType();
2015
2016 Compatible =
2017 areTypesCompatibleForGeneric(Context, ControllingQT, AssocQT);
2018
2019 if (Compatible)
2020 CompatIndices.push_back(i);
2021 }
2022 }
2023
2024 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2025 TypeSourceInfo *ControllingType) {
2026 // We strip parens here because the controlling expression is typically
2027 // parenthesized in macro definitions.
2028 if (ControllingExpr)
2029 ControllingExpr = ControllingExpr->IgnoreParens();
2030
2031 SourceRange SR = ControllingExpr
2032 ? ControllingExpr->getSourceRange()
2033 : ControllingType->getTypeLoc().getSourceRange();
2034 QualType QT = ControllingExpr ? ControllingExpr->getType()
2035 : ControllingType->getType();
2036
2037 return std::make_pair(SR, QT);
2038 };
2039
2040 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2041 // type compatible with at most one of the types named in its generic
2042 // association list."
2043 if (CompatIndices.size() > 1) {
2044 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2045 SourceRange SR = P.first;
2046 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
2047 << SR << P.second << (unsigned)CompatIndices.size();
2048 for (unsigned I : CompatIndices) {
2049 Diag(Types[I]->getTypeLoc().getBeginLoc(),
2050 diag::note_compat_assoc)
2051 << Types[I]->getTypeLoc().getSourceRange()
2052 << Types[I]->getType();
2053 }
2054 return ExprError();
2055 }
2056
2057 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2058 // its controlling expression shall have type compatible with exactly one of
2059 // the types named in its generic association list."
2060 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2061 CompatIndices.size() == 0) {
2062 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2063 SourceRange SR = P.first;
2064 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
2065 return ExprError();
2066 }
2067
2068 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2069 // type name that is compatible with the type of the controlling expression,
2070 // then the result expression of the generic selection is the expression
2071 // in that generic association. Otherwise, the result expression of the
2072 // generic selection is the expression in the default generic association."
2073 unsigned ResultIndex =
2074 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2075
2076 if (ControllingExpr) {
2078 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
2079 ContainsUnexpandedParameterPack, ResultIndex);
2080 }
2082 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
2083 ContainsUnexpandedParameterPack, ResultIndex);
2084}
2085
2087 switch (Kind) {
2088 default:
2089 llvm_unreachable("unexpected TokenKind");
2090 case tok::kw___func__:
2091 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2092 case tok::kw___FUNCTION__:
2094 case tok::kw___FUNCDNAME__:
2095 return PredefinedIdentKind::FuncDName; // [MS]
2096 case tok::kw___FUNCSIG__:
2097 return PredefinedIdentKind::FuncSig; // [MS]
2098 case tok::kw_L__FUNCTION__:
2099 return PredefinedIdentKind::LFunction; // [MS]
2100 case tok::kw_L__FUNCSIG__:
2101 return PredefinedIdentKind::LFuncSig; // [MS]
2102 case tok::kw___PRETTY_FUNCTION__:
2104 }
2105}
2106
2107/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2108/// to determine the value of a PredefinedExpr. This can be either a
2109/// block, lambda, captured statement, function, otherwise a nullptr.
2112 DC = DC->getParent();
2113 return cast_or_null<Decl>(DC);
2114}
2115
2116/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2117/// location of the token and the offset of the ud-suffix within it.
2119 unsigned Offset) {
2120 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
2121 S.getLangOpts());
2122}
2123
2124/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2125/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2127 IdentifierInfo *UDSuffix,
2128 SourceLocation UDSuffixLoc,
2129 ArrayRef<Expr*> Args,
2130 SourceLocation LitEndLoc) {
2131 assert(Args.size() <= 2 && "too many arguments for literal operator");
2132
2133 QualType ArgTy[2];
2134 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2135 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2136 if (ArgTy[ArgIdx]->isArrayType())
2137 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
2138 }
2139
2140 DeclarationName OpName =
2142 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2143 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2144
2145 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2146 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
2147 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2148 /*AllowStringTemplatePack*/ false,
2149 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2150 return ExprError();
2151
2152 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
2153}
2154
2156 // StringToks needs backing storage as it doesn't hold array elements itself
2157 std::vector<Token> ExpandedToks;
2158 if (getLangOpts().MicrosoftExt)
2159 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2160
2161 StringLiteralParser Literal(StringToks, PP,
2163 if (Literal.hadError)
2164 return ExprError();
2165
2166 SmallVector<SourceLocation, 4> StringTokLocs;
2167 for (const Token &Tok : StringToks)
2168 StringTokLocs.push_back(Tok.getLocation());
2169
2170 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2172 false, {}, StringTokLocs);
2173
2174 if (!Literal.getUDSuffix().empty()) {
2175 SourceLocation UDSuffixLoc =
2176 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2177 Literal.getUDSuffixOffset());
2178 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2179 }
2180
2181 return Lit;
2182}
2183
2184std::vector<Token>
2186 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2187 // local macros that expand to string literals that may be concatenated.
2188 // These macros are expanded here (in Sema), because StringLiteralParser
2189 // (in Lex) doesn't know the enclosing function (because it hasn't been
2190 // parsed yet).
2191 assert(getLangOpts().MicrosoftExt);
2192
2193 // Note: Although function local macros are defined only inside functions,
2194 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2195 // expansion of macros into empty string literals without additional checks.
2196 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2197 if (!CurrentDecl)
2198 CurrentDecl = Context.getTranslationUnitDecl();
2199
2200 std::vector<Token> ExpandedToks;
2201 ExpandedToks.reserve(Toks.size());
2202 for (const Token &Tok : Toks) {
2204 assert(tok::isStringLiteral(Tok.getKind()));
2205 ExpandedToks.emplace_back(Tok);
2206 continue;
2207 }
2208 if (isa<TranslationUnitDecl>(CurrentDecl))
2209 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2210 // Stringify predefined expression
2211 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2212 << Tok.getKind();
2213 SmallString<64> Str;
2214 llvm::raw_svector_ostream OS(Str);
2215 Token &Exp = ExpandedToks.emplace_back();
2216 Exp.startToken();
2217 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2218 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2219 OS << 'L';
2220 Exp.setKind(tok::wide_string_literal);
2221 } else {
2222 Exp.setKind(tok::string_literal);
2223 }
2224 OS << '"'
2226 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2227 << '"';
2228 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2229 }
2230 return ExpandedToks;
2231}
2232
2235 assert(!StringToks.empty() && "Must have at least one string!");
2236
2237 // StringToks needs backing storage as it doesn't hold array elements itself
2238 std::vector<Token> ExpandedToks;
2239 if (getLangOpts().MicrosoftExt)
2240 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2241
2242 StringLiteralParser Literal(StringToks, PP);
2243 if (Literal.hadError)
2244 return ExprError();
2245
2246 SmallVector<SourceLocation, 4> StringTokLocs;
2247 for (const Token &Tok : StringToks)
2248 StringTokLocs.push_back(Tok.getLocation());
2249
2250 QualType CharTy = Context.CharTy;
2252 if (Literal.isWide()) {
2253 CharTy = Context.getWideCharType();
2255 } else if (Literal.isUTF8()) {
2256 if (getLangOpts().Char8)
2257 CharTy = Context.Char8Ty;
2258 else if (getLangOpts().C23)
2259 CharTy = Context.UnsignedCharTy;
2261 } else if (Literal.isUTF16()) {
2262 CharTy = Context.Char16Ty;
2264 } else if (Literal.isUTF32()) {
2265 CharTy = Context.Char32Ty;
2267 } else if (Literal.isPascal()) {
2268 CharTy = Context.UnsignedCharTy;
2269 }
2270
2271 // Warn on u8 string literals before C++20 and C23, whose type
2272 // was an array of char before but becomes an array of char8_t.
2273 // In C++20, it cannot be used where a pointer to char is expected.
2274 // In C23, it might have an unexpected value if char was signed.
2275 if (Kind == StringLiteralKind::UTF8 &&
2277 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2278 : !getLangOpts().C23)) {
2279 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2280 ? diag::warn_cxx20_compat_utf8_string
2281 : diag::warn_c23_compat_utf8_string);
2282
2283 // Create removals for all 'u8' prefixes in the string literal(s). This
2284 // ensures C++20/C23 compatibility (but may change the program behavior when
2285 // built by non-Clang compilers for which the execution character set is
2286 // not always UTF-8).
2287 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2288 SourceLocation RemovalDiagLoc;
2289 for (const Token &Tok : StringToks) {
2290 if (Tok.getKind() == tok::utf8_string_literal) {
2291 if (RemovalDiagLoc.isInvalid())
2292 RemovalDiagLoc = Tok.getLocation();
2294 Tok.getLocation(),
2295 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2297 }
2298 }
2299 Diag(RemovalDiagLoc, RemovalDiag);
2300 }
2301
2302 QualType StrTy =
2303 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2304
2305 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2307 Context, Literal.GetString(), Kind, Literal.Pascal, StrTy, StringTokLocs);
2308 if (Literal.getUDSuffix().empty())
2309 return Lit;
2310
2311 // We're building a user-defined literal.
2312 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2313 SourceLocation UDSuffixLoc =
2314 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2315 Literal.getUDSuffixOffset());
2316
2317 // Make sure we're allowed user-defined literals here.
2318 if (!UDLScope)
2319 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2320
2321 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2322 // operator "" X (str, len)
2323 QualType SizeType = Context.getSizeType();
2324
2325 DeclarationName OpName =
2326 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2327 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2328 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2329
2330 QualType ArgTy[] = {
2331 Context.getArrayDecayedType(StrTy), SizeType
2332 };
2333
2334 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2335 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2336 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2337 /*AllowStringTemplatePack*/ true,
2338 /*DiagnoseMissing*/ true, Lit)) {
2339
2340 case LOLR_Cooked: {
2341 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2342 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2343 StringTokLocs[0]);
2344 Expr *Args[] = { Lit, LenArg };
2345
2346 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2347 }
2348
2349 case LOLR_Template: {
2350 TemplateArgumentListInfo ExplicitArgs;
2351 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2352 TemplateArgumentLocInfo ArgInfo(Lit);
2353 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2354 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2355 &ExplicitArgs);
2356 }
2357
2359 TemplateArgumentListInfo ExplicitArgs;
2360
2361 unsigned CharBits = Context.getIntWidth(CharTy);
2362 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2363 llvm::APSInt Value(CharBits, CharIsUnsigned);
2364
2365 TemplateArgument TypeArg(CharTy);
2366 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2367 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2368
2369 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2370 Value = Lit->getCodeUnit(I);
2371 TemplateArgument Arg(Context, Value, CharTy);
2373 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2374 }
2375 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2376 &ExplicitArgs);
2377 }
2378 case LOLR_Raw:
2380 llvm_unreachable("unexpected literal operator lookup result");
2381 case LOLR_Error:
2382 return ExprError();
2383 }
2384 llvm_unreachable("unexpected literal operator lookup result");
2385}
2386
2389 SourceLocation Loc,
2390 const CXXScopeSpec *SS) {
2391 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2392 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2393}
2394
2397 const DeclarationNameInfo &NameInfo,
2398 const CXXScopeSpec *SS, NamedDecl *FoundD,
2399 SourceLocation TemplateKWLoc,
2400 const TemplateArgumentListInfo *TemplateArgs) {
2403 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2404 TemplateArgs);
2405}
2406
2407// CUDA/HIP: Check whether a captured reference variable is referencing a
2408// host variable in a device or host device lambda.
2410 VarDecl *VD) {
2411 if (!S.getLangOpts().CUDA || !VD->hasInit())
2412 return false;
2413 assert(VD->getType()->isReferenceType());
2414
2415 // Check whether the reference variable is referencing a host variable.
2416 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2417 if (!DRE)
2418 return false;
2419 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2420 if (!Referee || !Referee->hasGlobalStorage() ||
2421 Referee->hasAttr<CUDADeviceAttr>())
2422 return false;
2423
2424 // Check whether the current function is a device or host device lambda.
2425 // Check whether the reference variable is a capture by getDeclContext()
2426 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2427 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2428 if (MD && MD->getParent()->isLambda() &&
2429 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2430 VD->getDeclContext() != MD)
2431 return true;
2432
2433 return false;
2434}
2435
2437 // A declaration named in an unevaluated operand never constitutes an odr-use.
2439 return NOUR_Unevaluated;
2440
2441 // C++2a [basic.def.odr]p4:
2442 // A variable x whose name appears as a potentially-evaluated expression e
2443 // is odr-used by e unless [...] x is a reference that is usable in
2444 // constant expressions.
2445 // CUDA/HIP:
2446 // If a reference variable referencing a host variable is captured in a
2447 // device or host device lambda, the value of the referee must be copied
2448 // to the capture and the reference variable must be treated as odr-use
2449 // since the value of the referee is not known at compile time and must
2450 // be loaded from the captured.
2451 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2452 if (VD->getType()->isReferenceType() &&
2453 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2455 VD->isUsableInConstantExpressions(Context))
2456 return NOUR_Constant;
2457 }
2458
2459 // All remaining non-variable cases constitute an odr-use. For variables, we
2460 // need to wait and see how the expression is used.
2461 return NOUR_None;
2462}
2463
2466 const DeclarationNameInfo &NameInfo,
2467 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2468 SourceLocation TemplateKWLoc,
2469 const TemplateArgumentListInfo *TemplateArgs) {
2470 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2471 NeedToCaptureVariable(D, NameInfo.getLoc());
2472
2474 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2475 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2477
2478 // C++ [except.spec]p17:
2479 // An exception-specification is considered to be needed when:
2480 // - in an expression, the function is the unique lookup result or
2481 // the selected member of a set of overloaded functions.
2482 //
2483 // We delay doing this until after we've built the function reference and
2484 // marked it as used so that:
2485 // a) if the function is defaulted, we get errors from defining it before /
2486 // instead of errors from computing its exception specification, and
2487 // b) if the function is a defaulted comparison, we can use the body we
2488 // build when defining it as input to the exception specification
2489 // computation rather than computing a new body.
2490 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2491 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2492 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2493 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2494 }
2495 }
2496
2497 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2499 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2501
2502 const auto *FD = dyn_cast<FieldDecl>(D);
2503 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2504 FD = IFD->getAnonField();
2505 if (FD) {
2506 UnusedPrivateFields.remove(FD);
2507 // Just in case we're building an illegal pointer-to-member.
2508 if (FD->isBitField())
2510 }
2511
2512 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2513 // designates a bit-field.
2514 if (const auto *BD = dyn_cast<BindingDecl>(D))
2515 if (const auto *BE = BD->getBinding())
2516 E->setObjectKind(BE->getObjectKind());
2517
2518 return E;
2519}
2520
2521void
2524 DeclarationNameInfo &NameInfo,
2525 const TemplateArgumentListInfo *&TemplateArgs) {
2527 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2528 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2529
2530 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2531 Id.TemplateId->NumArgs);
2532 translateTemplateArguments(TemplateArgsPtr, Buffer);
2533
2534 TemplateName TName = Id.TemplateId->Template.get();
2536 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2537 TemplateArgs = &Buffer;
2538 } else {
2539 NameInfo = GetNameFromUnqualifiedId(Id);
2540 TemplateArgs = nullptr;
2541 }
2542}
2543
2545 // During a default argument instantiation the CurContext points
2546 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2547 // function parameter list, hence add an explicit check.
2548 bool isDefaultArgument =
2549 !CodeSynthesisContexts.empty() &&
2550 CodeSynthesisContexts.back().Kind ==
2552 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2553 bool isInstance = CurMethod && CurMethod->isInstance() &&
2554 R.getNamingClass() == CurMethod->getParent() &&
2555 !isDefaultArgument;
2556
2557 // There are two ways we can find a class-scope declaration during template
2558 // instantiation that we did not find in the template definition: if it is a
2559 // member of a dependent base class, or if it is declared after the point of
2560 // use in the same class. Distinguish these by comparing the class in which
2561 // the member was found to the naming class of the lookup.
2562 unsigned DiagID = diag::err_found_in_dependent_base;
2563 unsigned NoteID = diag::note_member_declared_at;
2564 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2565 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2566 : diag::err_found_later_in_class;
2567 } else if (getLangOpts().MSVCCompat) {
2568 DiagID = diag::ext_found_in_dependent_base;
2569 NoteID = diag::note_dependent_member_use;
2570 }
2571
2572 if (isInstance) {
2573 // Give a code modification hint to insert 'this->'.
2574 Diag(R.getNameLoc(), DiagID)
2575 << R.getLookupName()
2576 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2577 CheckCXXThisCapture(R.getNameLoc());
2578 } else {
2579 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2580 // they're not shadowed).
2581 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2582 }
2583
2584 for (const NamedDecl *D : R)
2585 Diag(D->getLocation(), NoteID);
2586
2587 // Return true if we are inside a default argument instantiation
2588 // and the found name refers to an instance member function, otherwise
2589 // the caller will try to create an implicit member call and this is wrong
2590 // for default arguments.
2591 //
2592 // FIXME: Is this special case necessary? We could allow the caller to
2593 // diagnose this.
2594 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2595 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2596 return true;
2597 }
2598
2599 // Tell the callee to try to recover.
2600 return false;
2601}
2602
2605 TemplateArgumentListInfo *ExplicitTemplateArgs,
2606 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2607 DeclarationName Name = R.getLookupName();
2608 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2609
2610 unsigned diagnostic = diag::err_undeclared_var_use;
2611 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2615 diagnostic = diag::err_undeclared_use;
2616 diagnostic_suggest = diag::err_undeclared_use_suggest;
2617 }
2618
2619 // If the original lookup was an unqualified lookup, fake an
2620 // unqualified lookup. This is useful when (for example) the
2621 // original lookup would not have found something because it was a
2622 // dependent name.
2623 DeclContext *DC =
2624 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2625 while (DC) {
2626 if (isa<CXXRecordDecl>(DC)) {
2627 if (ExplicitTemplateArgs) {
2629 R, S, SS, Context.getCanonicalTagType(cast<CXXRecordDecl>(DC)),
2630 /*EnteringContext*/ false, TemplateNameIsRequired,
2631 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2632 return true;
2633 } else {
2634 LookupQualifiedName(R, DC);
2635 }
2636
2637 if (!R.empty()) {
2638 // Don't give errors about ambiguities in this lookup.
2639 R.suppressDiagnostics();
2640
2641 // If there's a best viable function among the results, only mention
2642 // that one in the notes.
2643 OverloadCandidateSet Candidates(R.getNameLoc(),
2645 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2647 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2648 OR_Success) {
2649 R.clear();
2650 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2651 R.resolveKind();
2652 }
2653
2655 }
2656
2657 R.clear();
2658 }
2659
2660 DC = DC->getLookupParent();
2661 }
2662
2663 // We didn't find anything, so try to correct for a typo.
2664 TypoCorrection Corrected;
2665 if (S && (Corrected =
2666 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2667 CCC, CorrectTypoKind::ErrorRecovery, LookupCtx))) {
2668 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2669 bool DroppedSpecifier =
2670 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2671 R.setLookupName(Corrected.getCorrection());
2672
2673 bool AcceptableWithRecovery = false;
2674 bool AcceptableWithoutRecovery = false;
2675 NamedDecl *ND = Corrected.getFoundDecl();
2676 if (ND) {
2677 if (Corrected.isOverloaded()) {
2678 OverloadCandidateSet OCS(R.getNameLoc(),
2681 for (NamedDecl *CD : Corrected) {
2682 if (FunctionTemplateDecl *FTD =
2683 dyn_cast<FunctionTemplateDecl>(CD))
2685 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2686 Args, OCS);
2687 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2688 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2690 Args, OCS);
2691 }
2692 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2693 case OR_Success:
2694 ND = Best->FoundDecl;
2695 Corrected.setCorrectionDecl(ND);
2696 break;
2697 default:
2698 // FIXME: Arbitrarily pick the first declaration for the note.
2699 Corrected.setCorrectionDecl(ND);
2700 break;
2701 }
2702 }
2703 R.addDecl(ND);
2704 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2707 if (!Record)
2710 R.setNamingClass(Record);
2711 }
2712
2713 auto *UnderlyingND = ND->getUnderlyingDecl();
2714 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2715 isa<FunctionTemplateDecl>(UnderlyingND);
2716 // FIXME: If we ended up with a typo for a type name or
2717 // Objective-C class name, we're in trouble because the parser
2718 // is in the wrong place to recover. Suggest the typo
2719 // correction, but don't make it a fix-it since we're not going
2720 // to recover well anyway.
2721 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2722 getAsTypeTemplateDecl(UnderlyingND) ||
2723 isa<ObjCInterfaceDecl>(UnderlyingND);
2724 } else {
2725 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2726 // because we aren't able to recover.
2727 AcceptableWithoutRecovery = true;
2728 }
2729
2730 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2731 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2732 ? diag::note_implicit_param_decl
2733 : diag::note_previous_decl;
2734 if (SS.isEmpty())
2735 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name << NameRange,
2736 PDiag(NoteID), AcceptableWithRecovery);
2737 else
2738 diagnoseTypo(Corrected,
2739 PDiag(diag::err_no_member_suggest)
2740 << Name << computeDeclContext(SS, false)
2741 << DroppedSpecifier << NameRange,
2742 PDiag(NoteID), AcceptableWithRecovery);
2743
2744 if (Corrected.WillReplaceSpecifier()) {
2746 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2747 SS.MakeTrivial(Context, NNS,
2748 NNS ? NameRange.getBegin() : SourceRange());
2749 }
2750
2751 // Tell the callee whether to try to recover.
2752 return !AcceptableWithRecovery;
2753 }
2754 }
2755 R.clear();
2756
2757 // Emit a special diagnostic for failed member lookups.
2758 // FIXME: computing the declaration context might fail here (?)
2759 if (!SS.isEmpty()) {
2760 Diag(R.getNameLoc(), diag::err_no_member)
2761 << Name << computeDeclContext(SS, false) << NameRange;
2762 return true;
2763 }
2764
2765 // Give up, we can't recover.
2766 Diag(R.getNameLoc(), diagnostic) << Name << NameRange;
2767 return true;
2768}
2769
2770/// In Microsoft mode, if we are inside a template class whose parent class has
2771/// dependent base classes, and we can't resolve an unqualified identifier, then
2772/// assume the identifier is a member of a dependent base class. We can only
2773/// recover successfully in static methods, instance methods, and other contexts
2774/// where 'this' is available. This doesn't precisely match MSVC's
2775/// instantiation model, but it's close enough.
2776static Expr *
2778 DeclarationNameInfo &NameInfo,
2779 SourceLocation TemplateKWLoc,
2780 const TemplateArgumentListInfo *TemplateArgs) {
2781 // Only try to recover from lookup into dependent bases in static methods or
2782 // contexts where 'this' is available.
2783 QualType ThisType = S.getCurrentThisType();
2784 const CXXRecordDecl *RD = nullptr;
2785 if (!ThisType.isNull())
2786 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2787 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2788 RD = MD->getParent();
2789 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2790 return nullptr;
2791
2792 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2793 // is available, suggest inserting 'this->' as a fixit.
2794 SourceLocation Loc = NameInfo.getLoc();
2795 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2796 DB << NameInfo.getName() << RD;
2797
2798 if (!ThisType.isNull()) {
2799 DB << FixItHint::CreateInsertion(Loc, "this->");
2801 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2802 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2803 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2804 }
2805
2806 // Synthesize a fake NNS that points to the derived class. This will
2807 // perform name lookup during template instantiation.
2808 CXXScopeSpec SS;
2809 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD)->getTypePtr());
2810 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2812 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2813 TemplateArgs);
2814}
2815
2818 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2819 bool HasTrailingLParen, bool IsAddressOfOperand,
2821 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2822 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2823 "cannot be direct & operand and have a trailing lparen");
2824 if (SS.isInvalid())
2825 return ExprError();
2826
2827 TemplateArgumentListInfo TemplateArgsBuffer;
2828
2829 // Decompose the UnqualifiedId into the following data.
2830 DeclarationNameInfo NameInfo;
2831 const TemplateArgumentListInfo *TemplateArgs;
2832 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2833
2834 DeclarationName Name = NameInfo.getName();
2836 SourceLocation NameLoc = NameInfo.getLoc();
2837
2838 if (II && II->isEditorPlaceholder()) {
2839 // FIXME: When typed placeholders are supported we can create a typed
2840 // placeholder expression node.
2841 return ExprError();
2842 }
2843
2844 // This specially handles arguments of attributes appertains to a type of C
2845 // struct field such that the name lookup within a struct finds the member
2846 // name, which is not the case for other contexts in C.
2847 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2848 // See if this is reference to a field of struct.
2849 LookupResult R(*this, NameInfo, LookupMemberName);
2850 // LookupName handles a name lookup from within anonymous struct.
2851 if (LookupName(R, S)) {
2852 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2853 QualType type = VD->getType().getNonReferenceType();
2854 // This will eventually be translated into MemberExpr upon
2855 // the use of instantiated struct fields.
2856 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2857 }
2858 }
2859 }
2860
2861 // Perform the required lookup.
2862 LookupResult R(*this, NameInfo,
2866 if (TemplateKWLoc.isValid() || TemplateArgs) {
2867 // Lookup the template name again to correctly establish the context in
2868 // which it was found. This is really unfortunate as we already did the
2869 // lookup to determine that it was a template name in the first place. If
2870 // this becomes a performance hit, we can work harder to preserve those
2871 // results until we get here but it's likely not worth it.
2872 AssumedTemplateKind AssumedTemplate;
2873 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2874 /*EnteringContext=*/false, TemplateKWLoc,
2875 &AssumedTemplate))
2876 return ExprError();
2877
2878 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2879 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2880 IsAddressOfOperand, TemplateArgs);
2881 } else {
2882 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2883 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2884 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2885
2886 // If the result might be in a dependent base class, this is a dependent
2887 // id-expression.
2888 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2889 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2890 IsAddressOfOperand, TemplateArgs);
2891
2892 // If this reference is in an Objective-C method, then we need to do
2893 // some special Objective-C lookup, too.
2894 if (IvarLookupFollowUp) {
2895 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2896 if (E.isInvalid())
2897 return ExprError();
2898
2899 if (Expr *Ex = E.getAs<Expr>())
2900 return Ex;
2901 }
2902 }
2903
2904 if (R.isAmbiguous())
2905 return ExprError();
2906
2907 // This could be an implicitly declared function reference if the language
2908 // mode allows it as a feature.
2909 if (R.empty() && HasTrailingLParen && II &&
2910 getLangOpts().implicitFunctionsAllowed()) {
2911 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2912 if (D) R.addDecl(D);
2913 }
2914
2915 // Determine whether this name might be a candidate for
2916 // argument-dependent lookup.
2917 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2918
2919 if (R.empty() && !ADL) {
2920 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2921 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2922 TemplateKWLoc, TemplateArgs))
2923 return E;
2924 }
2925
2926 // Don't diagnose an empty lookup for inline assembly.
2927 if (IsInlineAsmIdentifier)
2928 return ExprError();
2929
2930 // If this name wasn't predeclared and if this is not a function
2931 // call, diagnose the problem.
2932 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2933 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2934 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2935 "Typo correction callback misconfigured");
2936 if (CCC) {
2937 // Make sure the callback knows what the typo being diagnosed is.
2938 CCC->setTypoName(II);
2939 if (SS.isValid())
2940 CCC->setTypoNNS(SS.getScopeRep());
2941 }
2942 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2943 // a template name, but we happen to have always already looked up the name
2944 // before we get here if it must be a template name.
2945 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2946 {}, nullptr))
2947 return ExprError();
2948
2949 assert(!R.empty() &&
2950 "DiagnoseEmptyLookup returned false but added no results");
2951
2952 // If we found an Objective-C instance variable, let
2953 // LookupInObjCMethod build the appropriate expression to
2954 // reference the ivar.
2955 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2956 R.clear();
2957 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2958 // In a hopelessly buggy code, Objective-C instance variable
2959 // lookup fails and no expression will be built to reference it.
2960 if (!E.isInvalid() && !E.get())
2961 return ExprError();
2962 return E;
2963 }
2964 }
2965
2966 // This is guaranteed from this point on.
2967 assert(!R.empty() || ADL);
2968
2969 // Check whether this might be a C++ implicit instance member access.
2970 // C++ [class.mfct.non-static]p3:
2971 // When an id-expression that is not part of a class member access
2972 // syntax and not used to form a pointer to member is used in the
2973 // body of a non-static member function of class X, if name lookup
2974 // resolves the name in the id-expression to a non-static non-type
2975 // member of some class C, the id-expression is transformed into a
2976 // class member access expression using (*this) as the
2977 // postfix-expression to the left of the . operator.
2978 //
2979 // But we don't actually need to do this for '&' operands if R
2980 // resolved to a function or overloaded function set, because the
2981 // expression is ill-formed if it actually works out to be a
2982 // non-static member function:
2983 //
2984 // C++ [expr.ref]p4:
2985 // Otherwise, if E1.E2 refers to a non-static member function. . .
2986 // [t]he expression can be used only as the left-hand operand of a
2987 // member function call.
2988 //
2989 // There are other safeguards against such uses, but it's important
2990 // to get this right here so that we don't end up making a
2991 // spuriously dependent expression if we're inside a dependent
2992 // instance method.
2993 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2994 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2995 S);
2996
2997 if (TemplateArgs || TemplateKWLoc.isValid()) {
2998
2999 // In C++1y, if this is a variable template id, then check it
3000 // in BuildTemplateIdExpr().
3001 // The single lookup result must be a variable template declaration.
3005 assert(R.getAsSingle<TemplateDecl>() &&
3006 "There should only be one declaration found.");
3007 }
3008
3009 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
3010 }
3011
3012 return BuildDeclarationNameExpr(SS, R, ADL);
3013}
3014
3016 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3017 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3018 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3019 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
3020
3021 if (R.isAmbiguous())
3022 return ExprError();
3023
3024 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3025 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3026 NameInfo, /*TemplateArgs=*/nullptr);
3027
3028 if (R.empty()) {
3029 // Don't diagnose problems with invalid record decl, the secondary no_member
3030 // diagnostic during template instantiation is likely bogus, e.g. if a class
3031 // is invalid because it's derived from an invalid base class, then missing
3032 // members were likely supposed to be inherited.
3034 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
3035 if (CD->isInvalidDecl() || CD->isBeingDefined())
3036 return ExprError();
3037 Diag(NameInfo.getLoc(), diag::err_no_member)
3038 << NameInfo.getName() << DC << SS.getRange();
3039 return ExprError();
3040 }
3041
3042 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3043 QualType ET;
3044 TypeLocBuilder TLB;
3045 if (auto *TagD = dyn_cast<TagDecl>(TD)) {
3046 ET = SemaRef.Context.getTagType(ElaboratedTypeKeyword::None,
3047 SS.getScopeRep(), TagD,
3048 /*OwnsTag=*/false);
3049 auto TL = TLB.push<TagTypeLoc>(ET);
3051 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3052 TL.setNameLoc(NameInfo.getLoc());
3053 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(TD)) {
3054 ET = SemaRef.Context.getTypedefType(ElaboratedTypeKeyword::None,
3055 SS.getScopeRep(), TypedefD);
3056 TLB.push<TypedefTypeLoc>(ET).set(
3057 /*ElaboratedKeywordLoc=*/SourceLocation(),
3058 SS.getWithLocInContext(Context), NameInfo.getLoc());
3059 } else {
3060 // FIXME: What else can appear here?
3061 ET = SemaRef.Context.getTypeDeclType(TD);
3062 TLB.pushTypeSpec(ET).setNameLoc(NameInfo.getLoc());
3063 assert(SS.isEmpty());
3064 }
3065
3066 // Diagnose a missing typename if this resolved unambiguously to a type in
3067 // a dependent context. If we can recover with a type, downgrade this to
3068 // a warning in Microsoft compatibility mode.
3069 unsigned DiagID = diag::err_typename_missing;
3070 if (RecoveryTSI && getLangOpts().MSVCCompat)
3071 DiagID = diag::ext_typename_missing;
3072 SourceLocation Loc = SS.getBeginLoc();
3073 auto D = Diag(Loc, DiagID);
3074 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3075
3076 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3077 // context.
3078 if (!RecoveryTSI)
3079 return ExprError();
3080
3081 // Only issue the fixit if we're prepared to recover.
3082 D << FixItHint::CreateInsertion(Loc, "typename ");
3083
3084 // Recover by pretending this was an elaborated type.
3085 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3086
3087 return ExprEmpty();
3088 }
3089
3090 // If necessary, build an implicit class member access.
3091 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3093 /*TemplateKWLoc=*/SourceLocation(),
3094 R, /*TemplateArgs=*/nullptr,
3095 /*S=*/nullptr);
3096
3097 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
3098}
3099
3101 NestedNameSpecifier Qualifier,
3102 NamedDecl *FoundDecl,
3103 NamedDecl *Member) {
3104 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3105 if (!RD)
3106 return From;
3107
3108 QualType DestRecordType;
3109 QualType DestType;
3110 QualType FromRecordType;
3111 QualType FromType = From->getType();
3112 bool PointerConversions = false;
3113 if (isa<FieldDecl>(Member)) {
3114 DestRecordType = Context.getCanonicalTagType(RD);
3115 auto FromPtrType = FromType->getAs<PointerType>();
3116 DestRecordType = Context.getAddrSpaceQualType(
3117 DestRecordType, FromPtrType
3118 ? FromType->getPointeeType().getAddressSpace()
3119 : FromType.getAddressSpace());
3120
3121 if (FromPtrType) {
3122 DestType = Context.getPointerType(DestRecordType);
3123 FromRecordType = FromPtrType->getPointeeType();
3124 PointerConversions = true;
3125 } else {
3126 DestType = DestRecordType;
3127 FromRecordType = FromType;
3128 }
3129 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3130 if (!Method->isImplicitObjectMemberFunction())
3131 return From;
3132
3133 DestType = Method->getThisType().getNonReferenceType();
3134 DestRecordType = Method->getFunctionObjectParameterType();
3135
3136 if (FromType->getAs<PointerType>()) {
3137 FromRecordType = FromType->getPointeeType();
3138 PointerConversions = true;
3139 } else {
3140 FromRecordType = FromType;
3141 DestType = DestRecordType;
3142 }
3143
3144 LangAS FromAS = FromRecordType.getAddressSpace();
3145 LangAS DestAS = DestRecordType.getAddressSpace();
3146 if (FromAS != DestAS) {
3147 QualType FromRecordTypeWithoutAS =
3148 Context.removeAddrSpaceQualType(FromRecordType);
3149 QualType FromTypeWithDestAS =
3150 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3151 if (PointerConversions)
3152 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3153 From = ImpCastExprToType(From, FromTypeWithDestAS,
3154 CK_AddressSpaceConversion, From->getValueKind())
3155 .get();
3156 }
3157 } else {
3158 // No conversion necessary.
3159 return From;
3160 }
3161
3162 if (DestType->isDependentType() || FromType->isDependentType())
3163 return From;
3164
3165 // If the unqualified types are the same, no conversion is necessary.
3166 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3167 return From;
3168
3169 SourceRange FromRange = From->getSourceRange();
3170 SourceLocation FromLoc = FromRange.getBegin();
3171
3172 ExprValueKind VK = From->getValueKind();
3173
3174 // C++ [class.member.lookup]p8:
3175 // [...] Ambiguities can often be resolved by qualifying a name with its
3176 // class name.
3177 //
3178 // If the member was a qualified name and the qualified referred to a
3179 // specific base subobject type, we'll cast to that intermediate type
3180 // first and then to the object in which the member is declared. That allows
3181 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3182 //
3183 // class Base { public: int x; };
3184 // class Derived1 : public Base { };
3185 // class Derived2 : public Base { };
3186 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3187 //
3188 // void VeryDerived::f() {
3189 // x = 17; // error: ambiguous base subobjects
3190 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3191 // }
3192 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3193 QualType QType = QualType(Qualifier.getAsType(), 0);
3194 assert(QType->isRecordType() && "lookup done with non-record type");
3195
3196 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3197
3198 // In C++98, the qualifier type doesn't actually have to be a base
3199 // type of the object type, in which case we just ignore it.
3200 // Otherwise build the appropriate casts.
3201 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3202 CXXCastPath BasePath;
3203 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3204 FromLoc, FromRange, &BasePath))
3205 return ExprError();
3206
3207 if (PointerConversions)
3208 QType = Context.getPointerType(QType);
3209 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3210 VK, &BasePath).get();
3211
3212 FromType = QType;
3213 FromRecordType = QRecordType;
3214
3215 // If the qualifier type was the same as the destination type,
3216 // we're done.
3217 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3218 return From;
3219 }
3220 }
3221
3222 CXXCastPath BasePath;
3223 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3224 FromLoc, FromRange, &BasePath,
3225 /*IgnoreAccess=*/true))
3226 return ExprError();
3227
3228 // Propagate qualifiers to base subobjects as per:
3229 // C++ [basic.type.qualifier]p1.2:
3230 // A volatile object is [...] a subobject of a volatile object.
3231 Qualifiers FromTypeQuals = FromType.getQualifiers();
3232 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3233 DestType = Context.getQualifiedType(DestType, FromTypeQuals);
3234
3235 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, VK,
3236 &BasePath);
3237}
3238
3240 const LookupResult &R,
3241 bool HasTrailingLParen) {
3242 // Only when used directly as the postfix-expression of a call.
3243 if (!HasTrailingLParen)
3244 return false;
3245
3246 // Never if a scope specifier was provided.
3247 if (SS.isNotEmpty())
3248 return false;
3249
3250 // Only in C++ or ObjC++.
3251 if (!getLangOpts().CPlusPlus)
3252 return false;
3253
3254 // Turn off ADL when we find certain kinds of declarations during
3255 // normal lookup:
3256 for (const NamedDecl *D : R) {
3257 // C++0x [basic.lookup.argdep]p3:
3258 // -- a declaration of a class member
3259 // Since using decls preserve this property, we check this on the
3260 // original decl.
3261 if (D->isCXXClassMember())
3262 return false;
3263
3264 // C++0x [basic.lookup.argdep]p3:
3265 // -- a block-scope function declaration that is not a
3266 // using-declaration
3267 // NOTE: we also trigger this for function templates (in fact, we
3268 // don't check the decl type at all, since all other decl types
3269 // turn off ADL anyway).
3270 if (isa<UsingShadowDecl>(D))
3271 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3272 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3273 return false;
3274
3275 // C++0x [basic.lookup.argdep]p3:
3276 // -- a declaration that is neither a function or a function
3277 // template
3278 // And also for builtin functions.
3279 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3280 // But also builtin functions.
3281 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3282 return false;
3283 } else if (!isa<FunctionTemplateDecl>(D))
3284 return false;
3285 }
3286
3287 return true;
3288}
3289
3290
3291/// Diagnoses obvious problems with the use of the given declaration
3292/// as an expression. This is only actually called for lookups that
3293/// were not overloaded, and it doesn't promise that the declaration
3294/// will in fact be used.
3296 bool AcceptInvalid) {
3297 if (D->isInvalidDecl() && !AcceptInvalid)
3298 return true;
3299
3300 if (isa<TypedefNameDecl>(D)) {
3301 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3302 return true;
3303 }
3304
3305 if (isa<ObjCInterfaceDecl>(D)) {
3306 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3307 return true;
3308 }
3309
3310 if (isa<NamespaceDecl>(D)) {
3311 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3312 return true;
3313 }
3314
3315 return false;
3316}
3317
3318// Certain multiversion types should be treated as overloaded even when there is
3319// only one result.
3321 assert(R.isSingleResult() && "Expected only a single result");
3322 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3323 return FD &&
3324 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3325}
3326
3328 LookupResult &R, bool NeedsADL,
3329 bool AcceptInvalidDecl) {
3330 // If this is a single, fully-resolved result and we don't need ADL,
3331 // just build an ordinary singleton decl ref.
3332 if (!NeedsADL && R.isSingleResult() &&
3333 !R.getAsSingle<FunctionTemplateDecl>() &&
3335 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3336 R.getRepresentativeDecl(), nullptr,
3337 AcceptInvalidDecl);
3338
3339 // We only need to check the declaration if there's exactly one
3340 // result, because in the overloaded case the results can only be
3341 // functions and function templates.
3342 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3343 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3344 AcceptInvalidDecl))
3345 return ExprError();
3346
3347 // Otherwise, just build an unresolved lookup expression. Suppress
3348 // any lookup-related diagnostics; we'll hash these out later, when
3349 // we've picked a target.
3350 R.suppressDiagnostics();
3351
3353 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
3354 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3355 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3356
3357 return ULE;
3358}
3359
3361 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3362 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3363 bool AcceptInvalidDecl) {
3364 assert(D && "Cannot refer to a NULL declaration");
3365 assert(!isa<FunctionTemplateDecl>(D) &&
3366 "Cannot refer unambiguously to a function template");
3367
3368 SourceLocation Loc = NameInfo.getLoc();
3369 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3370 // Recovery from invalid cases (e.g. D is an invalid Decl).
3371 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3372 // diagnostics, as invalid decls use int as a fallback type.
3373 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3374 }
3375
3376 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3377 // Specifically diagnose references to class templates that are missing
3378 // a template argument list.
3379 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3380 return ExprError();
3381 }
3382
3383 // Make sure that we're referring to a value.
3385 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3386 Diag(D->getLocation(), diag::note_declared_at);
3387 return ExprError();
3388 }
3389
3390 // Check whether this declaration can be used. Note that we suppress
3391 // this check when we're going to perform argument-dependent lookup
3392 // on this function name, because this might not be the function
3393 // that overload resolution actually selects.
3394 if (DiagnoseUseOfDecl(D, Loc))
3395 return ExprError();
3396
3397 auto *VD = cast<ValueDecl>(D);
3398
3399 // Only create DeclRefExpr's for valid Decl's.
3400 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3401 return ExprError();
3402
3403 // Handle members of anonymous structs and unions. If we got here,
3404 // and the reference is to a class member indirect field, then this
3405 // must be the subject of a pointer-to-member expression.
3406 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3407 IndirectField && !IndirectField->isCXXClassMember())
3409 IndirectField);
3410
3411 QualType type = VD->getType();
3412 if (type.isNull())
3413 return ExprError();
3414 ExprValueKind valueKind = VK_PRValue;
3415
3416 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3417 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3418 // is expanded by some outer '...' in the context of the use.
3419 type = type.getNonPackExpansionType();
3420
3421 switch (D->getKind()) {
3422 // Ignore all the non-ValueDecl kinds.
3423#define ABSTRACT_DECL(kind)
3424#define VALUE(type, base)
3425#define DECL(type, base) case Decl::type:
3426#include "clang/AST/DeclNodes.inc"
3427 llvm_unreachable("invalid value decl kind");
3428
3429 // These shouldn't make it here.
3430 case Decl::ObjCAtDefsField:
3431 llvm_unreachable("forming non-member reference to ivar?");
3432
3433 // Enum constants are always r-values and never references.
3434 // Unresolved using declarations are dependent.
3435 case Decl::EnumConstant:
3436 case Decl::UnresolvedUsingValue:
3437 case Decl::OMPDeclareReduction:
3438 case Decl::OMPDeclareMapper:
3439 valueKind = VK_PRValue;
3440 break;
3441
3442 // Fields and indirect fields that got here must be for
3443 // pointer-to-member expressions; we just call them l-values for
3444 // internal consistency, because this subexpression doesn't really
3445 // exist in the high-level semantics.
3446 case Decl::Field:
3447 case Decl::IndirectField:
3448 case Decl::ObjCIvar:
3449 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3450 "building reference to field in C?");
3451
3452 // These can't have reference type in well-formed programs, but
3453 // for internal consistency we do this anyway.
3454 type = type.getNonReferenceType();
3455 valueKind = VK_LValue;
3456 break;
3457
3458 // Non-type template parameters are either l-values or r-values
3459 // depending on the type.
3460 case Decl::NonTypeTemplateParm: {
3461 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3462 type = reftype->getPointeeType();
3463 valueKind = VK_LValue; // even if the parameter is an r-value reference
3464 break;
3465 }
3466
3467 // [expr.prim.id.unqual]p2:
3468 // If the entity is a template parameter object for a template
3469 // parameter of type T, the type of the expression is const T.
3470 // [...] The expression is an lvalue if the entity is a [...] template
3471 // parameter object.
3472 if (type->isRecordType()) {
3473 type = type.getUnqualifiedType().withConst();
3474 valueKind = VK_LValue;
3475 break;
3476 }
3477
3478 // For non-references, we need to strip qualifiers just in case
3479 // the template parameter was declared as 'const int' or whatever.
3480 valueKind = VK_PRValue;
3481 type = type.getUnqualifiedType();
3482 break;
3483 }
3484
3485 case Decl::Var:
3486 case Decl::VarTemplateSpecialization:
3487 case Decl::VarTemplatePartialSpecialization:
3488 case Decl::Decomposition:
3489 case Decl::Binding:
3490 case Decl::OMPCapturedExpr:
3491 // In C, "extern void blah;" is valid and is an r-value.
3492 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3493 type->isVoidType()) {
3494 valueKind = VK_PRValue;
3495 break;
3496 }
3497 [[fallthrough]];
3498
3499 case Decl::ImplicitParam:
3500 case Decl::ParmVar: {
3501 // These are always l-values.
3502 valueKind = VK_LValue;
3503 type = type.getNonReferenceType();
3504
3505 // FIXME: Does the addition of const really only apply in
3506 // potentially-evaluated contexts? Since the variable isn't actually
3507 // captured in an unevaluated context, it seems that the answer is no.
3508 if (!isUnevaluatedContext()) {
3509 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3510 if (!CapturedType.isNull())
3511 type = CapturedType;
3512 }
3513 break;
3514 }
3515
3516 case Decl::Function: {
3517 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3518 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3519 type = Context.BuiltinFnTy;
3520 valueKind = VK_PRValue;
3521 break;
3522 }
3523 }
3524
3525 const FunctionType *fty = type->castAs<FunctionType>();
3526
3527 // If we're referring to a function with an __unknown_anytype
3528 // result type, make the entire expression __unknown_anytype.
3529 if (fty->getReturnType() == Context.UnknownAnyTy) {
3530 type = Context.UnknownAnyTy;
3531 valueKind = VK_PRValue;
3532 break;
3533 }
3534
3535 // Functions are l-values in C++.
3536 if (getLangOpts().CPlusPlus) {
3537 valueKind = VK_LValue;
3538 break;
3539 }
3540
3541 // C99 DR 316 says that, if a function type comes from a
3542 // function definition (without a prototype), that type is only
3543 // used for checking compatibility. Therefore, when referencing
3544 // the function, we pretend that we don't have the full function
3545 // type.
3546 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3547 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3548 fty->getExtInfo());
3549
3550 // Functions are r-values in C.
3551 valueKind = VK_PRValue;
3552 break;
3553 }
3554
3555 case Decl::CXXDeductionGuide:
3556 llvm_unreachable("building reference to deduction guide");
3557
3558 case Decl::MSProperty:
3559 case Decl::MSGuid:
3560 case Decl::TemplateParamObject:
3561 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3562 // capture in OpenMP, or duplicated between host and device?
3563 valueKind = VK_LValue;
3564 break;
3565
3566 case Decl::UnnamedGlobalConstant:
3567 valueKind = VK_LValue;
3568 break;
3569
3570 case Decl::CXXMethod:
3571 // If we're referring to a method with an __unknown_anytype
3572 // result type, make the entire expression __unknown_anytype.
3573 // This should only be possible with a type written directly.
3574 if (const FunctionProtoType *proto =
3575 dyn_cast<FunctionProtoType>(VD->getType()))
3576 if (proto->getReturnType() == Context.UnknownAnyTy) {
3577 type = Context.UnknownAnyTy;
3578 valueKind = VK_PRValue;
3579 break;
3580 }
3581
3582 // C++ methods are l-values if static, r-values if non-static.
3583 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3584 valueKind = VK_LValue;
3585 break;
3586 }
3587 [[fallthrough]];
3588
3589 case Decl::CXXConversion:
3590 case Decl::CXXDestructor:
3591 case Decl::CXXConstructor:
3592 valueKind = VK_PRValue;
3593 break;
3594 }
3595
3596 auto *E =
3597 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3598 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3599 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3600 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3601 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3602 // diagnostics).
3603 if (VD->isInvalidDecl() && E)
3604 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3605 return E;
3606}
3607
3608static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3610 Target.resize(CharByteWidth * (Source.size() + 1));
3611 char *ResultPtr = &Target[0];
3612 const llvm::UTF8 *ErrorPtr;
3613 bool success =
3614 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3615 (void)success;
3616 assert(success);
3617 Target.resize(ResultPtr - &Target[0]);
3618}
3619
3622 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3623 if (!currentDecl) {
3624 Diag(Loc, diag::ext_predef_outside_function);
3625 currentDecl = Context.getTranslationUnitDecl();
3626 }
3627
3628 QualType ResTy;
3629 StringLiteral *SL = nullptr;
3630 if (cast<DeclContext>(currentDecl)->isDependentContext())
3631 ResTy = Context.DependentTy;
3632 else {
3633 // Pre-defined identifiers are of type char[x], where x is the length of
3634 // the string.
3635 bool ForceElaboratedPrinting =
3636 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3637 auto Str =
3638 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3639 unsigned Length = Str.length();
3640
3641 llvm::APInt LengthI(32, Length + 1);
3644 ResTy =
3645 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3646 SmallString<32> RawChars;
3647 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3648 Str, RawChars);
3649 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3651 /*IndexTypeQuals*/ 0);
3653 /*Pascal*/ false, ResTy, Loc);
3654 } else {
3655 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3656 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3658 /*IndexTypeQuals*/ 0);
3660 /*Pascal*/ false, ResTy, Loc);
3661 }
3662 }
3663
3664 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3665 SL);
3666}
3667
3671
3673 SmallString<16> CharBuffer;
3674 bool Invalid = false;
3675 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3676 if (Invalid)
3677 return ExprError();
3678
3679 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3680 PP, Tok.getKind());
3681 if (Literal.hadError())
3682 return ExprError();
3683
3684 QualType Ty;
3685 if (Literal.isWide())
3686 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3687 else if (Literal.isUTF8() && getLangOpts().C23)
3688 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3689 else if (Literal.isUTF8() && getLangOpts().Char8)
3690 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3691 else if (Literal.isUTF16())
3692 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3693 else if (Literal.isUTF32())
3694 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3695 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3696 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3697 else
3698 Ty = Context.CharTy; // 'x' -> char in C++;
3699 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3700
3702 if (Literal.isWide())
3704 else if (Literal.isUTF16())
3706 else if (Literal.isUTF32())
3708 else if (Literal.isUTF8())
3710
3711 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3712 Tok.getLocation());
3713
3714 if (Literal.getUDSuffix().empty())
3715 return Lit;
3716
3717 // We're building a user-defined literal.
3718 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3719 SourceLocation UDSuffixLoc =
3720 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3721
3722 // Make sure we're allowed user-defined literals here.
3723 if (!UDLScope)
3724 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3725
3726 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3727 // operator "" X (ch)
3728 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3729 Lit, Tok.getLocation());
3730}
3731
3733 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3735 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3736 Context.IntTy, Loc);
3737}
3738
3740 QualType Ty, SourceLocation Loc) {
3741 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3742
3743 using llvm::APFloat;
3744 APFloat Val(Format);
3745
3746 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3747 if (RM == llvm::RoundingMode::Dynamic)
3748 RM = llvm::RoundingMode::NearestTiesToEven;
3749 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3750
3751 // Overflow is always an error, but underflow is only an error if
3752 // we underflowed to zero (APFloat reports denormals as underflow).
3753 if ((result & APFloat::opOverflow) ||
3754 ((result & APFloat::opUnderflow) && Val.isZero())) {
3755 unsigned diagnostic;
3756 SmallString<20> buffer;
3757 if (result & APFloat::opOverflow) {
3758 diagnostic = diag::warn_float_overflow;
3759 APFloat::getLargest(Format).toString(buffer);
3760 } else {
3761 diagnostic = diag::warn_float_underflow;
3762 APFloat::getSmallest(Format).toString(buffer);
3763 }
3764
3765 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3766 }
3767
3768 bool isExact = (result == APFloat::opOK);
3769 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3770}
3771
3772bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3773 assert(E && "Invalid expression");
3774
3775 if (E->isValueDependent())
3776 return false;
3777
3778 QualType QT = E->getType();
3779 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3780 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3781 return true;
3782 }
3783
3784 llvm::APSInt ValueAPS;
3786
3787 if (R.isInvalid())
3788 return true;
3789
3790 // GCC allows the value of unroll count to be 0.
3791 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3792 // "The values of 0 and 1 block any unrolling of the loop."
3793 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3794 // '#pragma unroll' cases.
3795 bool ValueIsPositive =
3796 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3797 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3798 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3799 << toString(ValueAPS, 10) << ValueIsPositive;
3800 return true;
3801 }
3802
3803 return false;
3804}
3805
3807 // Fast path for a single digit (which is quite common). A single digit
3808 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3809 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3810 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3811 return ActOnIntegerConstant(Tok.getLocation(), Val);
3812 }
3813
3814 SmallString<128> SpellingBuffer;
3815 // NumericLiteralParser wants to overread by one character. Add padding to
3816 // the buffer in case the token is copied to the buffer. If getSpelling()
3817 // returns a StringRef to the memory buffer, it should have a null char at
3818 // the EOF, so it is also safe.
3819 SpellingBuffer.resize(Tok.getLength() + 1);
3820
3821 // Get the spelling of the token, which eliminates trigraphs, etc.
3822 bool Invalid = false;
3823 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3824 if (Invalid)
3825 return ExprError();
3826
3827 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3828 PP.getSourceManager(), PP.getLangOpts(),
3829 PP.getTargetInfo(), PP.getDiagnostics());
3830 if (Literal.hadError)
3831 return ExprError();
3832
3833 if (Literal.hasUDSuffix()) {
3834 // We're building a user-defined literal.
3835 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3836 SourceLocation UDSuffixLoc =
3837 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3838
3839 // Make sure we're allowed user-defined literals here.
3840 if (!UDLScope)
3841 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3842
3843 QualType CookedTy;
3844 if (Literal.isFloatingLiteral()) {
3845 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3846 // long double, the literal is treated as a call of the form
3847 // operator "" X (f L)
3848 CookedTy = Context.LongDoubleTy;
3849 } else {
3850 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3851 // unsigned long long, the literal is treated as a call of the form
3852 // operator "" X (n ULL)
3853 CookedTy = Context.UnsignedLongLongTy;
3854 }
3855
3856 DeclarationName OpName =
3857 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3858 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3859 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3860
3861 SourceLocation TokLoc = Tok.getLocation();
3862
3863 // Perform literal operator lookup to determine if we're building a raw
3864 // literal or a cooked one.
3865 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3866 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3867 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3868 /*AllowStringTemplatePack*/ false,
3869 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3871 // Lookup failure for imaginary constants isn't fatal, there's still the
3872 // GNU extension producing _Complex types.
3873 break;
3874 case LOLR_Error:
3875 return ExprError();
3876 case LOLR_Cooked: {
3877 Expr *Lit;
3878 if (Literal.isFloatingLiteral()) {
3879 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3880 } else {
3881 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3882 if (Literal.GetIntegerValue(ResultVal))
3883 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3884 << /* Unsigned */ 1;
3885 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3886 Tok.getLocation());
3887 }
3888 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3889 }
3890
3891 case LOLR_Raw: {
3892 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3893 // literal is treated as a call of the form
3894 // operator "" X ("n")
3895 unsigned Length = Literal.getUDSuffixOffset();
3896 QualType StrTy = Context.getConstantArrayType(
3897 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3898 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3899 Expr *Lit =
3900 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3902 /*Pascal*/ false, StrTy, TokLoc);
3903 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3904 }
3905
3906 case LOLR_Template: {
3907 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3908 // template), L is treated as a call fo the form
3909 // operator "" X <'c1', 'c2', ... 'ck'>()
3910 // where n is the source character sequence c1 c2 ... ck.
3911 TemplateArgumentListInfo ExplicitArgs;
3912 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3913 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3914 llvm::APSInt Value(CharBits, CharIsUnsigned);
3915 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3916 Value = TokSpelling[I];
3917 TemplateArgument Arg(Context, Value, Context.CharTy);
3919 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3920 }
3921 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
3922 }
3924 llvm_unreachable("unexpected literal operator lookup result");
3925 }
3926 }
3927
3928 Expr *Res;
3929
3930 if (Literal.isFixedPointLiteral()) {
3931 QualType Ty;
3932
3933 if (Literal.isAccum) {
3934 if (Literal.isHalf) {
3935 Ty = Context.ShortAccumTy;
3936 } else if (Literal.isLong) {
3937 Ty = Context.LongAccumTy;
3938 } else {
3939 Ty = Context.AccumTy;
3940 }
3941 } else if (Literal.isFract) {
3942 if (Literal.isHalf) {
3943 Ty = Context.ShortFractTy;
3944 } else if (Literal.isLong) {
3945 Ty = Context.LongFractTy;
3946 } else {
3947 Ty = Context.FractTy;
3948 }
3949 }
3950
3951 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3952
3953 bool isSigned = !Literal.isUnsigned;
3954 unsigned scale = Context.getFixedPointScale(Ty);
3955 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3956
3957 llvm::APInt Val(bit_width, 0, isSigned);
3958 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3959 bool ValIsZero = Val.isZero() && !Overflowed;
3960
3961 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3962 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3963 // Clause 6.4.4 - The value of a constant shall be in the range of
3964 // representable values for its type, with exception for constants of a
3965 // fract type with a value of exactly 1; such a constant shall denote
3966 // the maximal value for the type.
3967 --Val;
3968 else if (Val.ugt(MaxVal) || Overflowed)
3969 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3970
3972 Tok.getLocation(), scale);
3973 } else if (Literal.isFloatingLiteral()) {
3974 QualType Ty;
3975 if (Literal.isHalf){
3976 if (getLangOpts().HLSL ||
3977 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3978 Ty = Context.HalfTy;
3979 else {
3980 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3981 return ExprError();
3982 }
3983 } else if (Literal.isFloat)
3984 Ty = Context.FloatTy;
3985 else if (Literal.isLong)
3986 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
3987 else if (Literal.isFloat16)
3988 Ty = Context.Float16Ty;
3989 else if (Literal.isFloat128)
3990 Ty = Context.Float128Ty;
3991 else if (getLangOpts().HLSL)
3992 Ty = Context.FloatTy;
3993 else
3994 Ty = Context.DoubleTy;
3995
3996 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3997
3998 if (Ty == Context.DoubleTy) {
3999 if (getLangOpts().SinglePrecisionConstants) {
4000 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4001 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4002 }
4003 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4004 "cl_khr_fp64", getLangOpts())) {
4005 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4006 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4008 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4009 }
4010 }
4011 } else if (!Literal.isIntegerLiteral()) {
4012 return ExprError();
4013 } else {
4014 QualType Ty;
4015
4016 // 'z/uz' literals are a C++23 feature.
4017 if (Literal.isSizeT)
4018 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
4020 ? diag::warn_cxx20_compat_size_t_suffix
4021 : diag::ext_cxx23_size_t_suffix
4022 : diag::err_cxx23_size_t_suffix);
4023
4024 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4025 // but we do not currently support the suffix in C++ mode because it's not
4026 // entirely clear whether WG21 will prefer this suffix to return a library
4027 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4028 // literals are a C++ extension.
4029 if (Literal.isBitInt)
4030 PP.Diag(Tok.getLocation(),
4031 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4032 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4033 : diag::ext_c23_bitint_suffix);
4034
4035 // Get the value in the widest-possible width. What is "widest" depends on
4036 // whether the literal is a bit-precise integer or not. For a bit-precise
4037 // integer type, try to scan the source to determine how many bits are
4038 // needed to represent the value. This may seem a bit expensive, but trying
4039 // to get the integer value from an overly-wide APInt is *extremely*
4040 // expensive, so the naive approach of assuming
4041 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4042 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4043 if (Literal.isBitInt)
4044 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4045 Literal.getLiteralDigits(), Literal.getRadix());
4046 if (Literal.MicrosoftInteger) {
4047 if (Literal.MicrosoftInteger == 128 &&
4048 !Context.getTargetInfo().hasInt128Type())
4049 PP.Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4050 << Literal.isUnsigned;
4051 BitsNeeded = Literal.MicrosoftInteger;
4052 }
4053
4054 llvm::APInt ResultVal(BitsNeeded, 0);
4055
4056 if (Literal.GetIntegerValue(ResultVal)) {
4057 // If this value didn't fit into uintmax_t, error and force to ull.
4058 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4059 << /* Unsigned */ 1;
4060 Ty = Context.UnsignedLongLongTy;
4061 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4062 "long long is not intmax_t?");
4063 } else {
4064 // If this value fits into a ULL, try to figure out what else it fits into
4065 // according to the rules of C99 6.4.4.1p5.
4066
4067 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4068 // be an unsigned int.
4069 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4070
4071 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4072 // suffix for portability of code with C++, but both `l` and `ll` are
4073 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4074 // same.
4075 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4076 Literal.isLong = true;
4077 Literal.isLongLong = false;
4078 }
4079
4080 // Check from smallest to largest, picking the smallest type we can.
4081 unsigned Width = 0;
4082
4083 // Microsoft specific integer suffixes are explicitly sized.
4084 if (Literal.MicrosoftInteger) {
4085 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4086 Width = 8;
4087 Ty = Context.CharTy;
4088 } else {
4089 Width = Literal.MicrosoftInteger;
4090 Ty = Context.getIntTypeForBitwidth(Width,
4091 /*Signed=*/!Literal.isUnsigned);
4092 }
4093 }
4094
4095 // Bit-precise integer literals are automagically-sized based on the
4096 // width required by the literal.
4097 if (Literal.isBitInt) {
4098 // The signed version has one more bit for the sign value. There are no
4099 // zero-width bit-precise integers, even if the literal value is 0.
4100 Width = std::max(ResultVal.getActiveBits(), 1u) +
4101 (Literal.isUnsigned ? 0u : 1u);
4102
4103 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4104 // and reset the type to the largest supported width.
4105 unsigned int MaxBitIntWidth =
4106 Context.getTargetInfo().getMaxBitIntWidth();
4107 if (Width > MaxBitIntWidth) {
4108 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4109 << Literal.isUnsigned;
4110 Width = MaxBitIntWidth;
4111 }
4112
4113 // Reset the result value to the smaller APInt and select the correct
4114 // type to be used. Note, we zext even for signed values because the
4115 // literal itself is always an unsigned value (a preceeding - is a
4116 // unary operator, not part of the literal).
4117 ResultVal = ResultVal.zextOrTrunc(Width);
4118 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4119 }
4120
4121 // Check C++23 size_t literals.
4122 if (Literal.isSizeT) {
4123 assert(!Literal.MicrosoftInteger &&
4124 "size_t literals can't be Microsoft literals");
4125 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4126 Context.getTargetInfo().getSizeType());
4127
4128 // Does it fit in size_t?
4129 if (ResultVal.isIntN(SizeTSize)) {
4130 // Does it fit in ssize_t?
4131 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4132 Ty = Context.getSignedSizeType();
4133 else if (AllowUnsigned)
4134 Ty = Context.getSizeType();
4135 Width = SizeTSize;
4136 }
4137 }
4138
4139 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4140 !Literal.isSizeT) {
4141 // Are int/unsigned possibilities?
4142 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4143
4144 // Does it fit in a unsigned int?
4145 if (ResultVal.isIntN(IntSize)) {
4146 // Does it fit in a signed int?
4147 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4148 Ty = Context.IntTy;
4149 else if (AllowUnsigned)
4150 Ty = Context.UnsignedIntTy;
4151 Width = IntSize;
4152 }
4153 }
4154
4155 // Are long/unsigned long possibilities?
4156 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4157 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4158
4159 // Does it fit in a unsigned long?
4160 if (ResultVal.isIntN(LongSize)) {
4161 // Does it fit in a signed long?
4162 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4163 Ty = Context.LongTy;
4164 else if (AllowUnsigned)
4165 Ty = Context.UnsignedLongTy;
4166 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4167 // is compatible.
4168 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4169 const unsigned LongLongSize =
4170 Context.getTargetInfo().getLongLongWidth();
4171 Diag(Tok.getLocation(),
4173 ? Literal.isLong
4174 ? diag::warn_old_implicitly_unsigned_long_cxx
4175 : /*C++98 UB*/ diag::
4176 ext_old_implicitly_unsigned_long_cxx
4177 : diag::warn_old_implicitly_unsigned_long)
4178 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4179 : /*will be ill-formed*/ 1);
4180 Ty = Context.UnsignedLongTy;
4181 }
4182 Width = LongSize;
4183 }
4184 }
4185
4186 // Check long long if needed.
4187 if (Ty.isNull() && !Literal.isSizeT) {
4188 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4189
4190 // Does it fit in a unsigned long long?
4191 if (ResultVal.isIntN(LongLongSize)) {
4192 // Does it fit in a signed long long?
4193 // To be compatible with MSVC, hex integer literals ending with the
4194 // LL or i64 suffix are always signed in Microsoft mode.
4195 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4196 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4197 Ty = Context.LongLongTy;
4198 else if (AllowUnsigned)
4199 Ty = Context.UnsignedLongLongTy;
4200 Width = LongLongSize;
4201
4202 // 'long long' is a C99 or C++11 feature, whether the literal
4203 // explicitly specified 'long long' or we needed the extra width.
4204 if (getLangOpts().CPlusPlus)
4205 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4206 ? diag::warn_cxx98_compat_longlong
4207 : diag::ext_cxx11_longlong);
4208 else if (!getLangOpts().C99)
4209 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4210 }
4211 }
4212
4213 // If we still couldn't decide a type, we either have 'size_t' literal
4214 // that is out of range, or a decimal literal that does not fit in a
4215 // signed long long and has no U suffix.
4216 if (Ty.isNull()) {
4217 if (Literal.isSizeT)
4218 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4219 << Literal.isUnsigned;
4220 else
4221 Diag(Tok.getLocation(),
4222 diag::ext_integer_literal_too_large_for_signed);
4223 Ty = Context.UnsignedLongLongTy;
4224 Width = Context.getTargetInfo().getLongLongWidth();
4225 }
4226
4227 if (ResultVal.getBitWidth() != Width)
4228 ResultVal = ResultVal.trunc(Width);
4229 }
4230 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4231 }
4232
4233 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4234 if (Literal.isImaginary) {
4235 Res = new (Context) ImaginaryLiteral(Res,
4236 Context.getComplexType(Res->getType()));
4237
4238 // In C++, this is a GNU extension. In C, it's a C2y extension.
4239 unsigned DiagId;
4240 if (getLangOpts().CPlusPlus)
4241 DiagId = diag::ext_gnu_imaginary_constant;
4242 else if (getLangOpts().C2y)
4243 DiagId = diag::warn_c23_compat_imaginary_constant;
4244 else
4245 DiagId = diag::ext_c2y_imaginary_constant;
4246 Diag(Tok.getLocation(), DiagId);
4247 }
4248 return Res;
4249}
4250
4252 assert(E && "ActOnParenExpr() missing expr");
4253 QualType ExprTy = E->getType();
4254 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4255 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4256 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4257 return new (Context) ParenExpr(L, R, E);
4258}
4259
4261 SourceLocation Loc,
4262 SourceRange ArgRange) {
4263 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4264 // scalar or vector data type argument..."
4265 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4266 // type (C99 6.2.5p18) or void.
4267 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4268 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4269 << T << ArgRange;
4270 return true;
4271 }
4272
4273 assert((T->isVoidType() || !T->isIncompleteType()) &&
4274 "Scalar types should always be complete");
4275 return false;
4276}
4277
4279 SourceLocation Loc,
4280 SourceRange ArgRange) {
4281 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4282 if (!T->isVectorType() && !T->isSizelessVectorType())
4283 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4284 << ""
4285 << "__builtin_vectorelements" << T << ArgRange;
4286
4287 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
4288 if (T->isSVESizelessBuiltinType()) {
4289 llvm::StringMap<bool> CallerFeatureMap;
4290 S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
4291 return S.ARM().checkSVETypeSupport(T, Loc, FD, CallerFeatureMap);
4292 }
4293 }
4294
4295 return false;
4296}
4297
4299 SourceLocation Loc,
4300 SourceRange ArgRange) {
4301 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4302 return true;
4303
4304 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4305 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4306 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4307 return true;
4308 }
4309
4310 return false;
4311}
4312
4314 SourceLocation Loc,
4315 SourceRange ArgRange,
4316 UnaryExprOrTypeTrait TraitKind) {
4317 // Invalid types must be hard errors for SFINAE in C++.
4318 if (S.LangOpts.CPlusPlus)
4319 return true;
4320
4321 // C99 6.5.3.4p1:
4322 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4323 TraitKind == UETT_PreferredAlignOf) {
4324
4325 // sizeof(function)/alignof(function) is allowed as an extension.
4326 if (T->isFunctionType()) {
4327 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4328 << getTraitSpelling(TraitKind) << ArgRange;
4329 return false;
4330 }
4331
4332 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4333 // this is an error (OpenCL v1.1 s6.3.k)
4334 if (T->isVoidType()) {
4335 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4336 : diag::ext_sizeof_alignof_void_type;
4337 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4338 return false;
4339 }
4340 }
4341 return true;
4342}
4343
4345 SourceLocation Loc,
4346 SourceRange ArgRange,
4347 UnaryExprOrTypeTrait TraitKind) {
4348 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4349 // runtime doesn't allow it.
4350 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4351 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4352 << T << (TraitKind == UETT_SizeOf)
4353 << ArgRange;
4354 return true;
4355 }
4356
4357 return false;
4358}
4359
4360/// Check whether E is a pointer from a decayed array type (the decayed
4361/// pointer type is equal to T) and emit a warning if it is.
4363 const Expr *E) {
4364 // Don't warn if the operation changed the type.
4365 if (T != E->getType())
4366 return;
4367
4368 // Now look for array decays.
4369 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4370 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4371 return;
4372
4373 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4374 << ICE->getType()
4375 << ICE->getSubExpr()->getType();
4376}
4377
4379 UnaryExprOrTypeTrait ExprKind) {
4380 QualType ExprTy = E->getType();
4381 assert(!ExprTy->isReferenceType());
4382
4383 bool IsUnevaluatedOperand =
4384 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4385 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4386 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4387 if (IsUnevaluatedOperand) {
4389 if (Result.isInvalid())
4390 return true;
4391 E = Result.get();
4392 }
4393
4394 // The operand for sizeof and alignof is in an unevaluated expression context,
4395 // so side effects could result in unintended consequences.
4396 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4397 // used to build SFINAE gadgets.
4398 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4399 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4401 !E->getType()->isVariableArrayType() &&
4402 E->HasSideEffects(Context, false))
4403 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4404
4405 if (ExprKind == UETT_VecStep)
4406 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4407 E->getSourceRange());
4408
4409 if (ExprKind == UETT_VectorElements)
4410 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4411 E->getSourceRange());
4412
4413 // Explicitly list some types as extensions.
4414 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4415 E->getSourceRange(), ExprKind))
4416 return false;
4417
4418 // WebAssembly tables are always illegal operands to unary expressions and
4419 // type traits.
4420 if (Context.getTargetInfo().getTriple().isWasm() &&
4422 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4423 << getTraitSpelling(ExprKind);
4424 return true;
4425 }
4426
4427 // 'alignof' applied to an expression only requires the base element type of
4428 // the expression to be complete. 'sizeof' requires the expression's type to
4429 // be complete (and will attempt to complete it if it's an array of unknown
4430 // bound).
4431 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4433 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4434 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4435 getTraitSpelling(ExprKind), E->getSourceRange()))
4436 return true;
4437 } else {
4439 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4440 getTraitSpelling(ExprKind), E->getSourceRange()))
4441 return true;
4442 }
4443
4444 // Completing the expression's type may have changed it.
4445 ExprTy = E->getType();
4446 assert(!ExprTy->isReferenceType());
4447
4448 if (ExprTy->isFunctionType()) {
4449 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4450 << getTraitSpelling(ExprKind) << E->getSourceRange();
4451 return true;
4452 }
4453
4454 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4455 E->getSourceRange(), ExprKind))
4456 return true;
4457
4458 if (ExprKind == UETT_CountOf) {
4459 // The type has to be an array type. We already checked for incomplete
4460 // types above.
4461 QualType ExprType = E->IgnoreParens()->getType();
4462 if (!ExprType->isArrayType()) {
4463 Diag(E->getExprLoc(), diag::err_countof_arg_not_array_type) << ExprType;
4464 return true;
4465 }
4466 // FIXME: warn on _Countof on an array parameter. Not warning on it
4467 // currently because there are papers in WG14 about array types which do
4468 // not decay that could impact this behavior, so we want to see if anything
4469 // changes here before coming up with a warning group for _Countof-related
4470 // diagnostics.
4471 }
4472
4473 if (ExprKind == UETT_SizeOf) {
4474 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4475 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4476 QualType OType = PVD->getOriginalType();
4477 QualType Type = PVD->getType();
4478 if (Type->isPointerType() && OType->isArrayType()) {
4479 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4480 << Type << OType;
4481 Diag(PVD->getLocation(), diag::note_declared_at);
4482 }
4483 }
4484 }
4485
4486 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4487 // decays into a pointer and returns an unintended result. This is most
4488 // likely a typo for "sizeof(array) op x".
4489 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4490 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4491 BO->getLHS());
4492 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4493 BO->getRHS());
4494 }
4495 }
4496
4497 return false;
4498}
4499
4500static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4501 // Cannot know anything else if the expression is dependent.
4502 if (E->isTypeDependent())
4503 return false;
4504
4505 if (E->getObjectKind() == OK_BitField) {
4506 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4507 << 1 << E->getSourceRange();
4508 return true;
4509 }
4510
4511 ValueDecl *D = nullptr;
4512 Expr *Inner = E->IgnoreParens();
4513 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4514 D = DRE->getDecl();
4515 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4516 D = ME->getMemberDecl();
4517 }
4518
4519 // If it's a field, require the containing struct to have a
4520 // complete definition so that we can compute the layout.
4521 //
4522 // This can happen in C++11 onwards, either by naming the member
4523 // in a way that is not transformed into a member access expression
4524 // (in an unevaluated operand, for instance), or by naming the member
4525 // in a trailing-return-type.
4526 //
4527 // For the record, since __alignof__ on expressions is a GCC
4528 // extension, GCC seems to permit this but always gives the
4529 // nonsensical answer 0.
4530 //
4531 // We don't really need the layout here --- we could instead just
4532 // directly check for all the appropriate alignment-lowing
4533 // attributes --- but that would require duplicating a lot of
4534 // logic that just isn't worth duplicating for such a marginal
4535 // use-case.
4536 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4537 // Fast path this check, since we at least know the record has a
4538 // definition if we can find a member of it.
4539 if (!FD->getParent()->isCompleteDefinition()) {
4540 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4541 << E->getSourceRange();
4542 return true;
4543 }
4544
4545 // Otherwise, if it's a field, and the field doesn't have
4546 // reference type, then it must have a complete type (or be a
4547 // flexible array member, which we explicitly want to
4548 // white-list anyway), which makes the following checks trivial.
4549 if (!FD->getType()->isReferenceType())
4550 return false;
4551 }
4552
4553 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4554}
4555
4557 E = E->IgnoreParens();
4558
4559 // Cannot know anything else if the expression is dependent.
4560 if (E->isTypeDependent())
4561 return false;
4562
4563 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4564}
4565
4567 CapturingScopeInfo *CSI) {
4568 assert(T->isVariablyModifiedType());
4569 assert(CSI != nullptr);
4570
4571 // We're going to walk down into the type and look for VLA expressions.
4572 do {
4573 const Type *Ty = T.getTypePtr();
4574 switch (Ty->getTypeClass()) {
4575#define TYPE(Class, Base)
4576#define ABSTRACT_TYPE(Class, Base)
4577#define NON_CANONICAL_TYPE(Class, Base)
4578#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4579#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4580#include "clang/AST/TypeNodes.inc"
4581 T = QualType();
4582 break;
4583 // These types are never variably-modified.
4584 case Type::Builtin:
4585 case Type::Complex:
4586 case Type::Vector:
4587 case Type::ExtVector:
4588 case Type::ConstantMatrix:
4589 case Type::Record:
4590 case Type::Enum:
4591 case Type::TemplateSpecialization:
4592 case Type::ObjCObject:
4593 case Type::ObjCInterface:
4594 case Type::ObjCObjectPointer:
4595 case Type::ObjCTypeParam:
4596 case Type::Pipe:
4597 case Type::BitInt:
4598 case Type::HLSLInlineSpirv:
4599 llvm_unreachable("type class is never variably-modified!");
4600 case Type::Adjusted:
4601 T = cast<AdjustedType>(Ty)->getOriginalType();
4602 break;
4603 case Type::Decayed:
4604 T = cast<DecayedType>(Ty)->getPointeeType();
4605 break;
4606 case Type::ArrayParameter:
4607 T = cast<ArrayParameterType>(Ty)->getElementType();
4608 break;
4609 case Type::Pointer:
4610 T = cast<PointerType>(Ty)->getPointeeType();
4611 break;
4612 case Type::BlockPointer:
4613 T = cast<BlockPointerType>(Ty)->getPointeeType();
4614 break;
4615 case Type::LValueReference:
4616 case Type::RValueReference:
4617 T = cast<ReferenceType>(Ty)->getPointeeType();
4618 break;
4619 case Type::MemberPointer:
4620 T = cast<MemberPointerType>(Ty)->getPointeeType();
4621 break;
4622 case Type::ConstantArray:
4623 case Type::IncompleteArray:
4624 // Losing element qualification here is fine.
4625 T = cast<ArrayType>(Ty)->getElementType();
4626 break;
4627 case Type::VariableArray: {
4628 // Losing element qualification here is fine.
4630
4631 // Unknown size indication requires no size computation.
4632 // Otherwise, evaluate and record it.
4633 auto Size = VAT->getSizeExpr();
4634 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4636 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4637
4638 T = VAT->getElementType();
4639 break;
4640 }
4641 case Type::FunctionProto:
4642 case Type::FunctionNoProto:
4643 T = cast<FunctionType>(Ty)->getReturnType();
4644 break;
4645 case Type::Paren:
4646 case Type::TypeOf:
4647 case Type::UnaryTransform:
4648 case Type::Attributed:
4649 case Type::BTFTagAttributed:
4650 case Type::OverflowBehavior:
4651 case Type::HLSLAttributedResource:
4652 case Type::SubstTemplateTypeParm:
4653 case Type::MacroQualified:
4654 case Type::CountAttributed:
4655 // Keep walking after single level desugaring.
4656 T = T.getSingleStepDesugaredType(Context);
4657 break;
4658 case Type::Typedef:
4659 T = cast<TypedefType>(Ty)->desugar();
4660 break;
4661 case Type::Decltype:
4662 T = cast<DecltypeType>(Ty)->desugar();
4663 break;
4664 case Type::PackIndexing:
4665 T = cast<PackIndexingType>(Ty)->desugar();
4666 break;
4667 case Type::Using:
4668 T = cast<UsingType>(Ty)->desugar();
4669 break;
4670 case Type::Auto:
4671 case Type::DeducedTemplateSpecialization:
4672 T = cast<DeducedType>(Ty)->getDeducedType();
4673 break;
4674 case Type::TypeOfExpr:
4675 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4676 break;
4677 case Type::Atomic:
4678 T = cast<AtomicType>(Ty)->getValueType();
4679 break;
4680 case Type::PredefinedSugar:
4681 T = cast<PredefinedSugarType>(Ty)->desugar();
4682 break;
4683 }
4684 } while (!T.isNull() && T->isVariablyModifiedType());
4685}
4686
4688 SourceLocation OpLoc,
4689 SourceRange ExprRange,
4690 UnaryExprOrTypeTrait ExprKind,
4691 StringRef KWName) {
4692 if (ExprType->isDependentType())
4693 return false;
4694
4695 // C++ [expr.sizeof]p2:
4696 // When applied to a reference or a reference type, the result
4697 // is the size of the referenced type.
4698 // C++11 [expr.alignof]p3:
4699 // When alignof is applied to a reference type, the result
4700 // shall be the alignment of the referenced type.
4701 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4702 ExprType = Ref->getPointeeType();
4703
4704 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4705 // When alignof or _Alignof is applied to an array type, the result
4706 // is the alignment of the element type.
4707 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4708 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4709 // If the trait is 'alignof' in C before C2y, the ability to apply the
4710 // trait to an incomplete array is an extension.
4711 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4712 ExprType->isIncompleteArrayType())
4713 Diag(OpLoc, getLangOpts().C2y
4714 ? diag::warn_c2y_compat_alignof_incomplete_array
4715 : diag::ext_c2y_alignof_incomplete_array);
4716 ExprType = Context.getBaseElementType(ExprType);
4717 }
4718
4719 if (ExprKind == UETT_VecStep)
4720 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4721
4722 if (ExprKind == UETT_VectorElements)
4723 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4724 ExprRange);
4725
4726 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4727 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4728 ExprRange);
4729
4730 // Explicitly list some types as extensions.
4731 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4732 ExprKind))
4733 return false;
4734
4736 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4737 KWName, ExprRange))
4738 return true;
4739
4740 if (ExprType->isFunctionType()) {
4741 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4742 return true;
4743 }
4744
4745 if (ExprKind == UETT_CountOf) {
4746 // The type has to be an array type. We already checked for incomplete
4747 // types above.
4748 if (!ExprType->isArrayType()) {
4749 Diag(OpLoc, diag::err_countof_arg_not_array_type) << ExprType;
4750 return true;
4751 }
4752 }
4753
4754 // WebAssembly tables are always illegal operands to unary expressions and
4755 // type traits.
4756 if (Context.getTargetInfo().getTriple().isWasm() &&
4757 ExprType->isWebAssemblyTableType()) {
4758 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4759 << getTraitSpelling(ExprKind);
4760 return true;
4761 }
4762
4763 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4764 ExprKind))
4765 return true;
4766
4767 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4768 if (auto *TT = ExprType->getAs<TypedefType>()) {
4769 for (auto I = FunctionScopes.rbegin(),
4770 E = std::prev(FunctionScopes.rend());
4771 I != E; ++I) {
4772 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4773 if (CSI == nullptr)
4774 break;
4775 DeclContext *DC = nullptr;
4776 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4777 DC = LSI->CallOperator;
4778 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4779 DC = CRSI->TheCapturedDecl;
4780 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4781 DC = BSI->TheDecl;
4782 if (DC) {
4783 if (DC->containsDecl(TT->getDecl()))
4784 break;
4785 captureVariablyModifiedType(Context, ExprType, CSI);
4786 }
4787 }
4788 }
4789 }
4790
4791 return false;
4792}
4793
4795 SourceLocation OpLoc,
4796 UnaryExprOrTypeTrait ExprKind,
4797 SourceRange R) {
4798 if (!TInfo)
4799 return ExprError();
4800
4801 QualType T = TInfo->getType();
4802
4803 if (!T->isDependentType() &&
4804 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4805 getTraitSpelling(ExprKind)))
4806 return ExprError();
4807
4808 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4809 // properly deal with VLAs in nested calls of sizeof and typeof.
4810 if (currentEvaluationContext().isUnevaluated() &&
4811 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4812 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4813 TInfo->getType()->isVariablyModifiedType())
4814 TInfo = TransformToPotentiallyEvaluated(TInfo);
4815
4816 // It's possible that the transformation above failed.
4817 if (!TInfo)
4818 return ExprError();
4819
4820 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4821 return new (Context) UnaryExprOrTypeTraitExpr(
4822 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4823}
4824
4827 UnaryExprOrTypeTrait ExprKind) {
4829 if (PE.isInvalid())
4830 return ExprError();
4831
4832 E = PE.get();
4833
4834 // Verify that the operand is valid.
4835 bool isInvalid = false;
4836 if (E->isTypeDependent()) {
4837 // Delay type-checking for type-dependent expressions.
4838 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4839 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4840 } else if (ExprKind == UETT_VecStep) {
4842 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4843 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4844 isInvalid = true;
4845 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4846 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4847 isInvalid = true;
4848 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4849 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4851 }
4852
4853 if (isInvalid)
4854 return ExprError();
4855
4856 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4857 E->getType()->isVariableArrayType()) {
4859 if (PE.isInvalid()) return ExprError();
4860 E = PE.get();
4861 }
4862
4863 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4864 return new (Context) UnaryExprOrTypeTraitExpr(
4865 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4866}
4867
4870 UnaryExprOrTypeTrait ExprKind, bool IsType,
4871 void *TyOrEx, SourceRange ArgRange) {
4872 // If error parsing type, ignore.
4873 if (!TyOrEx) return ExprError();
4874
4875 if (IsType) {
4876 TypeSourceInfo *TInfo;
4877 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4878 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4879 }
4880
4881 Expr *ArgEx = (Expr *)TyOrEx;
4882 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4883 return Result;
4884}
4885
4887 SourceLocation OpLoc, SourceRange R) {
4888 if (!TInfo)
4889 return true;
4890 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4891 UETT_AlignOf, KWName);
4892}
4893
4895 SourceLocation OpLoc, SourceRange R) {
4896 TypeSourceInfo *TInfo;
4898 &TInfo);
4899 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4900}
4901
4903 bool IsReal) {
4904 if (V.get()->isTypeDependent())
4905 return S.Context.DependentTy;
4906
4907 // _Real and _Imag are only l-values for normal l-values.
4908 if (V.get()->getObjectKind() != OK_Ordinary) {
4909 V = S.DefaultLvalueConversion(V.get());
4910 if (V.isInvalid())
4911 return QualType();
4912 }
4913
4914 // These operators return the element type of a complex type.
4915 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4916 return CT->getElementType();
4917
4918 // Otherwise they pass through real integer and floating point types here.
4919 if (V.get()->getType()->isArithmeticType())
4920 return V.get()->getType();
4921
4922 // Test for placeholders.
4923 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4924 if (PR.isInvalid()) return QualType();
4925 if (PR.get() != V.get()) {
4926 V = PR;
4927 return CheckRealImagOperand(S, V, Loc, IsReal);
4928 }
4929
4930 // Reject anything else.
4931 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4932 << (IsReal ? "__real" : "__imag");
4933 return QualType();
4934}
4935
4936
4937
4940 tok::TokenKind Kind, Expr *Input) {
4942 switch (Kind) {
4943 default: llvm_unreachable("Unknown unary op!");
4944 case tok::plusplus: Opc = UO_PostInc; break;
4945 case tok::minusminus: Opc = UO_PostDec; break;
4946 }
4947
4948 // Since this might is a postfix expression, get rid of ParenListExprs.
4950 if (Result.isInvalid()) return ExprError();
4951 Input = Result.get();
4952
4953 return BuildUnaryOp(S, OpLoc, Opc, Input);
4954}
4955
4956/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4957///
4958/// \return true on error
4960 SourceLocation opLoc,
4961 Expr *op) {
4962 assert(op->getType()->isObjCObjectPointerType());
4964 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4965 return false;
4966
4967 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4969 << op->getSourceRange();
4970 return true;
4971}
4972
4974 auto *BaseNoParens = Base->IgnoreParens();
4975 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4976 return MSProp->getPropertyDecl()->getType()->isArrayType();
4977 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4978}
4979
4980// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4981// Typically this is DependentTy, but can sometimes be more precise.
4982//
4983// There are cases when we could determine a non-dependent type:
4984// - LHS and RHS may have non-dependent types despite being type-dependent
4985// (e.g. unbounded array static members of the current instantiation)
4986// - one may be a dependent-sized array with known element type
4987// - one may be a dependent-typed valid index (enum in current instantiation)
4988//
4989// We *always* return a dependent type, in such cases it is DependentTy.
4990// This avoids creating type-dependent expressions with non-dependent types.
4991// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4993 const ASTContext &Ctx) {
4994 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4995 QualType LTy = LHS->getType(), RTy = RHS->getType();
4996 QualType Result = Ctx.DependentTy;
4997 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4998 if (const PointerType *PT = LTy->getAs<PointerType>())
4999 Result = PT->getPointeeType();
5000 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5001 Result = AT->getElementType();
5002 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5003 if (const PointerType *PT = RTy->getAs<PointerType>())
5004 Result = PT->getPointeeType();
5005 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5006 Result = AT->getElementType();
5007 }
5008 // Ensure we return a dependent type.
5009 return Result->isDependentType() ? Result : Ctx.DependentTy;
5010}
5011
5013 SourceLocation lbLoc,
5014 MultiExprArg ArgExprs,
5015 SourceLocation rbLoc) {
5016
5017 if (base && !base->getType().isNull() &&
5018 base->hasPlaceholderType(BuiltinType::ArraySection)) {
5019 auto *AS = cast<ArraySectionExpr>(base);
5020 if (AS->isOMPArraySection())
5022 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
5023 /*Length*/ nullptr,
5024 /*Stride=*/nullptr, rbLoc);
5025
5026 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
5027 SourceLocation(), /*Length*/ nullptr,
5028 rbLoc);
5029 }
5030
5031 // Since this might be a postfix expression, get rid of ParenListExprs.
5032 if (isa<ParenListExpr>(base)) {
5034 if (result.isInvalid())
5035 return ExprError();
5036 base = result.get();
5037 }
5038
5039 // Check if base and idx form a MatrixSubscriptExpr.
5040 //
5041 // Helper to check for comma expressions, which are not allowed as indices for
5042 // matrix subscript expressions.
5043 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
5044 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
5045 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
5046 << SourceRange(base->getBeginLoc(), rbLoc);
5047 return true;
5048 }
5049 return false;
5050 };
5051 // The matrix subscript operator ([][])is considered a single operator.
5052 // Separating the index expressions by parenthesis is not allowed.
5053 if (base && !base->getType().isNull() &&
5054 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
5055 !isa<MatrixSubscriptExpr>(base)) {
5056 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
5057 << SourceRange(base->getBeginLoc(), rbLoc);
5058 return ExprError();
5059 }
5060 // If the base is a MatrixSubscriptExpr, try to create a new
5061 // MatrixSubscriptExpr.
5062 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
5063 if (matSubscriptE) {
5064 assert(ArgExprs.size() == 1);
5065 if (CheckAndReportCommaError(ArgExprs.front()))
5066 return ExprError();
5067
5068 assert(matSubscriptE->isIncomplete() &&
5069 "base has to be an incomplete matrix subscript");
5070 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
5071 matSubscriptE->getRowIdx(),
5072 ArgExprs.front(), rbLoc);
5073 }
5074 if (base->getType()->isWebAssemblyTableType()) {
5075 Diag(base->getExprLoc(), diag::err_wasm_table_art)
5076 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5077 return ExprError();
5078 }
5079
5080 CheckInvalidBuiltinCountedByRef(base,
5082
5083 // Handle any non-overload placeholder types in the base and index
5084 // expressions. We can't handle overloads here because the other
5085 // operand might be an overloadable type, in which case the overload
5086 // resolution for the operator overload should get the first crack
5087 // at the overload.
5088 bool IsMSPropertySubscript = false;
5089 if (base->getType()->isNonOverloadPlaceholderType()) {
5090 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5091 if (!IsMSPropertySubscript) {
5092 ExprResult result = CheckPlaceholderExpr(base);
5093 if (result.isInvalid())
5094 return ExprError();
5095 base = result.get();
5096 }
5097 }
5098
5099 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5100 if (base->getType()->isMatrixType()) {
5101 assert(ArgExprs.size() == 1);
5102 if (CheckAndReportCommaError(ArgExprs.front()))
5103 return ExprError();
5104
5105 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5106 rbLoc);
5107 }
5108
5109 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5110 Expr *idx = ArgExprs[0];
5111 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5113 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5114 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5115 << SourceRange(base->getBeginLoc(), rbLoc);
5116 }
5117 }
5118
5119 if (ArgExprs.size() == 1 &&
5120 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5121 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5122 if (result.isInvalid())
5123 return ExprError();
5124 ArgExprs[0] = result.get();
5125 } else {
5126 if (CheckArgsForPlaceholders(ArgExprs))
5127 return ExprError();
5128 }
5129
5130 // Build an unanalyzed expression if either operand is type-dependent.
5131 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5132 (base->isTypeDependent() ||
5134 !isa<PackExpansionExpr>(ArgExprs[0])) {
5135 return new (Context) ArraySubscriptExpr(
5136 base, ArgExprs.front(),
5137 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5138 VK_LValue, OK_Ordinary, rbLoc);
5139 }
5140
5141 // MSDN, property (C++)
5142 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5143 // This attribute can also be used in the declaration of an empty array in a
5144 // class or structure definition. For example:
5145 // __declspec(property(get=GetX, put=PutX)) int x[];
5146 // The above statement indicates that x[] can be used with one or more array
5147 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5148 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5149 if (IsMSPropertySubscript) {
5150 assert(ArgExprs.size() == 1);
5151 // Build MS property subscript expression if base is MS property reference
5152 // or MS property subscript.
5153 return new (Context)
5154 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5155 VK_LValue, OK_Ordinary, rbLoc);
5156 }
5157
5158 // Use C++ overloaded-operator rules if either operand has record
5159 // type. The spec says to do this if either type is *overloadable*,
5160 // but enum types can't declare subscript operators or conversion
5161 // operators, so there's nothing interesting for overload resolution
5162 // to do if there aren't any record types involved.
5163 //
5164 // ObjC pointers have their own subscripting logic that is not tied
5165 // to overload resolution and so should not take this path.
5167 ((base->getType()->isRecordType() ||
5168 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5169 ArgExprs[0]->getType()->isRecordType())))) {
5170 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5171 }
5172
5173 ExprResult Res =
5174 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5175
5176 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5177 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5178
5179 return Res;
5180}
5181
5184 InitializationKind Kind =
5186 InitializationSequence InitSeq(*this, Entity, Kind, E);
5187 return InitSeq.Perform(*this, Entity, Kind, E);
5188}
5189
5191 Expr *RowIdx,
5192 SourceLocation RBLoc) {
5194 if (BaseR.isInvalid())
5195 return BaseR;
5196 Base = BaseR.get();
5197
5198 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5199 if (RowR.isInvalid())
5200 return RowR;
5201 RowIdx = RowR.get();
5202
5203 // Build an unanalyzed expression if any of the operands is type-dependent.
5204 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5205 return new (Context)
5206 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5207
5208 // Check that IndexExpr is an integer expression. If it is a constant
5209 // expression, check that it is less than Dim (= the number of elements in the
5210 // corresponding dimension).
5211 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5212 bool IsColumnIdx) -> Expr * {
5213 if (!IndexExpr->getType()->isIntegerType() &&
5214 !IndexExpr->isTypeDependent()) {
5215 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5216 << IsColumnIdx;
5217 return nullptr;
5218 }
5219
5220 if (std::optional<llvm::APSInt> Idx =
5221 IndexExpr->getIntegerConstantExpr(Context)) {
5222 if ((*Idx < 0 || *Idx >= Dim)) {
5223 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5224 << IsColumnIdx << Dim;
5225 return nullptr;
5226 }
5227 }
5228
5229 ExprResult ConvExpr = IndexExpr;
5230 assert(!ConvExpr.isInvalid() &&
5231 "should be able to convert any integer type to size type");
5232 return ConvExpr.get();
5233 };
5234
5235 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5236 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5237 if (!RowIdx)
5238 return ExprError();
5239
5240 QualType RowVecQT =
5241 Context.getExtVectorType(MTy->getElementType(), MTy->getNumColumns());
5242
5243 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5244}
5245
5247 Expr *ColumnIdx,
5248 SourceLocation RBLoc) {
5250 if (BaseR.isInvalid())
5251 return BaseR;
5252 Base = BaseR.get();
5253
5254 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5255 if (RowR.isInvalid())
5256 return RowR;
5257 RowIdx = RowR.get();
5258
5259 if (!ColumnIdx)
5260 return new (Context) MatrixSubscriptExpr(
5261 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5262
5263 // Build an unanalyzed expression if any of the operands is type-dependent.
5264 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5265 ColumnIdx->isTypeDependent())
5266 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5267 Context.DependentTy, RBLoc);
5268
5269 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5270 if (ColumnR.isInvalid())
5271 return ColumnR;
5272 ColumnIdx = ColumnR.get();
5273
5274 // Check that IndexExpr is an integer expression. If it is a constant
5275 // expression, check that it is less than Dim (= the number of elements in the
5276 // corresponding dimension).
5277 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5278 bool IsColumnIdx) -> Expr * {
5279 if (!IndexExpr->getType()->isIntegerType() &&
5280 !IndexExpr->isTypeDependent()) {
5281 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5282 << IsColumnIdx;
5283 return nullptr;
5284 }
5285
5286 if (std::optional<llvm::APSInt> Idx =
5287 IndexExpr->getIntegerConstantExpr(Context)) {
5288 if ((*Idx < 0 || *Idx >= Dim)) {
5289 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5290 << IsColumnIdx << Dim;
5291 return nullptr;
5292 }
5293 }
5294
5295 ExprResult ConvExpr = IndexExpr;
5296 assert(!ConvExpr.isInvalid() &&
5297 "should be able to convert any integer type to size type");
5298 return ConvExpr.get();
5299 };
5300
5301 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5302 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5303 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5304 if (!RowIdx || !ColumnIdx)
5305 return ExprError();
5306
5307 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5308 MTy->getElementType(), RBLoc);
5309}
5310
5311void Sema::CheckAddressOfNoDeref(const Expr *E) {
5312 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5313 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5314
5315 // For expressions like `&(*s).b`, the base is recorded and what should be
5316 // checked.
5317 const MemberExpr *Member = nullptr;
5318 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5319 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5320
5321 LastRecord.PossibleDerefs.erase(StrippedExpr);
5322}
5323
5324void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5326 return;
5327
5328 QualType ResultTy = E->getType();
5329 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5330
5331 // Bail if the element is an array since it is not memory access.
5332 if (isa<ArrayType>(ResultTy))
5333 return;
5334
5335 if (ResultTy->hasAttr(attr::NoDeref)) {
5336 LastRecord.PossibleDerefs.insert(E);
5337 return;
5338 }
5339
5340 // Check if the base type is a pointer to a member access of a struct
5341 // marked with noderef.
5342 const Expr *Base = E->getBase();
5343 QualType BaseTy = Base->getType();
5344 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5345 // Not a pointer access
5346 return;
5347
5348 const MemberExpr *Member = nullptr;
5349 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5350 Member->isArrow())
5351 Base = Member->getBase();
5352
5353 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5354 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5355 LastRecord.PossibleDerefs.insert(E);
5356 }
5357}
5358
5361 Expr *Idx, SourceLocation RLoc) {
5362 Expr *LHSExp = Base;
5363 Expr *RHSExp = Idx;
5364
5367
5368 // Per C++ core issue 1213, the result is an xvalue if either operand is
5369 // a non-lvalue array, and an lvalue otherwise.
5370 if (getLangOpts().CPlusPlus11) {
5371 for (auto *Op : {LHSExp, RHSExp}) {
5372 Op = Op->IgnoreImplicit();
5373 if (Op->getType()->isArrayType() && !Op->isLValue())
5374 VK = VK_XValue;
5375 }
5376 }
5377
5378 // Perform default conversions.
5379 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5381 if (Result.isInvalid())
5382 return ExprError();
5383 LHSExp = Result.get();
5384 }
5386 if (Result.isInvalid())
5387 return ExprError();
5388 RHSExp = Result.get();
5389
5390 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5391
5392 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5393 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5394 // in the subscript position. As a result, we need to derive the array base
5395 // and index from the expression types.
5396 Expr *BaseExpr, *IndexExpr;
5397 QualType ResultType;
5398 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5399 BaseExpr = LHSExp;
5400 IndexExpr = RHSExp;
5401 ResultType =
5403 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5404 BaseExpr = LHSExp;
5405 IndexExpr = RHSExp;
5406 ResultType = PTy->getPointeeType();
5407 } else if (const ObjCObjectPointerType *PTy =
5408 LHSTy->getAs<ObjCObjectPointerType>()) {
5409 BaseExpr = LHSExp;
5410 IndexExpr = RHSExp;
5411
5412 // Use custom logic if this should be the pseudo-object subscript
5413 // expression.
5414 if (!LangOpts.isSubscriptPointerArithmetic())
5415 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5416 nullptr, nullptr);
5417
5418 ResultType = PTy->getPointeeType();
5419 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5420 // Handle the uncommon case of "123[Ptr]".
5421 BaseExpr = RHSExp;
5422 IndexExpr = LHSExp;
5423 ResultType = PTy->getPointeeType();
5424 } else if (const ObjCObjectPointerType *PTy =
5425 RHSTy->getAs<ObjCObjectPointerType>()) {
5426 // Handle the uncommon case of "123[Ptr]".
5427 BaseExpr = RHSExp;
5428 IndexExpr = LHSExp;
5429 ResultType = PTy->getPointeeType();
5430 if (!LangOpts.isSubscriptPointerArithmetic()) {
5431 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5432 << ResultType << BaseExpr->getSourceRange();
5433 return ExprError();
5434 }
5435 } else if (LHSTy->isSubscriptableVectorType()) {
5436 if (LHSTy->isBuiltinType() &&
5437 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5438 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5439 if (BTy->isSVEBool())
5440 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5441 << LHSExp->getSourceRange()
5442 << RHSExp->getSourceRange());
5443 ResultType = BTy->getSveEltType(Context);
5444 } else {
5445 const VectorType *VTy = LHSTy->getAs<VectorType>();
5446 ResultType = VTy->getElementType();
5447 }
5448 BaseExpr = LHSExp; // vectors: V[123]
5449 IndexExpr = RHSExp;
5450 // We apply C++ DR1213 to vector subscripting too.
5451 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5452 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5453 if (Materialized.isInvalid())
5454 return ExprError();
5455 LHSExp = Materialized.get();
5456 }
5457 VK = LHSExp->getValueKind();
5458 if (VK != VK_PRValue)
5459 OK = OK_VectorComponent;
5460
5461 QualType BaseType = BaseExpr->getType();
5462 Qualifiers BaseQuals = BaseType.getQualifiers();
5463 Qualifiers MemberQuals = ResultType.getQualifiers();
5464 Qualifiers Combined = BaseQuals + MemberQuals;
5465 if (Combined != MemberQuals)
5466 ResultType = Context.getQualifiedType(ResultType, Combined);
5467 } else if (LHSTy->isArrayType()) {
5468 // If we see an array that wasn't promoted by
5469 // DefaultFunctionArrayLvalueConversion, it must be an array that
5470 // wasn't promoted because of the C90 rule that doesn't
5471 // allow promoting non-lvalue arrays. Warn, then
5472 // force the promotion here.
5473 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5474 << LHSExp->getSourceRange();
5475 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5476 CK_ArrayToPointerDecay).get();
5477 LHSTy = LHSExp->getType();
5478
5479 BaseExpr = LHSExp;
5480 IndexExpr = RHSExp;
5481 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5482 } else if (RHSTy->isArrayType()) {
5483 // Same as previous, except for 123[f().a] case
5484 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5485 << RHSExp->getSourceRange();
5486 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5487 CK_ArrayToPointerDecay).get();
5488 RHSTy = RHSExp->getType();
5489
5490 BaseExpr = RHSExp;
5491 IndexExpr = LHSExp;
5492 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5493 } else {
5494 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5495 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5496 }
5497 // C99 6.5.2.1p1
5498 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5499 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5500 << IndexExpr->getSourceRange());
5501
5502 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5503 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5504 !IndexExpr->isTypeDependent()) {
5505 std::optional<llvm::APSInt> IntegerContantExpr =
5507 if (!IntegerContantExpr.has_value() ||
5508 IntegerContantExpr.value().isNegative())
5509 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5510 }
5511
5512 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5513 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5514 // type. Note that Functions are not objects, and that (in C99 parlance)
5515 // incomplete types are not object types.
5516 if (ResultType->isFunctionType()) {
5517 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5518 << ResultType << BaseExpr->getSourceRange();
5519 return ExprError();
5520 }
5521
5522 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5523 // GNU extension: subscripting on pointer to void
5524 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5525 << BaseExpr->getSourceRange();
5526
5527 // C forbids expressions of unqualified void type from being l-values.
5528 // See IsCForbiddenLValueType.
5529 if (!ResultType.hasQualifiers())
5530 VK = VK_PRValue;
5531 } else if (!ResultType->isDependentType() &&
5532 !ResultType.isWebAssemblyReferenceType() &&
5534 LLoc, ResultType,
5535 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5536 return ExprError();
5537
5538 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5539 !ResultType.isCForbiddenLValueType());
5540
5542 FunctionScopes.size() > 1) {
5543 if (auto *TT =
5544 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5545 for (auto I = FunctionScopes.rbegin(),
5546 E = std::prev(FunctionScopes.rend());
5547 I != E; ++I) {
5548 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5549 if (CSI == nullptr)
5550 break;
5551 DeclContext *DC = nullptr;
5552 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5553 DC = LSI->CallOperator;
5554 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5555 DC = CRSI->TheCapturedDecl;
5556 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5557 DC = BSI->TheDecl;
5558 if (DC) {
5559 if (DC->containsDecl(TT->getDecl()))
5560 break;
5562 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5563 }
5564 }
5565 }
5566 }
5567
5568 return new (Context)
5569 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5570}
5571
5573 ParmVarDecl *Param, Expr *RewrittenInit,
5574 bool SkipImmediateInvocations) {
5575 if (Param->hasUnparsedDefaultArg()) {
5576 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5577 // If we've already cleared out the location for the default argument,
5578 // that means we're parsing it right now.
5579 if (!UnparsedDefaultArgLocs.count(Param)) {
5580 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5581 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5582 Param->setInvalidDecl();
5583 return true;
5584 }
5585
5586 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5587 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5589 diag::note_default_argument_declared_here);
5590 return true;
5591 }
5592
5593 if (Param->hasUninstantiatedDefaultArg()) {
5594 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5595 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5596 return true;
5597 }
5598
5599 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5600 assert(Init && "default argument but no initializer?");
5601
5602 // If the default expression creates temporaries, we need to
5603 // push them to the current stack of expression temporaries so they'll
5604 // be properly destroyed.
5605 // FIXME: We should really be rebuilding the default argument with new
5606 // bound temporaries; see the comment in PR5810.
5607 // We don't need to do that with block decls, though, because
5608 // blocks in default argument expression can never capture anything.
5609 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5610 // Set the "needs cleanups" bit regardless of whether there are
5611 // any explicit objects.
5612 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5613 // Append all the objects to the cleanup list. Right now, this
5614 // should always be a no-op, because blocks in default argument
5615 // expressions should never be able to capture anything.
5616 assert(!InitWithCleanup->getNumObjects() &&
5617 "default argument expression has capturing blocks?");
5618 }
5619 // C++ [expr.const]p15.1:
5620 // An expression or conversion is in an immediate function context if it is
5621 // potentially evaluated and [...] its innermost enclosing non-block scope
5622 // is a function parameter scope of an immediate function.
5624 *this,
5628 Param);
5629 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5630 SkipImmediateInvocations;
5631 runWithSufficientStackSpace(CallLoc, [&] {
5632 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5633 });
5634 return false;
5635}
5636
5641 }
5642
5643 bool HasImmediateCalls = false;
5644
5645 bool VisitCallExpr(CallExpr *E) override {
5646 if (const FunctionDecl *FD = E->getDirectCallee())
5647 HasImmediateCalls |= FD->isImmediateFunction();
5649 }
5650
5652 if (const FunctionDecl *FD = E->getConstructor())
5653 HasImmediateCalls |= FD->isImmediateFunction();
5655 }
5656
5657 // SourceLocExpr are not immediate invocations
5658 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5659 // need to be rebuilt so that they refer to the correct SourceLocation and
5660 // DeclContext.
5662 HasImmediateCalls = true;
5664 }
5665
5666 // A nested lambda might have parameters with immediate invocations
5667 // in their default arguments.
5668 // The compound statement is not visited (as it does not constitute a
5669 // subexpression).
5670 // FIXME: We should consider visiting and transforming captures
5671 // with init expressions.
5672 bool VisitLambdaExpr(LambdaExpr *E) override {
5673 return VisitCXXMethodDecl(E->getCallOperator());
5674 }
5675
5677 return TraverseStmt(E->getExpr());
5678 }
5679
5681 return TraverseStmt(E->getExpr());
5682 }
5683};
5684
5686 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5689
5690 bool AlwaysRebuild() { return true; }
5691
5692 // Lambda can only have immediate invocations in the default
5693 // args of their parameters, which is transformed upon calling the closure.
5694 // The body is not a subexpression, so we have nothing to do.
5695 // FIXME: Immediate calls in capture initializers should be transformed.
5698
5699 // Make sure we don't rebuild the this pointer as it would
5700 // cause it to incorrectly point it to the outermost class
5701 // in the case of nested struct initialization.
5703
5704 // Rewrite to source location to refer to the context in which they are used.
5706 DeclContext *DC = E->getParentContext();
5707 if (DC == SemaRef.CurContext)
5708 return E;
5709
5710 // FIXME: During instantiation, because the rebuild of defaults arguments
5711 // is not always done in the context of the template instantiator,
5712 // we run the risk of producing a dependent source location
5713 // that would never be rebuilt.
5714 // This usually happens during overload resolution, or in contexts
5715 // where the value of the source location does not matter.
5716 // However, we should find a better way to deal with source location
5717 // of function templates.
5718 if (!SemaRef.CurrentInstantiationScope ||
5719 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5720 DC = SemaRef.CurContext;
5721
5722 return getDerived().RebuildSourceLocExpr(
5723 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5724 }
5725};
5726
5728 FunctionDecl *FD, ParmVarDecl *Param,
5729 Expr *Init) {
5730 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5731
5732 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5733 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5734 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5735 InitializationContext =
5737 if (!InitializationContext.has_value())
5738 InitializationContext.emplace(CallLoc, Param, CurContext);
5739
5740 if (!Init && !Param->hasUnparsedDefaultArg()) {
5741 // Mark that we are replacing a default argument first.
5742 // If we are instantiating a template we won't have to
5743 // retransform immediate calls.
5744 // C++ [expr.const]p15.1:
5745 // An expression or conversion is in an immediate function context if it
5746 // is potentially evaluated and [...] its innermost enclosing non-block
5747 // scope is a function parameter scope of an immediate function.
5749 *this,
5753 Param);
5754
5755 if (Param->hasUninstantiatedDefaultArg()) {
5756 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5757 return ExprError();
5758 }
5759 // CWG2631
5760 // An immediate invocation that is not evaluated where it appears is
5761 // evaluated and checked for whether it is a constant expression at the
5762 // point where the enclosing initializer is used in a function call.
5764 if (!NestedDefaultChecking)
5765 V.TraverseDecl(Param);
5766
5767 // Rewrite the call argument that was created from the corresponding
5768 // parameter's default argument.
5769 if (V.HasImmediateCalls ||
5770 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5771 if (V.HasImmediateCalls)
5772 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5773 CallLoc, Param, CurContext};
5774 // Pass down lifetime extending flag, and collect temporaries in
5775 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5779 ExprResult Res;
5780 runWithSufficientStackSpace(CallLoc, [&] {
5781 Res = Immediate.TransformInitializer(Param->getInit(),
5782 /*NotCopy=*/false);
5783 });
5784 if (Res.isInvalid())
5785 return ExprError();
5786 Res = ConvertParamDefaultArgument(Param, Res.get(),
5787 Res.get()->getBeginLoc());
5788 if (Res.isInvalid())
5789 return ExprError();
5790 Init = Res.get();
5791 }
5792 }
5793
5795 CallLoc, FD, Param, Init,
5796 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5797 return ExprError();
5798
5799 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5800 Init, InitializationContext->Context);
5801}
5802
5804 FieldDecl *Field) {
5805 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5806 return Pattern;
5807 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5808 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5810 ClassPattern->lookup(Field->getDeclName());
5811 auto Rng = llvm::make_filter_range(
5812 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5813 if (Rng.empty())
5814 return nullptr;
5815 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5816 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5817 // && "Duplicated instantiation pattern for field decl");
5818 return cast<FieldDecl>(*Rng.begin());
5819}
5820
5822 assert(Field->hasInClassInitializer());
5823
5824 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5825
5826 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5827
5828 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5829 InitializationContext =
5831 if (!InitializationContext.has_value())
5832 InitializationContext.emplace(Loc, Field, CurContext);
5833
5834 Expr *Init = nullptr;
5835
5836 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5837 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5840
5841 if (!Field->getInClassInitializer()) {
5842 // Maybe we haven't instantiated the in-class initializer. Go check the
5843 // pattern FieldDecl to see if it has one.
5844 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5845 FieldDecl *Pattern =
5847 assert(Pattern && "We must have set the Pattern!");
5848 if (!Pattern->hasInClassInitializer() ||
5849 InstantiateInClassInitializer(Loc, Field, Pattern,
5851 Field->setInvalidDecl();
5852 return ExprError();
5853 }
5854 }
5855 }
5856
5857 // CWG2631
5858 // An immediate invocation that is not evaluated where it appears is
5859 // evaluated and checked for whether it is a constant expression at the
5860 // point where the enclosing initializer is used in a [...] a constructor
5861 // definition, or an aggregate initialization.
5863 if (!NestedDefaultChecking)
5864 V.TraverseDecl(Field);
5865
5866 // CWG1815
5867 // Support lifetime extension of temporary created by aggregate
5868 // initialization using a default member initializer. We should rebuild
5869 // the initializer in a lifetime extension context if the initializer
5870 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5871 // extension code recurses into the default initializer and does lifetime
5872 // extension when warranted.
5873 bool ContainsAnyTemporaries =
5874 isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());
5875 if (Field->getInClassInitializer() &&
5876 !Field->getInClassInitializer()->containsErrors() &&
5877 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5878 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5879 CurContext};
5880 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5881 NestedDefaultChecking;
5882 // Pass down lifetime extending flag, and collect temporaries in
5883 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5887 ExprResult Res;
5889 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5890 /*CXXDirectInit=*/false);
5891 });
5892 if (!Res.isInvalid())
5893 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5894 if (Res.isInvalid()) {
5895 Field->setInvalidDecl();
5896 return ExprError();
5897 }
5898 Init = Res.get();
5899 }
5900
5901 if (Field->getInClassInitializer()) {
5902 Expr *E = Init ? Init : Field->getInClassInitializer();
5903 if (!NestedDefaultChecking)
5905 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5906 });
5909 // C++11 [class.base.init]p7:
5910 // The initialization of each base and member constitutes a
5911 // full-expression.
5912 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5913 if (Res.isInvalid()) {
5914 Field->setInvalidDecl();
5915 return ExprError();
5916 }
5917 Init = Res.get();
5918
5919 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5920 Field, InitializationContext->Context,
5921 Init);
5922 }
5923
5924 // DR1351:
5925 // If the brace-or-equal-initializer of a non-static data member
5926 // invokes a defaulted default constructor of its class or of an
5927 // enclosing class in a potentially evaluated subexpression, the
5928 // program is ill-formed.
5929 //
5930 // This resolution is unworkable: the exception specification of the
5931 // default constructor can be needed in an unevaluated context, in
5932 // particular, in the operand of a noexcept-expression, and we can be
5933 // unable to compute an exception specification for an enclosed class.
5934 //
5935 // Any attempt to resolve the exception specification of a defaulted default
5936 // constructor before the initializer is lexically complete will ultimately
5937 // come here at which point we can diagnose it.
5938 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5939 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5940 << OutermostClass << Field;
5941 Diag(Field->getEndLoc(),
5942 diag::note_default_member_initializer_not_yet_parsed);
5943 // Recover by marking the field invalid, unless we're in a SFINAE context.
5944 if (!isSFINAEContext())
5945 Field->setInvalidDecl();
5946 return ExprError();
5947}
5948
5950 const FunctionProtoType *Proto,
5951 Expr *Fn) {
5952 if (Proto && Proto->isVariadic()) {
5953 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5955 else if (Fn && Fn->getType()->isBlockPointerType())
5957 else if (FDecl) {
5958 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5959 if (Method->isInstance())
5961 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5964 }
5966}
5967
5968namespace {
5969class FunctionCallCCC final : public FunctionCallFilterCCC {
5970public:
5971 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5972 unsigned NumArgs, MemberExpr *ME)
5973 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5974 FunctionName(FuncName) {}
5975
5976 bool ValidateCandidate(const TypoCorrection &candidate) override {
5977 if (!candidate.getCorrectionSpecifier() ||
5978 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5979 return false;
5980 }
5981
5983 }
5984
5985 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5986 return std::make_unique<FunctionCallCCC>(*this);
5987 }
5988
5989private:
5990 const IdentifierInfo *const FunctionName;
5991};
5992}
5993
5995 FunctionDecl *FDecl,
5996 ArrayRef<Expr *> Args) {
5997 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5998 DeclarationName FuncName = FDecl->getDeclName();
5999 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6000
6001 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6002 if (TypoCorrection Corrected = S.CorrectTypo(
6004 S.getScopeForContext(S.CurContext), nullptr, CCC,
6006 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6007 if (Corrected.isOverloaded()) {
6010 for (NamedDecl *CD : Corrected) {
6011 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6013 OCS);
6014 }
6015 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6016 case OR_Success:
6017 ND = Best->FoundDecl;
6018 Corrected.setCorrectionDecl(ND);
6019 break;
6020 default:
6021 break;
6022 }
6023 }
6024 ND = ND->getUnderlyingDecl();
6026 return Corrected;
6027 }
6028 }
6029 return TypoCorrection();
6030}
6031
6032// [C++26][[expr.unary.op]/p4
6033// A pointer to member is only formed when an explicit &
6034// is used and its operand is a qualified-id not enclosed in parentheses.
6036 if (!isa<ParenExpr>(Fn))
6037 return false;
6038
6039 Fn = Fn->IgnoreParens();
6040
6041 auto *UO = dyn_cast<UnaryOperator>(Fn);
6042 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6043 return false;
6044 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
6045 return DRE->hasQualifier();
6046 }
6047 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
6048 return bool(OVL->getQualifier());
6049 return false;
6050}
6051
6052bool
6054 FunctionDecl *FDecl,
6055 const FunctionProtoType *Proto,
6056 ArrayRef<Expr *> Args,
6057 SourceLocation RParenLoc,
6058 bool IsExecConfig) {
6059 // Bail out early if calling a builtin with custom typechecking.
6060 if (FDecl)
6061 if (unsigned ID = FDecl->getBuiltinID())
6062 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
6063 return false;
6064
6065 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6066 // assignment, to the types of the corresponding parameter, ...
6067
6068 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6069 bool HasExplicitObjectParameter =
6070 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6071 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6072 unsigned NumParams = Proto->getNumParams();
6073 bool Invalid = false;
6074 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6075 unsigned FnKind = Fn->getType()->isBlockPointerType()
6076 ? 1 /* block */
6077 : (IsExecConfig ? 3 /* kernel function (exec config) */
6078 : 0 /* function */);
6079
6080 // If too few arguments are available (and we don't have default
6081 // arguments for the remaining parameters), don't make the call.
6082 if (Args.size() < NumParams) {
6083 if (Args.size() < MinArgs) {
6084 TypoCorrection TC;
6085 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6086 unsigned diag_id =
6087 MinArgs == NumParams && !Proto->isVariadic()
6088 ? diag::err_typecheck_call_too_few_args_suggest
6089 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6091 TC, PDiag(diag_id)
6092 << FnKind << MinArgs - ExplicitObjectParameterOffset
6093 << static_cast<unsigned>(Args.size()) -
6094 ExplicitObjectParameterOffset
6095 << HasExplicitObjectParameter << TC.getCorrectionRange());
6096 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6097 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6098 ->getDeclName())
6099 Diag(RParenLoc,
6100 MinArgs == NumParams && !Proto->isVariadic()
6101 ? diag::err_typecheck_call_too_few_args_one
6102 : diag::err_typecheck_call_too_few_args_at_least_one)
6103 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6104 << HasExplicitObjectParameter << Fn->getSourceRange();
6105 else
6106 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6107 ? diag::err_typecheck_call_too_few_args
6108 : diag::err_typecheck_call_too_few_args_at_least)
6109 << FnKind << MinArgs - ExplicitObjectParameterOffset
6110 << static_cast<unsigned>(Args.size()) -
6111 ExplicitObjectParameterOffset
6112 << HasExplicitObjectParameter << Fn->getSourceRange();
6113
6114 // Emit the location of the prototype.
6115 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6116 Diag(FDecl->getLocation(), diag::note_callee_decl)
6117 << FDecl << FDecl->getParametersSourceRange();
6118
6119 return true;
6120 }
6121 // We reserve space for the default arguments when we create
6122 // the call expression, before calling ConvertArgumentsForCall.
6123 assert((Call->getNumArgs() == NumParams) &&
6124 "We should have reserved space for the default arguments before!");
6125 }
6126
6127 // If too many are passed and not variadic, error on the extras and drop
6128 // them.
6129 if (Args.size() > NumParams) {
6130 if (!Proto->isVariadic()) {
6131 TypoCorrection TC;
6132 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6133 unsigned diag_id =
6134 MinArgs == NumParams && !Proto->isVariadic()
6135 ? diag::err_typecheck_call_too_many_args_suggest
6136 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6138 TC, PDiag(diag_id)
6139 << FnKind << NumParams - ExplicitObjectParameterOffset
6140 << static_cast<unsigned>(Args.size()) -
6141 ExplicitObjectParameterOffset
6142 << HasExplicitObjectParameter << TC.getCorrectionRange());
6143 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6144 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6145 ->getDeclName())
6146 Diag(Args[NumParams]->getBeginLoc(),
6147 MinArgs == NumParams
6148 ? diag::err_typecheck_call_too_many_args_one
6149 : diag::err_typecheck_call_too_many_args_at_most_one)
6150 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6151 << static_cast<unsigned>(Args.size()) -
6152 ExplicitObjectParameterOffset
6153 << HasExplicitObjectParameter << Fn->getSourceRange()
6154 << SourceRange(Args[NumParams]->getBeginLoc(),
6155 Args.back()->getEndLoc());
6156 else
6157 Diag(Args[NumParams]->getBeginLoc(),
6158 MinArgs == NumParams
6159 ? diag::err_typecheck_call_too_many_args
6160 : diag::err_typecheck_call_too_many_args_at_most)
6161 << FnKind << NumParams - ExplicitObjectParameterOffset
6162 << static_cast<unsigned>(Args.size()) -
6163 ExplicitObjectParameterOffset
6164 << HasExplicitObjectParameter << Fn->getSourceRange()
6165 << SourceRange(Args[NumParams]->getBeginLoc(),
6166 Args.back()->getEndLoc());
6167
6168 // Emit the location of the prototype.
6169 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6170 Diag(FDecl->getLocation(), diag::note_callee_decl)
6171 << FDecl << FDecl->getParametersSourceRange();
6172
6173 // This deletes the extra arguments.
6174 Call->shrinkNumArgs(NumParams);
6175 return true;
6176 }
6177 }
6178 SmallVector<Expr *, 8> AllArgs;
6179 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6180
6181 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
6182 AllArgs, CallType);
6183 if (Invalid)
6184 return true;
6185 unsigned TotalNumArgs = AllArgs.size();
6186 for (unsigned i = 0; i < TotalNumArgs; ++i)
6187 Call->setArg(i, AllArgs[i]);
6188
6189 Call->computeDependence();
6190 return false;
6191}
6192
6194 const FunctionProtoType *Proto,
6195 unsigned FirstParam, ArrayRef<Expr *> Args,
6196 SmallVectorImpl<Expr *> &AllArgs,
6197 VariadicCallType CallType, bool AllowExplicit,
6198 bool IsListInitialization) {
6199 unsigned NumParams = Proto->getNumParams();
6200 bool Invalid = false;
6201 size_t ArgIx = 0;
6202 // Continue to check argument types (even if we have too few/many args).
6203 for (unsigned i = FirstParam; i < NumParams; i++) {
6204 QualType ProtoArgType = Proto->getParamType(i);
6205
6206 Expr *Arg;
6207 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6208 if (ArgIx < Args.size()) {
6209 Arg = Args[ArgIx++];
6210
6211 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6212 diag::err_call_incomplete_argument, Arg))
6213 return true;
6214
6215 // Strip the unbridged-cast placeholder expression off, if applicable.
6216 bool CFAudited = false;
6217 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6218 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6219 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6220 Arg = ObjC().stripARCUnbridgedCast(Arg);
6221 else if (getLangOpts().ObjCAutoRefCount &&
6222 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6223 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6224 CFAudited = true;
6225
6226 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6227 ProtoArgType->isBlockPointerType())
6228 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6229 BE->getBlockDecl()->setDoesNotEscape();
6230 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
6232 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6233 if (ArgExpr.isInvalid())
6234 return true;
6235 Arg = ArgExpr.getAs<Expr>();
6236 }
6237
6238 InitializedEntity Entity =
6240 ProtoArgType)
6242 Context, ProtoArgType, Proto->isParamConsumed(i));
6243
6244 // Remember that parameter belongs to a CF audited API.
6245 if (CFAudited)
6246 Entity.setParameterCFAudited();
6247
6248 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6249 // function boundaries is a common oversight.
6250 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6251 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6252 bool isPedantic =
6253 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6254 Diag(Arg->getExprLoc(),
6255 isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6256 : diag::warn_obt_discarded_at_function_boundary)
6257 << Arg->getType() << ProtoArgType;
6258 }
6259
6261 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6262 if (ArgE.isInvalid())
6263 return true;
6264
6265 Arg = ArgE.getAs<Expr>();
6266 } else {
6267 assert(Param && "can't use default arguments without a known callee");
6268
6269 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6270 if (ArgExpr.isInvalid())
6271 return true;
6272
6273 Arg = ArgExpr.getAs<Expr>();
6274 }
6275
6276 // Check for array bounds violations for each argument to the call. This
6277 // check only triggers warnings when the argument isn't a more complex Expr
6278 // with its own checking, such as a BinaryOperator.
6279 CheckArrayAccess(Arg);
6280
6281 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6282 CheckStaticArrayArgument(CallLoc, Param, Arg);
6283
6284 AllArgs.push_back(Arg);
6285 }
6286
6287 // If this is a variadic call, handle args passed through "...".
6288 if (CallType != VariadicCallType::DoesNotApply) {
6289 // Assume that extern "C" functions with variadic arguments that
6290 // return __unknown_anytype aren't *really* variadic.
6291 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6292 FDecl->isExternC()) {
6293 for (Expr *A : Args.slice(ArgIx)) {
6294 QualType paramType; // ignored
6295 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6296 Invalid |= arg.isInvalid();
6297 AllArgs.push_back(arg.get());
6298 }
6299
6300 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6301 } else {
6302 for (Expr *A : Args.slice(ArgIx)) {
6303 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6304 Invalid |= Arg.isInvalid();
6305 AllArgs.push_back(Arg.get());
6306 }
6307 }
6308
6309 // Check for array bounds violations.
6310 for (Expr *A : Args.slice(ArgIx))
6311 CheckArrayAccess(A);
6312 }
6313 return Invalid;
6314}
6315
6317 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6318 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6319 TL = DTL.getOriginalLoc();
6320 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6321 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6322 << ATL.getLocalSourceRange();
6323}
6324
6325void
6327 ParmVarDecl *Param,
6328 const Expr *ArgExpr) {
6329 // Static array parameters are not supported in C++.
6330 if (!Param || getLangOpts().CPlusPlus)
6331 return;
6332
6333 QualType OrigTy = Param->getOriginalType();
6334
6335 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6336 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6337 return;
6338
6339 if (ArgExpr->isNullPointerConstant(Context,
6341 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6342 DiagnoseCalleeStaticArrayParam(*this, Param);
6343 return;
6344 }
6345
6346 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6347 if (!CAT)
6348 return;
6349
6350 const ConstantArrayType *ArgCAT =
6351 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6352 if (!ArgCAT)
6353 return;
6354
6355 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6356 ArgCAT->getElementType())) {
6357 if (ArgCAT->getSize().ult(CAT->getSize())) {
6358 Diag(CallLoc, diag::warn_static_array_too_small)
6359 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6360 << (unsigned)CAT->getZExtSize() << 0;
6361 DiagnoseCalleeStaticArrayParam(*this, Param);
6362 }
6363 return;
6364 }
6365
6366 std::optional<CharUnits> ArgSize =
6368 std::optional<CharUnits> ParmSize =
6370 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6371 Diag(CallLoc, diag::warn_static_array_too_small)
6372 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6373 << (unsigned)ParmSize->getQuantity() << 1;
6374 DiagnoseCalleeStaticArrayParam(*this, Param);
6375 }
6376}
6377
6378/// Given a function expression of unknown-any type, try to rebuild it
6379/// to have a function type.
6381
6382/// Is the given type a placeholder that we need to lower out
6383/// immediately during argument processing?
6385 // Placeholders are never sugared.
6386 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6387 if (!placeholder) return false;
6388
6389 switch (placeholder->getKind()) {
6390 // Ignore all the non-placeholder types.
6391#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6392 case BuiltinType::Id:
6393#include "clang/Basic/OpenCLImageTypes.def"
6394#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6395 case BuiltinType::Id:
6396#include "clang/Basic/OpenCLExtensionTypes.def"
6397 // In practice we'll never use this, since all SVE types are sugared
6398 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6399#define SVE_TYPE(Name, Id, SingletonId) \
6400 case BuiltinType::Id:
6401#include "clang/Basic/AArch64ACLETypes.def"
6402#define PPC_VECTOR_TYPE(Name, Id, Size) \
6403 case BuiltinType::Id:
6404#include "clang/Basic/PPCTypes.def"
6405#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6406#include "clang/Basic/RISCVVTypes.def"
6407#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6408#include "clang/Basic/WebAssemblyReferenceTypes.def"
6409#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6410#include "clang/Basic/AMDGPUTypes.def"
6411#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6412#include "clang/Basic/HLSLIntangibleTypes.def"
6413#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6414#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6415#include "clang/AST/BuiltinTypes.def"
6416 return false;
6417
6418 case BuiltinType::UnresolvedTemplate:
6419 // We cannot lower out overload sets; they might validly be resolved
6420 // by the call machinery.
6421 case BuiltinType::Overload:
6422 return false;
6423
6424 // Unbridged casts in ARC can be handled in some call positions and
6425 // should be left in place.
6426 case BuiltinType::ARCUnbridgedCast:
6427 return false;
6428
6429 // Pseudo-objects should be converted as soon as possible.
6430 case BuiltinType::PseudoObject:
6431 return true;
6432
6433 // The debugger mode could theoretically but currently does not try
6434 // to resolve unknown-typed arguments based on known parameter types.
6435 case BuiltinType::UnknownAny:
6436 return true;
6437
6438 // These are always invalid as call arguments and should be reported.
6439 case BuiltinType::BoundMember:
6440 case BuiltinType::BuiltinFn:
6441 case BuiltinType::IncompleteMatrixIdx:
6442 case BuiltinType::ArraySection:
6443 case BuiltinType::OMPArrayShaping:
6444 case BuiltinType::OMPIterator:
6445 return true;
6446
6447 }
6448 llvm_unreachable("bad builtin type kind");
6449}
6450
6452 // Apply this processing to all the arguments at once instead of
6453 // dying at the first failure.
6454 bool hasInvalid = false;
6455 for (size_t i = 0, e = args.size(); i != e; i++) {
6456 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6457 ExprResult result = CheckPlaceholderExpr(args[i]);
6458 if (result.isInvalid()) hasInvalid = true;
6459 else args[i] = result.get();
6460 }
6461 }
6462 return hasInvalid;
6463}
6464
6465/// If a builtin function has a pointer argument with no explicit address
6466/// space, then it should be able to accept a pointer to any address
6467/// space as input. In order to do this, we need to replace the
6468/// standard builtin declaration with one that uses the same address space
6469/// as the call.
6470///
6471/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6472/// it does not contain any pointer arguments without
6473/// an address space qualifer. Otherwise the rewritten
6474/// FunctionDecl is returned.
6475/// TODO: Handle pointer return types.
6477 FunctionDecl *FDecl,
6478 MultiExprArg ArgExprs) {
6479
6480 QualType DeclType = FDecl->getType();
6481 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6482
6483 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6484 ArgExprs.size() < FT->getNumParams())
6485 return nullptr;
6486
6487 bool NeedsNewDecl = false;
6488 unsigned i = 0;
6489 SmallVector<QualType, 8> OverloadParams;
6490
6491 {
6492 // The lvalue conversions in this loop are only for type resolution and
6493 // don't actually occur.
6496 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6497
6498 for (QualType ParamType : FT->param_types()) {
6499
6500 // Convert array arguments to pointer to simplify type lookup.
6501 ExprResult ArgRes =
6503 if (ArgRes.isInvalid())
6504 return nullptr;
6505 Expr *Arg = ArgRes.get();
6506 QualType ArgType = Arg->getType();
6507 if (!ParamType->isPointerType() ||
6508 ParamType->getPointeeType().hasAddressSpace() ||
6509 !ArgType->isPointerType() ||
6510 !ArgType->getPointeeType().hasAddressSpace() ||
6511 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6512 OverloadParams.push_back(ParamType);
6513 continue;
6514 }
6515
6516 QualType PointeeType = ParamType->getPointeeType();
6517 NeedsNewDecl = true;
6518 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6519
6520 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6521 OverloadParams.push_back(Context.getPointerType(PointeeType));
6522 }
6523 }
6524
6525 if (!NeedsNewDecl)
6526 return nullptr;
6527
6529 EPI.Variadic = FT->isVariadic();
6530 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6531 OverloadParams, EPI);
6532 DeclContext *Parent = FDecl->getParent();
6533 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6534 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6535 FDecl->getIdentifier(), OverloadTy,
6536 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6537 false,
6538 /*hasPrototype=*/true);
6540 FT = cast<FunctionProtoType>(OverloadTy);
6541 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6542 QualType ParamType = FT->getParamType(i);
6543 ParmVarDecl *Parm =
6544 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6545 SourceLocation(), nullptr, ParamType,
6546 /*TInfo=*/nullptr, SC_None, nullptr);
6547 Parm->setScopeInfo(0, i);
6548 Params.push_back(Parm);
6549 }
6550 OverloadDecl->setParams(Params);
6551 // We cannot merge host/device attributes of redeclarations. They have to
6552 // be consistent when created.
6553 if (Sema->LangOpts.CUDA) {
6554 if (FDecl->hasAttr<CUDAHostAttr>())
6555 OverloadDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
6556 if (FDecl->hasAttr<CUDADeviceAttr>())
6557 OverloadDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
6558 }
6559 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6560 return OverloadDecl;
6561}
6562
6563static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6564 FunctionDecl *Callee,
6565 MultiExprArg ArgExprs) {
6566 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6567 // similar attributes) really don't like it when functions are called with an
6568 // invalid number of args.
6569 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6570 /*PartialOverloading=*/false) &&
6571 !Callee->isVariadic())
6572 return;
6573 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6574 return;
6575
6576 if (const EnableIfAttr *Attr =
6577 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6578 S.Diag(Fn->getBeginLoc(),
6579 isa<CXXMethodDecl>(Callee)
6580 ? diag::err_ovl_no_viable_member_function_in_call
6581 : diag::err_ovl_no_viable_function_in_call)
6582 << Callee << Callee->getSourceRange();
6583 S.Diag(Callee->getLocation(),
6584 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6585 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6586 return;
6587 }
6588}
6589
6591 const UnresolvedMemberExpr *const UME, Sema &S) {
6592
6593 const auto GetFunctionLevelDCIfCXXClass =
6594 [](Sema &S) -> const CXXRecordDecl * {
6595 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6596 if (!DC || !DC->getParent())
6597 return nullptr;
6598
6599 // If the call to some member function was made from within a member
6600 // function body 'M' return return 'M's parent.
6601 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6602 return MD->getParent()->getCanonicalDecl();
6603 // else the call was made from within a default member initializer of a
6604 // class, so return the class.
6605 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6606 return RD->getCanonicalDecl();
6607 return nullptr;
6608 };
6609 // If our DeclContext is neither a member function nor a class (in the
6610 // case of a lambda in a default member initializer), we can't have an
6611 // enclosing 'this'.
6612
6613 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6614 if (!CurParentClass)
6615 return false;
6616
6617 // The naming class for implicit member functions call is the class in which
6618 // name lookup starts.
6619 const CXXRecordDecl *const NamingClass =
6621 assert(NamingClass && "Must have naming class even for implicit access");
6622
6623 // If the unresolved member functions were found in a 'naming class' that is
6624 // related (either the same or derived from) to the class that contains the
6625 // member function that itself contained the implicit member access.
6626
6627 return CurParentClass == NamingClass ||
6628 CurParentClass->isDerivedFrom(NamingClass);
6629}
6630
6631static void
6633 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6634
6635 if (!UME)
6636 return;
6637
6638 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6639 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6640 // already been captured, or if this is an implicit member function call (if
6641 // it isn't, an attempt to capture 'this' should already have been made).
6642 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6643 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6644 return;
6645
6646 // Check if the naming class in which the unresolved members were found is
6647 // related (same as or is a base of) to the enclosing class.
6648
6650 return;
6651
6652
6653 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6654 // If the enclosing function is not dependent, then this lambda is
6655 // capture ready, so if we can capture this, do so.
6656 if (!EnclosingFunctionCtx->isDependentContext()) {
6657 // If the current lambda and all enclosing lambdas can capture 'this' -
6658 // then go ahead and capture 'this' (since our unresolved overload set
6659 // contains at least one non-static member function).
6660 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6661 S.CheckCXXThisCapture(CallLoc);
6662 } else if (S.CurContext->isDependentContext()) {
6663 // ... since this is an implicit member reference, that might potentially
6664 // involve a 'this' capture, mark 'this' for potential capture in
6665 // enclosing lambdas.
6666 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6667 CurLSI->addPotentialThisCapture(CallLoc);
6668 }
6669}
6670
6671// Once a call is fully resolved, warn for unqualified calls to specific
6672// C++ standard functions, like move and forward.
6674 const CallExpr *Call) {
6675 // We are only checking unary move and forward so exit early here.
6676 if (Call->getNumArgs() != 1)
6677 return;
6678
6679 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6680 if (!E || isa<UnresolvedLookupExpr>(E))
6681 return;
6682 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6683 if (!DRE || !DRE->getLocation().isValid())
6684 return;
6685
6686 if (DRE->getQualifier())
6687 return;
6688
6689 const FunctionDecl *FD = Call->getDirectCallee();
6690 if (!FD)
6691 return;
6692
6693 // Only warn for some functions deemed more frequent or problematic.
6694 unsigned BuiltinID = FD->getBuiltinID();
6695 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6696 return;
6697
6698 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6700 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6701}
6702
6704 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6705 Expr *ExecConfig) {
6707 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6708 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6709 if (Call.isInvalid())
6710 return Call;
6711
6712 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6713 // language modes.
6714 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6715 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6716 DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id)
6717 << ULE->getName();
6718 }
6719
6720 if (LangOpts.OpenMP)
6721 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6722 ExecConfig);
6723 if (LangOpts.CPlusPlus) {
6724 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6726
6727 // If we previously found that the id-expression of this call refers to a
6728 // consteval function but the call is dependent, we should not treat is an
6729 // an invalid immediate call.
6730 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6731 DRE && Call.get()->isValueDependent()) {
6733 }
6734 }
6735 return Call;
6736}
6737
6738// Any type that could be used to form a callable expression
6739static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6740 QualType T = E->getType();
6741 if (T->isDependentType())
6742 return true;
6743
6744 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6745 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6746 T->isFunctionType() || T->isFunctionReferenceType() ||
6747 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6748 T->isBlockPointerType() || T->isRecordType())
6749 return true;
6750
6753}
6754
6756 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6757 Expr *ExecConfig, bool IsExecConfig,
6758 bool AllowRecovery) {
6759 // Since this might be a postfix expression, get rid of ParenListExprs.
6761 if (Result.isInvalid()) return ExprError();
6762 Fn = Result.get();
6763
6764 if (CheckArgsForPlaceholders(ArgExprs))
6765 return ExprError();
6766
6767 // The result of __builtin_counted_by_ref cannot be used as a function
6768 // argument. It allows leaking and modification of bounds safety information.
6769 for (const Expr *Arg : ArgExprs)
6770 if (CheckInvalidBuiltinCountedByRef(Arg,
6772 return ExprError();
6773
6774 if (getLangOpts().CPlusPlus) {
6775 // If this is a pseudo-destructor expression, build the call immediately.
6777 if (!ArgExprs.empty()) {
6778 // Pseudo-destructor calls should not have any arguments.
6779 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6781 SourceRange(ArgExprs.front()->getBeginLoc(),
6782 ArgExprs.back()->getEndLoc()));
6783 }
6784
6785 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6786 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6787 }
6788 if (Fn->getType() == Context.PseudoObjectTy) {
6789 ExprResult result = CheckPlaceholderExpr(Fn);
6790 if (result.isInvalid()) return ExprError();
6791 Fn = result.get();
6792 }
6793
6794 // Determine whether this is a dependent call inside a C++ template,
6795 // in which case we won't do any semantic analysis now.
6796 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6797 if (ExecConfig) {
6799 cast<CallExpr>(ExecConfig), ArgExprs,
6800 Context.DependentTy, VK_PRValue,
6801 RParenLoc, CurFPFeatureOverrides());
6802 } else {
6803
6805 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6806 Fn->getBeginLoc());
6807
6808 // If the type of the function itself is not dependent
6809 // check that it is a reasonable as a function, as type deduction
6810 // later assume the CallExpr has a sensible TYPE.
6811 if (!MayBeFunctionType(Context, Fn))
6812 return ExprError(
6813 Diag(LParenLoc, diag::err_typecheck_call_not_function)
6814 << Fn->getType() << Fn->getSourceRange());
6815
6816 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6817 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6818 }
6819 }
6820
6821 // Determine whether this is a call to an object (C++ [over.call.object]).
6822 if (Fn->getType()->isRecordType())
6823 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6824 RParenLoc);
6825
6826 if (Fn->getType() == Context.UnknownAnyTy) {
6827 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6828 if (result.isInvalid()) return ExprError();
6829 Fn = result.get();
6830 }
6831
6832 if (Fn->getType() == Context.BoundMemberTy) {
6833 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6834 RParenLoc, ExecConfig, IsExecConfig,
6835 AllowRecovery);
6836 }
6837 }
6838
6839 // Check for overloaded calls. This can happen even in C due to extensions.
6840 if (Fn->getType() == Context.OverloadTy) {
6842
6843 // We aren't supposed to apply this logic if there's an '&' involved.
6846 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6847 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6848 OverloadExpr *ovl = find.Expression;
6849 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6851 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6852 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6853 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6854 RParenLoc, ExecConfig, IsExecConfig,
6855 AllowRecovery);
6856 }
6857 }
6858
6859 // If we're directly calling a function, get the appropriate declaration.
6860 if (Fn->getType() == Context.UnknownAnyTy) {
6861 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6862 if (result.isInvalid()) return ExprError();
6863 Fn = result.get();
6864 }
6865
6866 Expr *NakedFn = Fn->IgnoreParens();
6867
6868 bool CallingNDeclIndirectly = false;
6869 NamedDecl *NDecl = nullptr;
6870 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6871 if (UnOp->getOpcode() == UO_AddrOf) {
6872 CallingNDeclIndirectly = true;
6873 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6874 }
6875 }
6876
6877 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6878 NDecl = DRE->getDecl();
6879
6880 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6881 if (FDecl && FDecl->getBuiltinID()) {
6882 // Rewrite the function decl for this builtin by replacing parameters
6883 // with no explicit address space with the address space of the arguments
6884 // in ArgExprs.
6885 if ((FDecl =
6886 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6887 NDecl = FDecl;
6889 Context, DRE->getQualifierLoc(), SourceLocation(), FDecl, false,
6890 SourceLocation(), Fn->getType() /* BuiltinFnTy */,
6891 Fn->getValueKind(), FDecl, nullptr, DRE->isNonOdrUse());
6892 }
6893 }
6894 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6895 NDecl = ME->getMemberDecl();
6896
6897 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6898 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6899 FD, /*Complain=*/true, Fn->getBeginLoc()))
6900 return ExprError();
6901
6902 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6903
6904 // If this expression is a call to a builtin function in HIP compilation,
6905 // allow a pointer-type argument to default address space to be passed as a
6906 // pointer-type parameter to a non-default address space. If Arg is declared
6907 // in the default address space and Param is declared in a non-default
6908 // address space, perform an implicit address space cast to the parameter
6909 // type.
6910 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
6911 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6912 ++Idx) {
6913 ParmVarDecl *Param = FD->getParamDecl(Idx);
6914 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6915 !ArgExprs[Idx]->getType()->isPointerType())
6916 continue;
6917
6918 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6919 auto ArgTy = ArgExprs[Idx]->getType();
6920 auto ArgPtTy = ArgTy->getPointeeType();
6921 auto ArgAS = ArgPtTy.getAddressSpace();
6922
6923 // Add address space cast if target address spaces are different
6924 bool NeedImplicitASC =
6925 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6926 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6927 // or from specific AS which has target AS matching that of Param.
6929 if (!NeedImplicitASC)
6930 continue;
6931
6932 // First, ensure that the Arg is an RValue.
6933 if (ArgExprs[Idx]->isGLValue()) {
6934 ExprResult Res = DefaultLvalueConversion(ArgExprs[Idx]);
6935 if (Res.isInvalid())
6936 return ExprError();
6937 ArgExprs[Idx] = Res.get();
6938 }
6939
6940 // Construct a new arg type with address space of Param
6941 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6942 ArgPtQuals.setAddressSpace(ParamAS);
6943 auto NewArgPtTy =
6944 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6945 auto NewArgTy =
6946 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
6947 ArgTy.getQualifiers());
6948
6949 // Finally perform an implicit address space cast
6950 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6951 CK_AddressSpaceConversion)
6952 .get();
6953 }
6954 }
6955 }
6956
6957 if (Context.isDependenceAllowed() &&
6958 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6959 assert(!getLangOpts().CPlusPlus);
6960 assert((Fn->containsErrors() ||
6961 llvm::any_of(ArgExprs,
6962 [](clang::Expr *E) { return E->containsErrors(); })) &&
6963 "should only occur in error-recovery path.");
6964 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6965 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6966 }
6967 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6968 ExecConfig, IsExecConfig);
6969}
6970
6972 MultiExprArg CallArgs) {
6973 std::string Name = Context.BuiltinInfo.getName(Id);
6974 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6976 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6977
6978 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6979 assert(BuiltInDecl && "failed to find builtin declaration");
6980
6981 ExprResult DeclRef =
6982 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6983 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6984
6986 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6987
6988 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6989 return Call.get();
6990}
6991
6993 SourceLocation BuiltinLoc,
6994 SourceLocation RParenLoc) {
6995 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6996 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6997}
6998
7000 SourceLocation BuiltinLoc,
7001 SourceLocation RParenLoc) {
7004 QualType SrcTy = E->getType();
7005 if (!SrcTy->isDependentType() &&
7006 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7007 return ExprError(
7008 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7009 << DestTy << SrcTy << E->getSourceRange());
7010 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7011}
7012
7014 SourceLocation BuiltinLoc,
7015 SourceLocation RParenLoc) {
7016 TypeSourceInfo *TInfo;
7017 GetTypeFromParser(ParsedDestTy, &TInfo);
7018 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7019}
7020
7022 SourceLocation LParenLoc,
7023 ArrayRef<Expr *> Args,
7024 SourceLocation RParenLoc, Expr *Config,
7025 bool IsExecConfig, ADLCallKind UsesADL) {
7026 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
7027 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7028
7029 auto IsSJLJ = [&] {
7030 switch (BuiltinID) {
7031 case Builtin::BI__builtin_longjmp:
7032 case Builtin::BI__builtin_setjmp:
7033 case Builtin::BI__sigsetjmp:
7034 case Builtin::BI_longjmp:
7035 case Builtin::BI_setjmp:
7036 case Builtin::BIlongjmp:
7037 case Builtin::BIsetjmp:
7038 case Builtin::BIsiglongjmp:
7039 case Builtin::BIsigsetjmp:
7040 return true;
7041 default:
7042 return false;
7043 }
7044 };
7045
7046 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7047 if (!CurrentDefer.empty() && IsSJLJ()) {
7048 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7049 // for more than just blocks (e.g. lambdas, nested classes...).
7050 Scope *DeferParent = CurrentDefer.back().first;
7051 Scope *Block = CurScope->getBlockParent();
7052 if (DeferParent->Contains(*CurScope) &&
7053 (!Block || !DeferParent->Contains(*Block)))
7054 Diag(Fn->getExprLoc(), diag::err_defer_invalid_sjlj) << FDecl;
7055 }
7056
7057 // Functions with 'interrupt' attribute cannot be called directly.
7058 if (FDecl) {
7059 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7060 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7061 return ExprError();
7062 }
7063 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7064 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
7065 return ExprError();
7066 }
7067 }
7068
7069 // X86 interrupt handlers may only call routines with attribute
7070 // no_caller_saved_registers since there is no efficient way to
7071 // save and restore the non-GPR state.
7072 if (auto *Caller = getCurFunctionDecl()) {
7073 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7074 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7075 const TargetInfo &TI = Context.getTargetInfo();
7076 bool HasNonGPRRegisters =
7077 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
7078 if (HasNonGPRRegisters &&
7079 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7080 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
7081 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7082 if (FDecl)
7083 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7084 }
7085 }
7086 }
7087
7088 // Extract the return type from the builtin function pointer type.
7089 QualType ResultTy;
7090 if (BuiltinID)
7091 ResultTy = FDecl->getCallResultType();
7092 else
7093 ResultTy = Context.BoolTy;
7094
7095 // Promote the function operand.
7096 // We special-case function promotion here because we only allow promoting
7097 // builtin functions to function pointers in the callee of a call.
7099 if (BuiltinID &&
7100 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7101 // FIXME Several builtins still have setType in
7102 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7103 // Builtins.td to ensure they are correct before removing setType calls.
7104 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7105 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7106 } else
7108 if (Result.isInvalid())
7109 return ExprError();
7110 Fn = Result.get();
7111
7112 // Check for a valid function type, but only if it is not a builtin which
7113 // requires custom type checking. These will be handled by
7114 // CheckBuiltinFunctionCall below just after creation of the call expression.
7115 const FunctionType *FuncT = nullptr;
7116 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7117 retry:
7118 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7119 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7120 // have type pointer to function".
7121 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7122 if (!FuncT)
7123 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7124 << Fn->getType() << Fn->getSourceRange());
7125 } else if (const BlockPointerType *BPT =
7126 Fn->getType()->getAs<BlockPointerType>()) {
7127 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7128 } else {
7129 // Handle calls to expressions of unknown-any type.
7130 if (Fn->getType() == Context.UnknownAnyTy) {
7131 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7132 if (rewrite.isInvalid())
7133 return ExprError();
7134 Fn = rewrite.get();
7135 goto retry;
7136 }
7137
7138 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7139 << Fn->getType() << Fn->getSourceRange());
7140 }
7141 }
7142
7143 // Get the number of parameters in the function prototype, if any.
7144 // We will allocate space for max(Args.size(), NumParams) arguments
7145 // in the call expression.
7146 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7147 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7148
7149 CallExpr *TheCall;
7150 if (Config) {
7151 assert(UsesADL == ADLCallKind::NotADL &&
7152 "CUDAKernelCallExpr should not use ADL");
7153 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7154 Args, ResultTy, VK_PRValue, RParenLoc,
7155 CurFPFeatureOverrides(), NumParams);
7156 } else {
7157 TheCall =
7158 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7159 CurFPFeatureOverrides(), NumParams, UsesADL);
7160 }
7161
7162 // Bail out early if calling a builtin with custom type checking.
7163 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7164 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7165 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
7166 E = CheckForImmediateInvocation(E, FDecl);
7167 return E;
7168 }
7169
7170 if (getLangOpts().CUDA) {
7171 if (Config) {
7172 // CUDA: Kernel calls must be to global functions
7173 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7174 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7175 << FDecl << Fn->getSourceRange());
7176
7177 // CUDA: Kernel function must have 'void' return type
7178 if (!FuncT->getReturnType()->isVoidType() &&
7179 !FuncT->getReturnType()->getAs<AutoType>() &&
7181 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7182 << Fn->getType() << Fn->getSourceRange());
7183 } else {
7184 // CUDA: Calls to global functions must be configured
7185 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7186 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7187 << FDecl << Fn->getSourceRange());
7188 }
7189 }
7190
7191 // Check for a valid return type
7192 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7193 FDecl))
7194 return ExprError();
7195
7196 // We know the result type of the call, set it.
7197 TheCall->setType(FuncT->getCallResultType(Context));
7199
7200 // WebAssembly tables can't be used as arguments.
7201 if (Context.getTargetInfo().getTriple().isWasm()) {
7202 for (const Expr *Arg : Args) {
7203 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7204 return ExprError(Diag(Arg->getExprLoc(),
7205 diag::err_wasm_table_as_function_parameter));
7206 }
7207 }
7208 }
7209
7210 if (Proto) {
7211 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7212 IsExecConfig))
7213 return ExprError();
7214 } else {
7215 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7216
7217 if (FDecl) {
7218 // Check if we have too few/too many template arguments, based
7219 // on our knowledge of the function definition.
7220 const FunctionDecl *Def = nullptr;
7221 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7222 Proto = Def->getType()->getAs<FunctionProtoType>();
7223 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7224 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7225 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7226 }
7227
7228 // If the function we're calling isn't a function prototype, but we have
7229 // a function prototype from a prior declaratiom, use that prototype.
7230 if (!FDecl->hasPrototype())
7231 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7232 }
7233
7234 // If we still haven't found a prototype to use but there are arguments to
7235 // the call, diagnose this as calling a function without a prototype.
7236 // However, if we found a function declaration, check to see if
7237 // -Wdeprecated-non-prototype was disabled where the function was declared.
7238 // If so, we will silence the diagnostic here on the assumption that this
7239 // interface is intentional and the user knows what they're doing. We will
7240 // also silence the diagnostic if there is a function declaration but it
7241 // was implicitly defined (the user already gets diagnostics about the
7242 // creation of the implicit function declaration, so the additional warning
7243 // is not helpful).
7244 if (!Proto && !Args.empty() &&
7245 (!FDecl || (!FDecl->isImplicit() &&
7246 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7247 FDecl->getLocation()))))
7248 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7249 << (FDecl != nullptr) << FDecl;
7250
7251 // Promote the arguments (C99 6.5.2.2p6).
7252 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7253 Expr *Arg = Args[i];
7254
7255 if (Proto && i < Proto->getNumParams()) {
7257 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7258 ExprResult ArgE =
7260 if (ArgE.isInvalid())
7261 return true;
7262
7263 Arg = ArgE.getAs<Expr>();
7264
7265 } else {
7267
7268 if (ArgE.isInvalid())
7269 return true;
7270
7271 Arg = ArgE.getAs<Expr>();
7272 }
7273
7274 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7275 diag::err_call_incomplete_argument, Arg))
7276 return ExprError();
7277
7278 TheCall->setArg(i, Arg);
7279 }
7280 TheCall->computeDependence();
7281 }
7282
7283 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7284 if (Method->isImplicitObjectMemberFunction())
7285 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7286 << Fn->getSourceRange() << 0);
7287
7288 // Check for sentinels
7289 if (NDecl)
7290 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7291
7292 // Warn for unions passing across security boundary (CMSE).
7293 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7294 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7295 if (const auto *RT =
7296 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7297 if (RT->getDecl()->isOrContainsUnion())
7298 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7299 << 0 << i;
7300 }
7301 }
7302 }
7303
7304 // Do special checking on direct calls to functions.
7305 if (FDecl) {
7306 if (CheckFunctionCall(FDecl, TheCall, Proto))
7307 return ExprError();
7308
7309 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7310
7311 if (BuiltinID)
7312 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7313 } else if (NDecl) {
7314 if (CheckPointerCall(NDecl, TheCall, Proto))
7315 return ExprError();
7316 } else {
7317 if (CheckOtherCall(TheCall, Proto))
7318 return ExprError();
7319 }
7320
7321 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7322}
7323
7326 SourceLocation RParenLoc, Expr *InitExpr) {
7327 assert(Ty && "ActOnCompoundLiteral(): missing type");
7328 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7329
7330 TypeSourceInfo *TInfo;
7331 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7332 if (!TInfo)
7333 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7334
7335 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7336}
7337
7340 SourceLocation RParenLoc, Expr *LiteralExpr) {
7341 QualType literalType = TInfo->getType();
7342
7343 if (literalType->isArrayType()) {
7345 LParenLoc, Context.getBaseElementType(literalType),
7346 diag::err_array_incomplete_or_sizeless_type,
7347 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7348 return ExprError();
7349 if (literalType->isVariableArrayType()) {
7350 // C23 6.7.10p4: An entity of variable length array type shall not be
7351 // initialized except by an empty initializer.
7352 //
7353 // The C extension warnings are issued from ParseBraceInitializer() and
7354 // do not need to be issued here. However, we continue to issue an error
7355 // in the case there are initializers or we are compiling C++. We allow
7356 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7357 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7358 // FIXME: should we allow this construct in C++ when it makes sense to do
7359 // so?
7360 //
7361 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7362 // shall specify an object type or an array of unknown size, but not a
7363 // variable length array type. This seems odd, as it allows 'int a[size] =
7364 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7365 // says, this is what's implemented here for C (except for the extension
7366 // that permits constant foldable size arrays)
7367
7368 auto diagID = LangOpts.CPlusPlus
7369 ? diag::err_variable_object_no_init
7370 : diag::err_compound_literal_with_vla_type;
7371 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7372 diagID))
7373 return ExprError();
7374 }
7375 } else if (!literalType->isDependentType() &&
7376 RequireCompleteType(LParenLoc, literalType,
7377 diag::err_typecheck_decl_incomplete_type,
7378 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7379 return ExprError();
7380
7381 InitializedEntity Entity
7385 SourceRange(LParenLoc, RParenLoc),
7386 /*InitList=*/true);
7387 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7388 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7389 &literalType);
7390 if (Result.isInvalid())
7391 return ExprError();
7392 LiteralExpr = Result.get();
7393
7394 // We treat the compound literal as being at file scope if it's not in a
7395 // function or method body, or within the function's prototype scope. This
7396 // means the following compound literal is not at file scope:
7397 // void func(char *para[(int [1]){ 0 }[0]);
7398 const Scope *S = getCurScope();
7399 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7400 !S->isInCFunctionScope() &&
7401 (!S || !S->isFunctionPrototypeScope());
7402
7403 // In C, compound literals are l-values for some reason.
7404 // For GCC compatibility, in C++, file-scope array compound literals with
7405 // constant initializers are also l-values, and compound literals are
7406 // otherwise prvalues.
7407 //
7408 // (GCC also treats C++ list-initialized file-scope array prvalues with
7409 // constant initializers as l-values, but that's non-conforming, so we don't
7410 // follow it there.)
7411 //
7412 // FIXME: It would be better to handle the lvalue cases as materializing and
7413 // lifetime-extending a temporary object, but our materialized temporaries
7414 // representation only supports lifetime extension from a variable, not "out
7415 // of thin air".
7416 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7417 // is bound to the result of applying array-to-pointer decay to the compound
7418 // literal.
7419 // FIXME: GCC supports compound literals of reference type, which should
7420 // obviously have a value kind derived from the kind of reference involved.
7422 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7423 ? VK_PRValue
7424 : VK_LValue;
7425
7426 // C99 6.5.2.5
7427 // "If the compound literal occurs outside the body of a function, the
7428 // initializer list shall consist of constant expressions."
7429 if (IsFileScope)
7430 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7431 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7432 Expr *Init = ILE->getInit(i);
7433 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7434 !Init->isConstantInitializer(Context, /*IsForRef=*/false)) {
7435 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7436 << Init->getSourceBitField();
7437 return ExprError();
7438 }
7439
7440 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7441 }
7442
7443 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7444 LiteralExpr, IsFileScope);
7445 if (IsFileScope) {
7446 if (!LiteralExpr->isTypeDependent() &&
7447 !LiteralExpr->isValueDependent() &&
7448 !literalType->isDependentType()) // C99 6.5.2.5p3
7449 if (CheckForConstantInitializer(LiteralExpr))
7450 return ExprError();
7451 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7452 literalType.getAddressSpace() != LangAS::Default) {
7453 // Embedded-C extensions to C99 6.5.2.5:
7454 // "If the compound literal occurs inside the body of a function, the
7455 // type name shall not be qualified by an address-space qualifier."
7456 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7457 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7458 return ExprError();
7459 }
7460
7461 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7462 // Compound literals that have automatic storage duration are destroyed at
7463 // the end of the scope in C; in C++, they're just temporaries.
7464
7465 // Emit diagnostics if it is or contains a C union type that is non-trivial
7466 // to destruct.
7471
7472 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7473 if (literalType.isDestructedType()) {
7474 Cleanup.setExprNeedsCleanups(true);
7475 ExprCleanupObjects.push_back(E);
7477 }
7478 }
7479
7482 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7483 E->getInitializer()->getExprLoc());
7484
7485 return MaybeBindToTemporary(E);
7486}
7487
7490 SourceLocation RBraceLoc) {
7491 // Only produce each kind of designated initialization diagnostic once.
7492 SourceLocation FirstDesignator;
7493 bool DiagnosedArrayDesignator = false;
7494 bool DiagnosedNestedDesignator = false;
7495 bool DiagnosedMixedDesignator = false;
7496
7497 // Check that any designated initializers are syntactically valid in the
7498 // current language mode.
7499 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7500 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7501 if (FirstDesignator.isInvalid())
7502 FirstDesignator = DIE->getBeginLoc();
7503
7504 if (!getLangOpts().CPlusPlus)
7505 break;
7506
7507 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7508 DiagnosedNestedDesignator = true;
7509 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7510 << DIE->getDesignatorsSourceRange();
7511 }
7512
7513 for (auto &Desig : DIE->designators()) {
7514 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7515 DiagnosedArrayDesignator = true;
7516 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7517 << Desig.getSourceRange();
7518 }
7519 }
7520
7521 if (!DiagnosedMixedDesignator &&
7522 !isa<DesignatedInitExpr>(InitArgList[0])) {
7523 DiagnosedMixedDesignator = true;
7524 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7525 << DIE->getSourceRange();
7526 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7527 << InitArgList[0]->getSourceRange();
7528 }
7529 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7530 isa<DesignatedInitExpr>(InitArgList[0])) {
7531 DiagnosedMixedDesignator = true;
7532 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7533 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7534 << DIE->getSourceRange();
7535 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7536 << InitArgList[I]->getSourceRange();
7537 }
7538 }
7539
7540 if (FirstDesignator.isValid()) {
7541 // Only diagnose designated initiaization as a C++20 extension if we didn't
7542 // already diagnose use of (non-C++20) C99 designator syntax.
7543 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7544 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7545 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7546 ? diag::warn_cxx17_compat_designated_init
7547 : diag::ext_cxx_designated_init);
7548 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7549 Diag(FirstDesignator, diag::ext_designated_init);
7550 }
7551 }
7552
7553 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7554}
7555
7558 SourceLocation RBraceLoc) {
7559 // Semantic analysis for initializers is done by ActOnDeclarator() and
7560 // CheckInitializer() - it requires knowledge of the object being initialized.
7561
7562 // Immediately handle non-overload placeholders. Overloads can be
7563 // resolved contextually, but everything else here can't.
7564 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7565 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7566 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7567
7568 // Ignore failures; dropping the entire initializer list because
7569 // of one failure would be terrible for indexing/etc.
7570 if (result.isInvalid()) continue;
7571
7572 InitArgList[I] = result.get();
7573 }
7574 }
7575
7576 InitListExpr *E =
7577 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7578 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7579 return E;
7580}
7581
7583 assert(E.get()->getType()->isBlockPointerType());
7584 assert(E.get()->isPRValue());
7585
7586 // Only do this in an r-value context.
7587 if (!getLangOpts().ObjCAutoRefCount) return;
7588
7590 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7591 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7592 Cleanup.setExprNeedsCleanups(true);
7593}
7594
7596 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7597 // Also, callers should have filtered out the invalid cases with
7598 // pointers. Everything else should be possible.
7599
7600 QualType SrcTy = Src.get()->getType();
7601 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7602 return CK_NoOp;
7603
7604 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7606 llvm_unreachable("member pointer type in C");
7607
7608 case Type::STK_CPointer:
7611 switch (DestTy->getScalarTypeKind()) {
7612 case Type::STK_CPointer: {
7613 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7614 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7615 if (SrcAS != DestAS)
7616 return CK_AddressSpaceConversion;
7617 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7618 return CK_NoOp;
7619 return CK_BitCast;
7620 }
7622 return (SrcKind == Type::STK_BlockPointer
7623 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7625 if (SrcKind == Type::STK_ObjCObjectPointer)
7626 return CK_BitCast;
7627 if (SrcKind == Type::STK_CPointer)
7628 return CK_CPointerToObjCPointerCast;
7630 return CK_BlockPointerToObjCPointerCast;
7631 case Type::STK_Bool:
7632 return CK_PointerToBoolean;
7633 case Type::STK_Integral:
7634 return CK_PointerToIntegral;
7635 case Type::STK_Floating:
7640 llvm_unreachable("illegal cast from pointer");
7641 }
7642 llvm_unreachable("Should have returned before this");
7643
7645 switch (DestTy->getScalarTypeKind()) {
7647 return CK_FixedPointCast;
7648 case Type::STK_Bool:
7649 return CK_FixedPointToBoolean;
7650 case Type::STK_Integral:
7651 return CK_FixedPointToIntegral;
7652 case Type::STK_Floating:
7653 return CK_FixedPointToFloating;
7656 Diag(Src.get()->getExprLoc(),
7657 diag::err_unimplemented_conversion_with_fixed_point_type)
7658 << DestTy;
7659 return CK_IntegralCast;
7660 case Type::STK_CPointer:
7664 llvm_unreachable("illegal cast to pointer type");
7665 }
7666 llvm_unreachable("Should have returned before this");
7667
7668 case Type::STK_Bool: // casting from bool is like casting from an integer
7669 case Type::STK_Integral:
7670 switch (DestTy->getScalarTypeKind()) {
7671 case Type::STK_CPointer:
7676 return CK_NullToPointer;
7677 return CK_IntegralToPointer;
7678 case Type::STK_Bool:
7679 return CK_IntegralToBoolean;
7680 case Type::STK_Integral:
7681 return CK_IntegralCast;
7682 case Type::STK_Floating:
7683 return CK_IntegralToFloating;
7685 Src = ImpCastExprToType(Src.get(),
7686 DestTy->castAs<ComplexType>()->getElementType(),
7687 CK_IntegralCast);
7688 return CK_IntegralRealToComplex;
7690 Src = ImpCastExprToType(Src.get(),
7691 DestTy->castAs<ComplexType>()->getElementType(),
7692 CK_IntegralToFloating);
7693 return CK_FloatingRealToComplex;
7695 llvm_unreachable("member pointer type in C");
7697 return CK_IntegralToFixedPoint;
7698 }
7699 llvm_unreachable("Should have returned before this");
7700
7701 case Type::STK_Floating:
7702 switch (DestTy->getScalarTypeKind()) {
7703 case Type::STK_Floating:
7704 return CK_FloatingCast;
7705 case Type::STK_Bool:
7706 return CK_FloatingToBoolean;
7707 case Type::STK_Integral:
7708 return CK_FloatingToIntegral;
7710 Src = ImpCastExprToType(Src.get(),
7711 DestTy->castAs<ComplexType>()->getElementType(),
7712 CK_FloatingCast);
7713 return CK_FloatingRealToComplex;
7715 Src = ImpCastExprToType(Src.get(),
7716 DestTy->castAs<ComplexType>()->getElementType(),
7717 CK_FloatingToIntegral);
7718 return CK_IntegralRealToComplex;
7719 case Type::STK_CPointer:
7722 llvm_unreachable("valid float->pointer cast?");
7724 llvm_unreachable("member pointer type in C");
7726 return CK_FloatingToFixedPoint;
7727 }
7728 llvm_unreachable("Should have returned before this");
7729
7731 switch (DestTy->getScalarTypeKind()) {
7733 return CK_FloatingComplexCast;
7735 return CK_FloatingComplexToIntegralComplex;
7736 case Type::STK_Floating: {
7737 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7738 if (Context.hasSameType(ET, DestTy))
7739 return CK_FloatingComplexToReal;
7740 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7741 return CK_FloatingCast;
7742 }
7743 case Type::STK_Bool:
7744 return CK_FloatingComplexToBoolean;
7745 case Type::STK_Integral:
7746 Src = ImpCastExprToType(Src.get(),
7747 SrcTy->castAs<ComplexType>()->getElementType(),
7748 CK_FloatingComplexToReal);
7749 return CK_FloatingToIntegral;
7750 case Type::STK_CPointer:
7753 llvm_unreachable("valid complex float->pointer cast?");
7755 llvm_unreachable("member pointer type in C");
7757 Diag(Src.get()->getExprLoc(),
7758 diag::err_unimplemented_conversion_with_fixed_point_type)
7759 << SrcTy;
7760 return CK_IntegralCast;
7761 }
7762 llvm_unreachable("Should have returned before this");
7763
7765 switch (DestTy->getScalarTypeKind()) {
7767 return CK_IntegralComplexToFloatingComplex;
7769 return CK_IntegralComplexCast;
7770 case Type::STK_Integral: {
7771 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7772 if (Context.hasSameType(ET, DestTy))
7773 return CK_IntegralComplexToReal;
7774 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7775 return CK_IntegralCast;
7776 }
7777 case Type::STK_Bool:
7778 return CK_IntegralComplexToBoolean;
7779 case Type::STK_Floating:
7780 Src = ImpCastExprToType(Src.get(),
7781 SrcTy->castAs<ComplexType>()->getElementType(),
7782 CK_IntegralComplexToReal);
7783 return CK_IntegralToFloating;
7784 case Type::STK_CPointer:
7787 llvm_unreachable("valid complex int->pointer cast?");
7789 llvm_unreachable("member pointer type in C");
7791 Diag(Src.get()->getExprLoc(),
7792 diag::err_unimplemented_conversion_with_fixed_point_type)
7793 << SrcTy;
7794 return CK_IntegralCast;
7795 }
7796 llvm_unreachable("Should have returned before this");
7797 }
7798
7799 llvm_unreachable("Unhandled scalar cast");
7800}
7801
7802static bool breakDownVectorType(QualType type, uint64_t &len,
7803 QualType &eltType) {
7804 // Vectors are simple.
7805 if (const VectorType *vecType = type->getAs<VectorType>()) {
7806 len = vecType->getNumElements();
7807 eltType = vecType->getElementType();
7808 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7809 return true;
7810 }
7811
7812 // We allow lax conversion to and from non-vector types, but only if
7813 // they're real types (i.e. non-complex, non-pointer scalar types).
7814 if (!type->isRealType()) return false;
7815
7816 len = 1;
7817 eltType = type;
7818 return true;
7819}
7820
7822 assert(srcTy->isVectorType() || destTy->isVectorType());
7823
7824 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7825 if (!FirstType->isSVESizelessBuiltinType())
7826 return false;
7827
7828 const auto *VecTy = SecondType->getAs<VectorType>();
7829 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7830 };
7831
7832 return ValidScalableConversion(srcTy, destTy) ||
7833 ValidScalableConversion(destTy, srcTy);
7834}
7835
7837 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7838 return false;
7839
7840 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7841 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7842
7843 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7844 matSrcType->getNumColumns() == matDestType->getNumColumns();
7845}
7846
7848 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7849
7850 uint64_t SrcLen, DestLen;
7851 QualType SrcEltTy, DestEltTy;
7852 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7853 return false;
7854 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7855 return false;
7856
7857 // ASTContext::getTypeSize will return the size rounded up to a
7858 // power of 2, so instead of using that, we need to use the raw
7859 // element size multiplied by the element count.
7860 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7861 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7862
7863 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7864}
7865
7867 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7868 "expected at least one type to be a vector here");
7869
7870 bool IsSrcTyAltivec =
7871 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7873 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7875 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7877
7878 bool IsDestTyAltivec = DestTy->isVectorType() &&
7879 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7881 (DestTy->castAs<VectorType>()->getVectorKind() ==
7883 (DestTy->castAs<VectorType>()->getVectorKind() ==
7885
7886 return (IsSrcTyAltivec || IsDestTyAltivec);
7887}
7888
7890 assert(destTy->isVectorType() || srcTy->isVectorType());
7891
7892 // Disallow lax conversions between scalars and ExtVectors (these
7893 // conversions are allowed for other vector types because common headers
7894 // depend on them). Most scalar OP ExtVector cases are handled by the
7895 // splat path anyway, which does what we want (convert, not bitcast).
7896 // What this rules out for ExtVectors is crazy things like char4*float.
7897 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7898 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7899
7900 return areVectorTypesSameSize(srcTy, destTy);
7901}
7902
7904 assert(destTy->isVectorType() || srcTy->isVectorType());
7905
7906 switch (Context.getLangOpts().getLaxVectorConversions()) {
7908 return false;
7909
7911 if (!srcTy->isIntegralOrEnumerationType()) {
7912 auto *Vec = srcTy->getAs<VectorType>();
7913 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7914 return false;
7915 }
7916 if (!destTy->isIntegralOrEnumerationType()) {
7917 auto *Vec = destTy->getAs<VectorType>();
7918 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7919 return false;
7920 }
7921 // OK, integer (vector) -> integer (vector) bitcast.
7922 break;
7923
7925 break;
7926 }
7927
7928 return areLaxCompatibleVectorTypes(srcTy, destTy);
7929}
7930
7932 CastKind &Kind) {
7933 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7934 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7935 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7936 << DestTy << SrcTy << R;
7937 }
7938 } else if (SrcTy->isMatrixType()) {
7939 return Diag(R.getBegin(),
7940 diag::err_invalid_conversion_between_matrix_and_type)
7941 << SrcTy << DestTy << R;
7942 } else if (DestTy->isMatrixType()) {
7943 return Diag(R.getBegin(),
7944 diag::err_invalid_conversion_between_matrix_and_type)
7945 << DestTy << SrcTy << R;
7946 }
7947
7948 Kind = CK_MatrixCast;
7949 return false;
7950}
7951
7953 CastKind &Kind) {
7954 assert(VectorTy->isVectorType() && "Not a vector type!");
7955
7956 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7957 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7958 return Diag(R.getBegin(),
7959 Ty->isVectorType() ?
7960 diag::err_invalid_conversion_between_vectors :
7961 diag::err_invalid_conversion_between_vector_and_integer)
7962 << VectorTy << Ty << R;
7963 } else
7964 return Diag(R.getBegin(),
7965 diag::err_invalid_conversion_between_vector_and_scalar)
7966 << VectorTy << Ty << R;
7967
7968 Kind = CK_BitCast;
7969 return false;
7970}
7971
7973 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7974
7975 if (DestElemTy == SplattedExpr->getType())
7976 return SplattedExpr;
7977
7978 assert(DestElemTy->isFloatingType() ||
7979 DestElemTy->isIntegralOrEnumerationType());
7980
7981 CastKind CK;
7982 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7983 // OpenCL requires that we convert `true` boolean expressions to -1, but
7984 // only when splatting vectors.
7985 if (DestElemTy->isFloatingType()) {
7986 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7987 // in two steps: boolean to signed integral, then to floating.
7988 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7989 CK_BooleanToSignedIntegral);
7990 SplattedExpr = CastExprRes.get();
7991 CK = CK_IntegralToFloating;
7992 } else {
7993 CK = CK_BooleanToSignedIntegral;
7994 }
7995 } else {
7996 ExprResult CastExprRes = SplattedExpr;
7997 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7998 if (CastExprRes.isInvalid())
7999 return ExprError();
8000 SplattedExpr = CastExprRes.get();
8001 }
8002 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8003}
8004
8006 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8007
8008 if (DestElemTy == SplattedExpr->getType())
8009 return SplattedExpr;
8010
8011 assert(DestElemTy->isFloatingType() ||
8012 DestElemTy->isIntegralOrEnumerationType());
8013
8014 ExprResult CastExprRes = SplattedExpr;
8015 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
8016 if (CastExprRes.isInvalid())
8017 return ExprError();
8018 SplattedExpr = CastExprRes.get();
8019
8020 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8021}
8022
8024 Expr *CastExpr, CastKind &Kind) {
8025 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8026
8027 QualType SrcTy = CastExpr->getType();
8028
8029 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8030 // an ExtVectorType.
8031 // In OpenCL, casts between vectors of different types are not allowed.
8032 // (See OpenCL 6.2).
8033 if (SrcTy->isVectorType()) {
8034 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8035 (getLangOpts().OpenCL &&
8036 !Context.hasSameUnqualifiedType(DestTy, SrcTy) &&
8037 !Context.areCompatibleVectorTypes(DestTy, SrcTy))) {
8038 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8039 << DestTy << SrcTy << R;
8040 return ExprError();
8041 }
8042 Kind = CK_BitCast;
8043 return CastExpr;
8044 }
8045
8046 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8047 // conversion will take place first from scalar to elt type, and then
8048 // splat from elt type to vector.
8049 if (SrcTy->isPointerType())
8050 return Diag(R.getBegin(),
8051 diag::err_invalid_conversion_between_vector_and_scalar)
8052 << DestTy << SrcTy << R;
8053
8054 Kind = CK_VectorSplat;
8055 return prepareVectorSplat(DestTy, CastExpr);
8056}
8057
8058/// Check that a call to alloc_size function specifies sufficient space for the
8059/// destination type.
8060static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8061 const Expr *E) {
8062 QualType SourceType = E->getType();
8063 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8064 DestType == SourceType)
8065 return;
8066
8067 const auto *CE = dyn_cast<CallExpr>(E->IgnoreParenCasts());
8068 if (!CE)
8069 return;
8070
8071 // Find the total size allocated by the function call.
8072 if (!CE->getCalleeAllocSizeAttr())
8073 return;
8074 std::optional<llvm::APInt> AllocSize =
8075 CE->evaluateBytesReturnedByAllocSizeCall(S.Context);
8076 // Allocations of size zero are permitted as a special case. They are usually
8077 // done intentionally.
8078 if (!AllocSize || AllocSize->isZero())
8079 return;
8080 auto Size = CharUnits::fromQuantity(AllocSize->getZExtValue());
8081
8082 QualType TargetType = DestType->getPointeeType();
8083 // Find the destination size. As a special case function types have size of
8084 // one byte to match the sizeof operator behavior.
8085 auto LhsSize = TargetType->isFunctionType()
8086 ? CharUnits::One()
8087 : S.Context.getTypeSizeInCharsIfKnown(TargetType);
8088 if (LhsSize && Size < LhsSize)
8089 S.Diag(E->getExprLoc(), diag::warn_alloc_size)
8090 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8091}
8092
8095 Declarator &D, ParsedType &Ty,
8096 SourceLocation RParenLoc, Expr *CastExpr) {
8097 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8098 "ActOnCastExpr(): missing type or expr");
8099
8101 if (D.isInvalidType())
8102 return ExprError();
8103
8104 if (getLangOpts().CPlusPlus) {
8105 // Check that there are no default arguments (C++ only).
8107 }
8108
8110
8111 QualType castType = castTInfo->getType();
8112 Ty = CreateParsedType(castType, castTInfo);
8113
8114 bool isVectorLiteral = false;
8115
8116 // Check for an altivec or OpenCL literal,
8117 // i.e. all the elements are integer constants.
8118 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8119 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8120 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8121 && castType->isVectorType() && (PE || PLE)) {
8122 if (PLE && PLE->getNumExprs() == 0) {
8123 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8124 return ExprError();
8125 }
8126 if (PE || PLE->getNumExprs() == 1) {
8127 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8128 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8129 isVectorLiteral = true;
8130 }
8131 else
8132 isVectorLiteral = true;
8133 }
8134
8135 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8136 // then handle it as such.
8137 if (isVectorLiteral)
8138 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8139
8140 // If the Expr being casted is a ParenListExpr, handle it specially.
8141 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8142 // sequence of BinOp comma operators.
8145 if (Result.isInvalid()) return ExprError();
8146 CastExpr = Result.get();
8147 }
8148
8149 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8150 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8151
8153
8155
8157
8158 CheckSufficientAllocSize(*this, castType, CastExpr);
8159
8160 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8161}
8162
8164 SourceLocation RParenLoc, Expr *E,
8165 TypeSourceInfo *TInfo) {
8166 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8167 "Expected paren or paren list expression");
8168
8169 Expr **exprs;
8170 unsigned numExprs;
8171 Expr *subExpr;
8172 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8173 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8174 LiteralLParenLoc = PE->getLParenLoc();
8175 LiteralRParenLoc = PE->getRParenLoc();
8176 exprs = PE->getExprs();
8177 numExprs = PE->getNumExprs();
8178 } else { // isa<ParenExpr> by assertion at function entrance
8179 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8180 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8181 subExpr = cast<ParenExpr>(E)->getSubExpr();
8182 exprs = &subExpr;
8183 numExprs = 1;
8184 }
8185
8186 QualType Ty = TInfo->getType();
8187 assert(Ty->isVectorType() && "Expected vector type");
8188
8189 SmallVector<Expr *, 8> initExprs;
8190 const VectorType *VTy = Ty->castAs<VectorType>();
8191 unsigned numElems = VTy->getNumElements();
8192
8193 // '(...)' form of vector initialization in AltiVec: the number of
8194 // initializers must be one or must match the size of the vector.
8195 // If a single value is specified in the initializer then it will be
8196 // replicated to all the components of the vector
8198 VTy->getElementType()))
8199 return ExprError();
8201 // The number of initializers must be one or must match the size of the
8202 // vector. If a single value is specified in the initializer then it will
8203 // be replicated to all the components of the vector
8204 if (numExprs == 1) {
8205 QualType ElemTy = VTy->getElementType();
8206 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8207 if (Literal.isInvalid())
8208 return ExprError();
8209 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8210 PrepareScalarCast(Literal, ElemTy));
8211 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8212 }
8213 else if (numExprs < numElems) {
8214 Diag(E->getExprLoc(),
8215 diag::err_incorrect_number_of_vector_initializers);
8216 return ExprError();
8217 }
8218 else
8219 initExprs.append(exprs, exprs + numExprs);
8220 }
8221 else {
8222 // For OpenCL, when the number of initializers is a single value,
8223 // it will be replicated to all components of the vector.
8225 numExprs == 1) {
8226 QualType SrcTy = exprs[0]->getType();
8227 if (!SrcTy->isArithmeticType()) {
8228 Diag(exprs[0]->getBeginLoc(), diag::err_typecheck_convert_incompatible)
8229 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8230 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8231 return ExprError();
8232 }
8233 QualType ElemTy = VTy->getElementType();
8234 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8235 if (Literal.isInvalid())
8236 return ExprError();
8237 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8238 PrepareScalarCast(Literal, ElemTy));
8239 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8240 }
8241
8242 initExprs.append(exprs, exprs + numExprs);
8243 }
8244 // FIXME: This means that pretty-printing the final AST will produce curly
8245 // braces instead of the original commas.
8246 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8247 initExprs, LiteralRParenLoc);
8248 initE->setType(Ty);
8249 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8250}
8251
8254 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8255 if (!E)
8256 return OrigExpr;
8257
8258 ExprResult Result(E->getExpr(0));
8259
8260 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8261 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8262 E->getExpr(i));
8263
8264 if (Result.isInvalid()) return ExprError();
8265
8266 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8267}
8268
8274
8276 unsigned NumUserSpecifiedExprs,
8277 SourceLocation InitLoc,
8278 SourceLocation LParenLoc,
8279 SourceLocation RParenLoc) {
8280 return CXXParenListInitExpr::Create(Context, Args, T, NumUserSpecifiedExprs,
8281 InitLoc, LParenLoc, RParenLoc);
8282}
8283
8284bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8285 SourceLocation QuestionLoc) {
8286 const Expr *NullExpr = LHSExpr;
8287 const Expr *NonPointerExpr = RHSExpr;
8291
8292 if (NullKind == Expr::NPCK_NotNull) {
8293 NullExpr = RHSExpr;
8294 NonPointerExpr = LHSExpr;
8295 NullKind =
8298 }
8299
8300 if (NullKind == Expr::NPCK_NotNull)
8301 return false;
8302
8303 if (NullKind == Expr::NPCK_ZeroExpression)
8304 return false;
8305
8306 if (NullKind == Expr::NPCK_ZeroLiteral) {
8307 // In this case, check to make sure that we got here from a "NULL"
8308 // string in the source code.
8309 NullExpr = NullExpr->IgnoreParenImpCasts();
8310 SourceLocation loc = NullExpr->getExprLoc();
8311 if (!findMacroSpelling(loc, "NULL"))
8312 return false;
8313 }
8314
8315 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8316 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8317 << NonPointerExpr->getType() << DiagType
8318 << NonPointerExpr->getSourceRange();
8319 return true;
8320}
8321
8322/// Return false if the condition expression is valid, true otherwise.
8323static bool checkCondition(Sema &S, const Expr *Cond,
8324 SourceLocation QuestionLoc) {
8325 QualType CondTy = Cond->getType();
8326
8327 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8328 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8329 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8330 << CondTy << Cond->getSourceRange();
8331 return true;
8332 }
8333
8334 // C99 6.5.15p2
8335 if (CondTy->isScalarType()) return false;
8336
8337 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8338 << CondTy << Cond->getSourceRange();
8339 return true;
8340}
8341
8342/// Return false if the NullExpr can be promoted to PointerTy,
8343/// true otherwise.
8345 QualType PointerTy) {
8346 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8347 !NullExpr.get()->isNullPointerConstant(S.Context,
8349 return true;
8350
8351 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8352 return false;
8353}
8354
8355/// Checks compatibility between two pointers and return the resulting
8356/// type.
8358 ExprResult &RHS,
8359 SourceLocation Loc) {
8360 QualType LHSTy = LHS.get()->getType();
8361 QualType RHSTy = RHS.get()->getType();
8362
8363 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8364 // Two identical pointers types are always compatible.
8365 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8366 }
8367
8368 QualType lhptee, rhptee;
8369
8370 // Get the pointee types.
8371 bool IsBlockPointer = false;
8372 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8373 lhptee = LHSBTy->getPointeeType();
8374 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8375 IsBlockPointer = true;
8376 } else {
8377 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8378 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8379 }
8380
8381 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8382 // differently qualified versions of compatible types, the result type is
8383 // a pointer to an appropriately qualified version of the composite
8384 // type.
8385
8386 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8387 // clause doesn't make sense for our extensions. E.g. address space 2 should
8388 // be incompatible with address space 3: they may live on different devices or
8389 // anything.
8390 Qualifiers lhQual = lhptee.getQualifiers();
8391 Qualifiers rhQual = rhptee.getQualifiers();
8392
8393 LangAS ResultAddrSpace = LangAS::Default;
8394 LangAS LAddrSpace = lhQual.getAddressSpace();
8395 LangAS RAddrSpace = rhQual.getAddressSpace();
8396
8397 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8398 // spaces is disallowed.
8399 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8400 ResultAddrSpace = LAddrSpace;
8401 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8402 ResultAddrSpace = RAddrSpace;
8403 else {
8404 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8405 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8406 << RHS.get()->getSourceRange();
8407 return QualType();
8408 }
8409
8410 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8411 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8412 lhQual.removeCVRQualifiers();
8413 rhQual.removeCVRQualifiers();
8414
8415 if (!lhQual.getPointerAuth().isEquivalent(rhQual.getPointerAuth())) {
8416 S.Diag(Loc, diag::err_typecheck_cond_incompatible_ptrauth)
8417 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8418 << RHS.get()->getSourceRange();
8419 return QualType();
8420 }
8421
8422 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8423 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8424 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8425 // qual types are compatible iff
8426 // * corresponded types are compatible
8427 // * CVR qualifiers are equal
8428 // * address spaces are equal
8429 // Thus for conditional operator we merge CVR and address space unqualified
8430 // pointees and if there is a composite type we return a pointer to it with
8431 // merged qualifiers.
8432 LHSCastKind =
8433 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8434 RHSCastKind =
8435 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8436 lhQual.removeAddressSpace();
8437 rhQual.removeAddressSpace();
8438
8439 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8440 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8441
8442 QualType CompositeTy = S.Context.mergeTypes(
8443 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8444 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8445
8446 if (CompositeTy.isNull()) {
8447 // In this situation, we assume void* type. No especially good
8448 // reason, but this is what gcc does, and we do have to pick
8449 // to get a consistent AST.
8450 QualType incompatTy;
8451 incompatTy = S.Context.getPointerType(
8452 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8453 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8454 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8455
8456 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8457 // for casts between types with incompatible address space qualifiers.
8458 // For the following code the compiler produces casts between global and
8459 // local address spaces of the corresponded innermost pointees:
8460 // local int *global *a;
8461 // global int *global *b;
8462 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8463 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8464 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8465 << RHS.get()->getSourceRange();
8466
8467 return incompatTy;
8468 }
8469
8470 // The pointer types are compatible.
8471 // In case of OpenCL ResultTy should have the address space qualifier
8472 // which is a superset of address spaces of both the 2nd and the 3rd
8473 // operands of the conditional operator.
8474 QualType ResultTy = [&, ResultAddrSpace]() {
8475 if (S.getLangOpts().OpenCL) {
8476 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8477 CompositeQuals.setAddressSpace(ResultAddrSpace);
8478 return S.Context
8479 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8480 .withCVRQualifiers(MergedCVRQual);
8481 }
8482 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8483 }();
8484 if (IsBlockPointer)
8485 ResultTy = S.Context.getBlockPointerType(ResultTy);
8486 else
8487 ResultTy = S.Context.getPointerType(ResultTy);
8488
8489 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8490 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8491 return ResultTy;
8492}
8493
8494/// Return the resulting type when the operands are both block pointers.
8496 ExprResult &LHS,
8497 ExprResult &RHS,
8498 SourceLocation Loc) {
8499 QualType LHSTy = LHS.get()->getType();
8500 QualType RHSTy = RHS.get()->getType();
8501
8502 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8503 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8505 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8506 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8507 return destType;
8508 }
8509 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8510 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8511 << RHS.get()->getSourceRange();
8512 return QualType();
8513 }
8514
8515 // We have 2 block pointer types.
8516 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8517}
8518
8519/// Return the resulting type when the operands are both pointers.
8520static QualType
8522 ExprResult &RHS,
8523 SourceLocation Loc) {
8524 // get the pointer types
8525 QualType LHSTy = LHS.get()->getType();
8526 QualType RHSTy = RHS.get()->getType();
8527
8528 // get the "pointed to" types
8529 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8530 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8531
8532 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8533 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8534 // Figure out necessary qualifiers (C99 6.5.15p6)
8535 QualType destPointee
8536 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8537 QualType destType = S.Context.getPointerType(destPointee);
8538 // Add qualifiers if necessary.
8539 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8540 // Promote to void*.
8541 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8542 return destType;
8543 }
8544 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8545 QualType destPointee
8546 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8547 QualType destType = S.Context.getPointerType(destPointee);
8548 // Add qualifiers if necessary.
8549 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8550 // Promote to void*.
8551 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8552 return destType;
8553 }
8554
8555 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8556}
8557
8558/// Return false if the first expression is not an integer and the second
8559/// expression is not a pointer, true otherwise.
8561 Expr* PointerExpr, SourceLocation Loc,
8562 bool IsIntFirstExpr) {
8563 if (!PointerExpr->getType()->isPointerType() ||
8564 !Int.get()->getType()->isIntegerType())
8565 return false;
8566
8567 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8568 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8569
8570 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8571 << Expr1->getType() << Expr2->getType()
8572 << Expr1->getSourceRange() << Expr2->getSourceRange();
8573 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8574 CK_IntegralToPointer);
8575 return true;
8576}
8577
8578/// Simple conversion between integer and floating point types.
8579///
8580/// Used when handling the OpenCL conditional operator where the
8581/// condition is a vector while the other operands are scalar.
8582///
8583/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8584/// types are either integer or floating type. Between the two
8585/// operands, the type with the higher rank is defined as the "result
8586/// type". The other operand needs to be promoted to the same type. No
8587/// other type promotion is allowed. We cannot use
8588/// UsualArithmeticConversions() for this purpose, since it always
8589/// promotes promotable types.
8591 ExprResult &RHS,
8592 SourceLocation QuestionLoc) {
8594 if (LHS.isInvalid())
8595 return QualType();
8597 if (RHS.isInvalid())
8598 return QualType();
8599
8600 // For conversion purposes, we ignore any qualifiers.
8601 // For example, "const float" and "float" are equivalent.
8602 QualType LHSType =
8604 QualType RHSType =
8606
8607 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8608 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8609 << LHSType << LHS.get()->getSourceRange();
8610 return QualType();
8611 }
8612
8613 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8614 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8615 << RHSType << RHS.get()->getSourceRange();
8616 return QualType();
8617 }
8618
8619 // If both types are identical, no conversion is needed.
8620 if (LHSType == RHSType)
8621 return LHSType;
8622
8623 // Now handle "real" floating types (i.e. float, double, long double).
8624 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8625 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8626 /*IsCompAssign = */ false);
8627
8628 // Finally, we have two differing integer types.
8630 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8631}
8632
8633/// Convert scalar operands to a vector that matches the
8634/// condition in length.
8635///
8636/// Used when handling the OpenCL conditional operator where the
8637/// condition is a vector while the other operands are scalar.
8638///
8639/// We first compute the "result type" for the scalar operands
8640/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8641/// into a vector of that type where the length matches the condition
8642/// vector type. s6.11.6 requires that the element types of the result
8643/// and the condition must have the same number of bits.
8644static QualType
8646 QualType CondTy, SourceLocation QuestionLoc) {
8647 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8648 if (ResTy.isNull()) return QualType();
8649
8650 const VectorType *CV = CondTy->getAs<VectorType>();
8651 assert(CV);
8652
8653 // Determine the vector result type
8654 unsigned NumElements = CV->getNumElements();
8655 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8656
8657 // Ensure that all types have the same number of bits
8659 != S.Context.getTypeSize(ResTy)) {
8660 // Since VectorTy is created internally, it does not pretty print
8661 // with an OpenCL name. Instead, we just print a description.
8662 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8663 SmallString<64> Str;
8664 llvm::raw_svector_ostream OS(Str);
8665 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8666 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8667 << CondTy << OS.str();
8668 return QualType();
8669 }
8670
8671 // Convert operands to the vector result type
8672 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8673 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8674
8675 return VectorTy;
8676}
8677
8678/// Return false if this is a valid OpenCL condition vector
8680 SourceLocation QuestionLoc) {
8681 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8682 // integral type.
8683 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8684 assert(CondTy);
8685 QualType EleTy = CondTy->getElementType();
8686 if (EleTy->isIntegerType()) return false;
8687
8688 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8689 << Cond->getType() << Cond->getSourceRange();
8690 return true;
8691}
8692
8693/// Return false if the vector condition type and the vector
8694/// result type are compatible.
8695///
8696/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8697/// number of elements, and their element types have the same number
8698/// of bits.
8699static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8700 SourceLocation QuestionLoc) {
8701 const VectorType *CV = CondTy->getAs<VectorType>();
8702 const VectorType *RV = VecResTy->getAs<VectorType>();
8703 assert(CV && RV);
8704
8705 if (CV->getNumElements() != RV->getNumElements()) {
8706 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8707 << CondTy << VecResTy;
8708 return true;
8709 }
8710
8711 QualType CVE = CV->getElementType();
8712 QualType RVE = RV->getElementType();
8713
8714 // Boolean vectors are permitted outside of OpenCL mode.
8715 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE) &&
8716 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8717 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8718 << CondTy << VecResTy;
8719 return true;
8720 }
8721
8722 return false;
8723}
8724
8725/// Return the resulting type for the conditional operator in
8726/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8727/// s6.3.i) when the condition is a vector type.
8728static QualType
8730 ExprResult &LHS, ExprResult &RHS,
8731 SourceLocation QuestionLoc) {
8733 if (Cond.isInvalid())
8734 return QualType();
8735 QualType CondTy = Cond.get()->getType();
8736
8737 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8738 return QualType();
8739
8740 // If either operand is a vector then find the vector type of the
8741 // result as specified in OpenCL v1.1 s6.3.i.
8742 if (LHS.get()->getType()->isVectorType() ||
8743 RHS.get()->getType()->isVectorType()) {
8744 bool IsBoolVecLang =
8745 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8746 QualType VecResTy =
8747 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8748 /*isCompAssign*/ false,
8749 /*AllowBothBool*/ true,
8750 /*AllowBoolConversions*/ false,
8751 /*AllowBooleanOperation*/ IsBoolVecLang,
8752 /*ReportInvalid*/ true);
8753 if (VecResTy.isNull())
8754 return QualType();
8755 // The result type must match the condition type as specified in
8756 // OpenCL v1.1 s6.11.6.
8757 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8758 return QualType();
8759 return VecResTy;
8760 }
8761
8762 // Both operands are scalar.
8763 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8764}
8765
8766/// Return true if the Expr is block type
8767static bool checkBlockType(Sema &S, const Expr *E) {
8768 if (E->getType()->isBlockPointerType()) {
8769 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8770 return true;
8771 }
8772
8773 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8774 QualType Ty = CE->getCallee()->getType();
8775 if (Ty->isBlockPointerType()) {
8776 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8777 return true;
8778 }
8779 }
8780 return false;
8781}
8782
8783/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8784/// In that case, LHS = cond.
8785/// C99 6.5.15
8788 ExprObjectKind &OK,
8789 SourceLocation QuestionLoc) {
8790
8791 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8792 if (!LHSResult.isUsable()) return QualType();
8793 LHS = LHSResult;
8794
8795 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8796 if (!RHSResult.isUsable()) return QualType();
8797 RHS = RHSResult;
8798
8799 // C++ is sufficiently different to merit its own checker.
8800 if (getLangOpts().CPlusPlus)
8801 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8802
8803 VK = VK_PRValue;
8804 OK = OK_Ordinary;
8805
8806 if (Context.isDependenceAllowed() &&
8807 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8808 RHS.get()->isTypeDependent())) {
8809 assert(!getLangOpts().CPlusPlus);
8810 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8811 RHS.get()->containsErrors()) &&
8812 "should only occur in error-recovery path.");
8813 return Context.DependentTy;
8814 }
8815
8816 // The OpenCL operator with a vector condition is sufficiently
8817 // different to merit its own checker.
8818 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8819 Cond.get()->getType()->isExtVectorType())
8820 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8821
8822 // First, check the condition.
8824 if (Cond.isInvalid())
8825 return QualType();
8826 if (checkCondition(*this, Cond.get(), QuestionLoc))
8827 return QualType();
8828
8829 // Handle vectors.
8830 if (LHS.get()->getType()->isVectorType() ||
8831 RHS.get()->getType()->isVectorType())
8832 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8833 /*AllowBothBool*/ true,
8834 /*AllowBoolConversions*/ false,
8835 /*AllowBooleanOperation*/ false,
8836 /*ReportInvalid*/ true);
8837
8838 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
8840 if (LHS.isInvalid() || RHS.isInvalid())
8841 return QualType();
8842
8843 // WebAssembly tables are not allowed as conditional LHS or RHS.
8844 QualType LHSTy = LHS.get()->getType();
8845 QualType RHSTy = RHS.get()->getType();
8846 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8847 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8848 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8849 return QualType();
8850 }
8851
8852 // Diagnose attempts to convert between __ibm128, __float128 and long double
8853 // where such conversions currently can't be handled.
8854 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8855 Diag(QuestionLoc,
8856 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8857 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8858 return QualType();
8859 }
8860
8861 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8862 // selection operator (?:).
8863 if (getLangOpts().OpenCL &&
8864 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8865 return QualType();
8866 }
8867
8868 // If both operands have arithmetic type, do the usual arithmetic conversions
8869 // to find a common type: C99 6.5.15p3,5.
8870 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8871 // Disallow invalid arithmetic conversions, such as those between bit-
8872 // precise integers types of different sizes, or between a bit-precise
8873 // integer and another type.
8874 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8875 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8876 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8877 << RHS.get()->getSourceRange();
8878 return QualType();
8879 }
8880
8881 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8882 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8883
8884 return ResTy;
8885 }
8886
8887 // If both operands are the same structure or union type, the result is that
8888 // type.
8889 // FIXME: Type of conditional expression must be complete in C mode.
8890 if (LHSTy->isRecordType() &&
8891 Context.hasSameUnqualifiedType(LHSTy, RHSTy)) // C99 6.5.15p3
8892 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
8893 RHSTy.getUnqualifiedType());
8894
8895 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8896 // The following || allows only one side to be void (a GCC-ism).
8897 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8898 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8899 // UsualArithmeticConversions already handled the case where both sides
8900 // are the same type.
8901 } else if (RHSTy->isVoidType()) {
8902 ResTy = RHSTy;
8903 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8904 << RHS.get()->getSourceRange();
8905 } else {
8906 ResTy = LHSTy;
8907 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8908 << LHS.get()->getSourceRange();
8909 }
8910 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8911 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8912 return ResTy;
8913 }
8914
8915 // C23 6.5.15p7:
8916 // ... if both the second and third operands have nullptr_t type, the
8917 // result also has that type.
8918 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8919 return ResTy;
8920
8921 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8922 // the type of the other operand."
8923 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8924 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8925
8926 // All objective-c pointer type analysis is done here.
8927 QualType compositeType =
8928 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8929 if (LHS.isInvalid() || RHS.isInvalid())
8930 return QualType();
8931 if (!compositeType.isNull())
8932 return compositeType;
8933
8934
8935 // Handle block pointer types.
8936 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8937 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8938 QuestionLoc);
8939
8940 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8941 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8942 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8943 QuestionLoc);
8944
8945 // GCC compatibility: soften pointer/integer mismatch. Note that
8946 // null pointers have been filtered out by this point.
8947 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8948 /*IsIntFirstExpr=*/true))
8949 return RHSTy;
8950 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8951 /*IsIntFirstExpr=*/false))
8952 return LHSTy;
8953
8954 // Emit a better diagnostic if one of the expressions is a null pointer
8955 // constant and the other is not a pointer type. In this case, the user most
8956 // likely forgot to take the address of the other expression.
8957 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8958 return QualType();
8959
8960 // Finally, if the LHS and RHS types are canonically the same type, we can
8961 // use the common sugared type.
8962 if (Context.hasSameType(LHSTy, RHSTy))
8963 return Context.getCommonSugaredType(LHSTy, RHSTy);
8964
8965 // Otherwise, the operands are not compatible.
8966 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8967 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8968 << RHS.get()->getSourceRange();
8969 return QualType();
8970}
8971
8972/// SuggestParentheses - Emit a note with a fixit hint that wraps
8973/// ParenRange in parentheses.
8975 const PartialDiagnostic &Note,
8976 SourceRange ParenRange) {
8977 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8978 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8979 EndLoc.isValid()) {
8980 Self.Diag(Loc, Note)
8981 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8982 << FixItHint::CreateInsertion(EndLoc, ")");
8983 } else {
8984 // We can't display the parentheses, so just show the bare note.
8985 Self.Diag(Loc, Note) << ParenRange;
8986 }
8987}
8988
8990 return BinaryOperator::isAdditiveOp(Opc) ||
8992 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8993 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8994 // not any of the logical operators. Bitwise-xor is commonly used as a
8995 // logical-xor because there is no logical-xor operator. The logical
8996 // operators, including uses of xor, have a high false positive rate for
8997 // precedence warnings.
8998}
8999
9000/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9001/// expression, either using a built-in or overloaded operator,
9002/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9003/// expression.
9004static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9005 const Expr **RHSExprs) {
9006 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9007 E = E->IgnoreImpCasts();
9009 E = E->IgnoreImpCasts();
9010 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9011 E = MTE->getSubExpr();
9012 E = E->IgnoreImpCasts();
9013 }
9014
9015 // Built-in binary operator.
9016 if (const auto *OP = dyn_cast<BinaryOperator>(E);
9017 OP && IsArithmeticOp(OP->getOpcode())) {
9018 *Opcode = OP->getOpcode();
9019 *RHSExprs = OP->getRHS();
9020 return true;
9021 }
9022
9023 // Overloaded operator.
9024 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9025 if (Call->getNumArgs() != 2)
9026 return false;
9027
9028 // Make sure this is really a binary operator that is safe to pass into
9029 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9030 OverloadedOperatorKind OO = Call->getOperator();
9031 if (OO < OO_Plus || OO > OO_Arrow ||
9032 OO == OO_PlusPlus || OO == OO_MinusMinus)
9033 return false;
9034
9036 if (IsArithmeticOp(OpKind)) {
9037 *Opcode = OpKind;
9038 *RHSExprs = Call->getArg(1);
9039 return true;
9040 }
9041 }
9042
9043 return false;
9044}
9045
9046/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9047/// or is a logical expression such as (x==y) which has int type, but is
9048/// commonly interpreted as boolean.
9049static bool ExprLooksBoolean(const Expr *E) {
9050 E = E->IgnoreParenImpCasts();
9051
9052 if (E->getType()->isBooleanType())
9053 return true;
9054 if (const auto *OP = dyn_cast<BinaryOperator>(E))
9055 return OP->isComparisonOp() || OP->isLogicalOp();
9056 if (const auto *OP = dyn_cast<UnaryOperator>(E))
9057 return OP->getOpcode() == UO_LNot;
9058 if (E->getType()->isPointerType())
9059 return true;
9060 // FIXME: What about overloaded operator calls returning "unspecified boolean
9061 // type"s (commonly pointer-to-members)?
9062
9063 return false;
9064}
9065
9066/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9067/// and binary operator are mixed in a way that suggests the programmer assumed
9068/// the conditional operator has higher precedence, for example:
9069/// "int x = a + someBinaryCondition ? 1 : 2".
9071 Expr *Condition, const Expr *LHSExpr,
9072 const Expr *RHSExpr) {
9073 BinaryOperatorKind CondOpcode;
9074 const Expr *CondRHS;
9075
9076 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9077 return;
9078 if (!ExprLooksBoolean(CondRHS))
9079 return;
9080
9081 // The condition is an arithmetic binary expression, with a right-
9082 // hand side that looks boolean, so warn.
9083
9084 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9085 ? diag::warn_precedence_bitwise_conditional
9086 : diag::warn_precedence_conditional;
9087
9088 Self.Diag(OpLoc, DiagID)
9089 << Condition->getSourceRange()
9090 << BinaryOperator::getOpcodeStr(CondOpcode);
9091
9093 Self, OpLoc,
9094 Self.PDiag(diag::note_precedence_silence)
9095 << BinaryOperator::getOpcodeStr(CondOpcode),
9096 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9097
9098 SuggestParentheses(Self, OpLoc,
9099 Self.PDiag(diag::note_precedence_conditional_first),
9100 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9101}
9102
9103/// Compute the nullability of a conditional expression.
9105 QualType LHSTy, QualType RHSTy,
9106 ASTContext &Ctx) {
9107 if (!ResTy->isAnyPointerType())
9108 return ResTy;
9109
9110 auto GetNullability = [](QualType Ty) {
9111 std::optional<NullabilityKind> Kind = Ty->getNullability();
9112 if (Kind) {
9113 // For our purposes, treat _Nullable_result as _Nullable.
9116 return *Kind;
9117 }
9119 };
9120
9121 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9122 NullabilityKind MergedKind;
9123
9124 // Compute nullability of a binary conditional expression.
9125 if (IsBin) {
9126 if (LHSKind == NullabilityKind::NonNull)
9127 MergedKind = NullabilityKind::NonNull;
9128 else
9129 MergedKind = RHSKind;
9130 // Compute nullability of a normal conditional expression.
9131 } else {
9132 if (LHSKind == NullabilityKind::Nullable ||
9133 RHSKind == NullabilityKind::Nullable)
9134 MergedKind = NullabilityKind::Nullable;
9135 else if (LHSKind == NullabilityKind::NonNull)
9136 MergedKind = RHSKind;
9137 else if (RHSKind == NullabilityKind::NonNull)
9138 MergedKind = LHSKind;
9139 else
9140 MergedKind = NullabilityKind::Unspecified;
9141 }
9142
9143 // Return if ResTy already has the correct nullability.
9144 if (GetNullability(ResTy) == MergedKind)
9145 return ResTy;
9146
9147 // Strip all nullability from ResTy.
9148 while (ResTy->getNullability())
9149 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9150
9151 // Create a new AttributedType with the new nullability kind.
9152 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
9153}
9154
9156 SourceLocation ColonLoc,
9157 Expr *CondExpr, Expr *LHSExpr,
9158 Expr *RHSExpr) {
9159 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9160 // was the condition.
9161 OpaqueValueExpr *opaqueValue = nullptr;
9162 Expr *commonExpr = nullptr;
9163 if (!LHSExpr) {
9164 commonExpr = CondExpr;
9165 // Lower out placeholder types first. This is important so that we don't
9166 // try to capture a placeholder. This happens in few cases in C++; such
9167 // as Objective-C++'s dictionary subscripting syntax.
9168 if (commonExpr->hasPlaceholderType()) {
9169 ExprResult result = CheckPlaceholderExpr(commonExpr);
9170 if (!result.isUsable()) return ExprError();
9171 commonExpr = result.get();
9172 }
9173 // We usually want to apply unary conversions *before* saving, except
9174 // in the special case of a C++ l-value conditional.
9175 if (!(getLangOpts().CPlusPlus
9176 && !commonExpr->isTypeDependent()
9177 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9178 && commonExpr->isGLValue()
9179 && commonExpr->isOrdinaryOrBitFieldObject()
9180 && RHSExpr->isOrdinaryOrBitFieldObject()
9181 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9182 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9183 if (commonRes.isInvalid())
9184 return ExprError();
9185 commonExpr = commonRes.get();
9186 }
9187
9188 // If the common expression is a class or array prvalue, materialize it
9189 // so that we can safely refer to it multiple times.
9190 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9191 commonExpr->getType()->isArrayType())) {
9192 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9193 if (MatExpr.isInvalid())
9194 return ExprError();
9195 commonExpr = MatExpr.get();
9196 }
9197
9198 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9199 commonExpr->getType(),
9200 commonExpr->getValueKind(),
9201 commonExpr->getObjectKind(),
9202 commonExpr);
9203 LHSExpr = CondExpr = opaqueValue;
9204 }
9205
9206 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9209 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9210 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9211 VK, OK, QuestionLoc);
9212 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9213 RHS.isInvalid())
9214 return ExprError();
9215
9216 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9217 RHS.get());
9218
9219 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9220
9221 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9222 Context);
9223
9224 if (!commonExpr)
9225 return new (Context)
9226 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9227 RHS.get(), result, VK, OK);
9228
9230 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9231 ColonLoc, result, VK, OK);
9232}
9233
9235 unsigned FromAttributes = 0, ToAttributes = 0;
9236 if (const auto *FromFn =
9237 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9238 FromAttributes =
9239 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9240 if (const auto *ToFn =
9241 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9242 ToAttributes =
9243 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9244
9245 return FromAttributes != ToAttributes;
9246}
9247
9248// checkPointerTypesForAssignment - This is a very tricky routine (despite
9249// being closely modeled after the C99 spec:-). The odd characteristic of this
9250// routine is it effectively iqnores the qualifiers on the top level pointee.
9251// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9252// FIXME: add a couple examples in this comment.
9254 QualType LHSType,
9255 QualType RHSType,
9256 SourceLocation Loc) {
9257 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9258 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9259
9260 // get the "pointed to" type (ignoring qualifiers at the top level)
9261 const Type *lhptee, *rhptee;
9262 Qualifiers lhq, rhq;
9263 std::tie(lhptee, lhq) =
9264 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9265 std::tie(rhptee, rhq) =
9266 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9267
9269
9270 // C99 6.5.16.1p1: This following citation is common to constraints
9271 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9272 // qualifiers of the type *pointed to* by the right;
9273
9274 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9275 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9277 // Ignore lifetime for further calculation.
9278 lhq.removeObjCLifetime();
9279 rhq.removeObjCLifetime();
9280 }
9281
9282 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
9283 // Treat address-space mismatches as fatal.
9284 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
9286
9287 // It's okay to add or remove GC or lifetime qualifiers when converting to
9288 // and from void*.
9291 S.getASTContext()) &&
9292 (lhptee->isVoidType() || rhptee->isVoidType()))
9293 ; // keep old
9294
9295 // Treat lifetime mismatches as fatal.
9296 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9298
9299 // Treat pointer-auth mismatches as fatal.
9300 else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth()))
9302
9303 // For GCC/MS compatibility, other qualifier mismatches are treated
9304 // as still compatible in C.
9305 else
9307 }
9308
9309 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9310 // incomplete type and the other is a pointer to a qualified or unqualified
9311 // version of void...
9312 if (lhptee->isVoidType()) {
9313 if (rhptee->isIncompleteOrObjectType())
9314 return ConvTy;
9315
9316 // As an extension, we allow cast to/from void* to function pointer.
9317 assert(rhptee->isFunctionType());
9319 }
9320
9321 if (rhptee->isVoidType()) {
9322 // In C, void * to another pointer type is compatible, but we want to note
9323 // that there will be an implicit conversion happening here.
9324 if (lhptee->isIncompleteOrObjectType())
9325 return ConvTy == AssignConvertType::Compatible &&
9326 !S.getLangOpts().CPlusPlus
9328 : ConvTy;
9329
9330 // As an extension, we allow cast to/from void* to function pointer.
9331 assert(lhptee->isFunctionType());
9333 }
9334
9335 if (!S.Diags.isIgnored(
9336 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9337 Loc) &&
9338 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9339 !S.TryFunctionConversion(RHSType, LHSType, RHSType))
9341
9342 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9343 // unqualified versions of compatible types, ...
9344 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9345
9346 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9347 if (!S.Context.hasSameType(ltrans, rtrans)) {
9348 QualType LUnderlying =
9349 ltrans->isOverflowBehaviorType()
9350 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9351 : ltrans;
9352 QualType RUnderlying =
9353 rtrans->isOverflowBehaviorType()
9354 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9355 : rtrans;
9356
9357 if (S.Context.hasSameType(LUnderlying, RUnderlying))
9359
9360 ltrans = LUnderlying;
9361 rtrans = RUnderlying;
9362 }
9363 }
9364
9365 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9366 // Check if the pointee types are compatible ignoring the sign.
9367 // We explicitly check for char so that we catch "char" vs
9368 // "unsigned char" on systems where "char" is unsigned.
9369 if (lhptee->isCharType())
9370 ltrans = S.Context.UnsignedCharTy;
9371 else if (lhptee->hasSignedIntegerRepresentation())
9372 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9373
9374 if (rhptee->isCharType())
9375 rtrans = S.Context.UnsignedCharTy;
9376 else if (rhptee->hasSignedIntegerRepresentation())
9377 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9378
9379 if (ltrans == rtrans) {
9380 // Types are compatible ignoring the sign. Qualifier incompatibility
9381 // takes priority over sign incompatibility because the sign
9382 // warning can be disabled.
9383 if (!S.IsAssignConvertCompatible(ConvTy))
9384 return ConvTy;
9385
9387 }
9388
9389 // If we are a multi-level pointer, it's possible that our issue is simply
9390 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9391 // the eventual target type is the same and the pointers have the same
9392 // level of indirection, this must be the issue.
9393 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9394 do {
9395 std::tie(lhptee, lhq) =
9396 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9397 std::tie(rhptee, rhq) =
9398 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9399
9400 // Inconsistent address spaces at this point is invalid, even if the
9401 // address spaces would be compatible.
9402 // FIXME: This doesn't catch address space mismatches for pointers of
9403 // different nesting levels, like:
9404 // __local int *** a;
9405 // int ** b = a;
9406 // It's not clear how to actually determine when such pointers are
9407 // invalidly incompatible.
9408 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9409 return AssignConvertType::
9410 IncompatibleNestedPointerAddressSpaceMismatch;
9411
9412 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9413
9414 if (lhptee == rhptee)
9416 }
9417
9418 // General pointer incompatibility takes priority over qualifiers.
9419 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9422 }
9423 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9424 // hasSameType, so we can skip further checks.
9425 const auto *LFT = ltrans->getAs<FunctionType>();
9426 const auto *RFT = rtrans->getAs<FunctionType>();
9427 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9428 // The invocation of IsFunctionConversion below will try to transform rtrans
9429 // to obtain an exact match for ltrans. This should not fail because of
9430 // mismatches in result type and parameter types, they were already checked
9431 // by typesAreCompatible above. So we will recreate rtrans (or where
9432 // appropriate ltrans) using the result type and parameter types from ltrans
9433 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9434 const auto *LFPT = dyn_cast<FunctionProtoType>(LFT);
9435 const auto *RFPT = dyn_cast<FunctionProtoType>(RFT);
9436 if (LFPT && RFPT) {
9437 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9438 LFPT->getParamTypes(),
9439 RFPT->getExtProtoInfo());
9440 } else if (LFPT) {
9442 EPI.ExtInfo = RFT->getExtInfo();
9443 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9444 LFPT->getParamTypes(), EPI);
9445 } else if (RFPT) {
9446 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9447 // all of its ExtProtoInfo. Transform ltrans instead.
9449 EPI.ExtInfo = LFT->getExtInfo();
9450 ltrans = S.Context.getFunctionType(RFPT->getReturnType(),
9451 RFPT->getParamTypes(), EPI);
9452 } else {
9453 rtrans = S.Context.getFunctionNoProtoType(LFT->getReturnType(),
9454 RFT->getExtInfo());
9455 }
9456 if (!S.Context.hasSameUnqualifiedType(rtrans, ltrans) &&
9457 !S.IsFunctionConversion(rtrans, ltrans))
9459 }
9460 return ConvTy;
9461}
9462
9463/// checkBlockPointerTypesForAssignment - This routine determines whether two
9464/// block pointer types are compatible or whether a block and normal pointer
9465/// are compatible. It is more restrict than comparing two function pointer
9466// types.
9468 QualType LHSType,
9469 QualType RHSType) {
9470 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9471 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9472
9473 QualType lhptee, rhptee;
9474
9475 // get the "pointed to" type (ignoring qualifiers at the top level)
9476 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9477 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9478
9479 // In C++, the types have to match exactly.
9480 if (S.getLangOpts().CPlusPlus)
9482
9484
9485 // For blocks we enforce that qualifiers are identical.
9486 Qualifiers LQuals = lhptee.getLocalQualifiers();
9487 Qualifiers RQuals = rhptee.getLocalQualifiers();
9488 if (S.getLangOpts().OpenCL) {
9489 LQuals.removeAddressSpace();
9490 RQuals.removeAddressSpace();
9491 }
9492 if (LQuals != RQuals)
9494
9495 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9496 // assignment.
9497 // The current behavior is similar to C++ lambdas. A block might be
9498 // assigned to a variable iff its return type and parameters are compatible
9499 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9500 // an assignment. Presumably it should behave in way that a function pointer
9501 // assignment does in C, so for each parameter and return type:
9502 // * CVR and address space of LHS should be a superset of CVR and address
9503 // space of RHS.
9504 // * unqualified types should be compatible.
9505 if (S.getLangOpts().OpenCL) {
9507 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9508 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9510 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9512
9513 return ConvTy;
9514}
9515
9516/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9517/// for assignment compatibility.
9519 QualType LHSType,
9520 QualType RHSType) {
9521 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9522 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9523
9524 if (LHSType->isObjCBuiltinType()) {
9525 // Class is not compatible with ObjC object pointers.
9526 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9527 !RHSType->isObjCQualifiedClassType())
9530 }
9531 if (RHSType->isObjCBuiltinType()) {
9532 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9533 !LHSType->isObjCQualifiedClassType())
9536 }
9537 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9538 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9539
9540 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9541 // make an exception for id<P>
9542 !LHSType->isObjCQualifiedIdType())
9544
9545 if (S.Context.typesAreCompatible(LHSType, RHSType))
9547 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9550}
9551
9553 QualType LHSType,
9554 QualType RHSType) {
9555 // Fake up an opaque expression. We don't actually care about what
9556 // cast operations are required, so if CheckAssignmentConstraints
9557 // adds casts to this they'll be wasted, but fortunately that doesn't
9558 // usually happen on valid code.
9559 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9560 ExprResult RHSPtr = &RHSExpr;
9561 CastKind K;
9562
9563 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9564}
9565
9566/// This helper function returns true if QT is a vector type that has element
9567/// type ElementType.
9568static bool isVector(QualType QT, QualType ElementType) {
9569 if (const VectorType *VT = QT->getAs<VectorType>())
9570 return VT->getElementType().getCanonicalType() == ElementType;
9571 return false;
9572}
9573
9574/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9575/// has code to accommodate several GCC extensions when type checking
9576/// pointers. Here are some objectionable examples that GCC considers warnings:
9577///
9578/// int a, *pint;
9579/// short *pshort;
9580/// struct foo *pfoo;
9581///
9582/// pint = pshort; // warning: assignment from incompatible pointer type
9583/// a = pint; // warning: assignment makes integer from pointer without a cast
9584/// pint = a; // warning: assignment makes pointer from integer without a cast
9585/// pint = pfoo; // warning: assignment from incompatible pointer type
9586///
9587/// As a result, the code for dealing with pointers is more complex than the
9588/// C99 spec dictates.
9589///
9590/// Sets 'Kind' for any result kind except Incompatible.
9592 ExprResult &RHS,
9593 CastKind &Kind,
9594 bool ConvertRHS) {
9595 QualType RHSType = RHS.get()->getType();
9596 QualType OrigLHSType = LHSType;
9597
9598 // Get canonical types. We're not formatting these types, just comparing
9599 // them.
9600 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9601 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9602
9603 // Common case: no conversion required.
9604 if (LHSType == RHSType) {
9605 Kind = CK_NoOp;
9607 }
9608
9609 // If the LHS has an __auto_type, there are no additional type constraints
9610 // to be worried about.
9611 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9612 if (AT->isGNUAutoType()) {
9613 Kind = CK_NoOp;
9615 }
9616 }
9617
9618 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHSType, RHSType);
9619 switch (OBTResult) {
9621 Kind = CK_NoOp;
9624 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9628 break;
9629 }
9630
9631 // Check for incompatible OBT types in pointer pointee types
9632 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9633 QualType LHSPointee = LHSType->getPointeeType();
9634 QualType RHSPointee = RHSType->getPointeeType();
9635 if ((LHSPointee->isOverflowBehaviorType() ||
9636 RHSPointee->isOverflowBehaviorType()) &&
9637 !Context.areCompatibleOverflowBehaviorTypes(LHSPointee, RHSPointee)) {
9638 Kind = CK_NoOp;
9640 }
9641 }
9642
9643 // If we have an atomic type, try a non-atomic assignment, then just add an
9644 // atomic qualification step.
9645 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9647 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9649 return Result;
9650 if (Kind != CK_NoOp && ConvertRHS)
9651 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9652 Kind = CK_NonAtomicToAtomic;
9653 return Result;
9654 }
9655
9656 // If the left-hand side is a reference type, then we are in a
9657 // (rare!) case where we've allowed the use of references in C,
9658 // e.g., as a parameter type in a built-in function. In this case,
9659 // just make sure that the type referenced is compatible with the
9660 // right-hand side type. The caller is responsible for adjusting
9661 // LHSType so that the resulting expression does not have reference
9662 // type.
9663 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9664 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9665 Kind = CK_LValueBitCast;
9667 }
9669 }
9670
9671 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9672 // of an ExtVector type to the same ExtVector type.
9673 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9674 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9675 // Implicit conversions require the same number of elements.
9676 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9678
9679 if (LHSType->isExtVectorBoolType() &&
9680 RHSExtType->getElementType()->isIntegerType()) {
9681 Kind = CK_IntegralToBoolean;
9683 }
9684 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9685 if (Context.getLangOpts().OpenCL &&
9686 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9687 Kind = CK_BitCast;
9689 }
9691 }
9692 if (RHSType->isArithmeticType()) {
9693 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9694 if (ConvertRHS)
9695 RHS = prepareVectorSplat(LHSType, RHS.get());
9696 Kind = CK_VectorSplat;
9698 }
9699 }
9700
9701 // Conversions to or from vector type.
9702 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9703 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9704 // Allow assignments of an AltiVec vector type to an equivalent GCC
9705 // vector type and vice versa
9706 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9707 Kind = CK_BitCast;
9709 }
9710
9711 // If we are allowing lax vector conversions, and LHS and RHS are both
9712 // vectors, the total size only needs to be the same. This is a bitcast;
9713 // no bits are changed but the result type is different.
9714 if (isLaxVectorConversion(RHSType, LHSType)) {
9715 // The default for lax vector conversions with Altivec vectors will
9716 // change, so if we are converting between vector types where
9717 // at least one is an Altivec vector, emit a warning.
9718 if (Context.getTargetInfo().getTriple().isPPC() &&
9719 anyAltivecTypes(RHSType, LHSType) &&
9720 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9721 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9722 << RHSType << LHSType;
9723 Kind = CK_BitCast;
9725 }
9726 }
9727
9728 // When the RHS comes from another lax conversion (e.g. binops between
9729 // scalars and vectors) the result is canonicalized as a vector. When the
9730 // LHS is also a vector, the lax is allowed by the condition above. Handle
9731 // the case where LHS is a scalar.
9732 if (LHSType->isScalarType()) {
9733 const VectorType *VecType = RHSType->getAs<VectorType>();
9734 if (VecType && VecType->getNumElements() == 1 &&
9735 isLaxVectorConversion(RHSType, LHSType)) {
9736 if (Context.getTargetInfo().getTriple().isPPC() &&
9738 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9740 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9741 << RHSType << LHSType;
9742 ExprResult *VecExpr = &RHS;
9743 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9744 Kind = CK_BitCast;
9746 }
9747 }
9748
9749 // Allow assignments between fixed-length and sizeless SVE vectors.
9750 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9751 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9752 if (ARM().areCompatibleSveTypes(LHSType, RHSType) ||
9753 ARM().areLaxCompatibleSveTypes(LHSType, RHSType)) {
9754 Kind = CK_BitCast;
9756 }
9757
9758 // Allow assignments between fixed-length and sizeless RVV vectors.
9759 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9760 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9761 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9762 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9763 Kind = CK_BitCast;
9765 }
9766 }
9767
9769 }
9770
9771 // Diagnose attempts to convert between __ibm128, __float128 and long double
9772 // where such conversions currently can't be handled.
9773 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9775
9776 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9777 // discards the imaginary part.
9778 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9779 !LHSType->getAs<ComplexType>())
9781
9782 // Arithmetic conversions.
9783 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9784 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9785 if (ConvertRHS)
9786 Kind = PrepareScalarCast(RHS, LHSType);
9788 }
9789
9790 // Conversions to normal pointers.
9791 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9792 // U* -> T*
9793 if (isa<PointerType>(RHSType)) {
9794 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9795 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9796 if (AddrSpaceL != AddrSpaceR)
9797 Kind = CK_AddressSpaceConversion;
9798 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9799 Kind = CK_NoOp;
9800 else
9801 Kind = CK_BitCast;
9802 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9803 RHS.get()->getBeginLoc());
9804 }
9805
9806 // int -> T*
9807 if (RHSType->isIntegerType()) {
9808 Kind = CK_IntegralToPointer; // FIXME: null?
9810 }
9811
9812 // C pointers are not compatible with ObjC object pointers,
9813 // with two exceptions:
9814 if (isa<ObjCObjectPointerType>(RHSType)) {
9815 // - conversions to void*
9816 if (LHSPointer->getPointeeType()->isVoidType()) {
9817 Kind = CK_BitCast;
9819 }
9820
9821 // - conversions from 'Class' to the redefinition type
9822 if (RHSType->isObjCClassType() &&
9823 Context.hasSameType(LHSType,
9824 Context.getObjCClassRedefinitionType())) {
9825 Kind = CK_BitCast;
9827 }
9828
9829 Kind = CK_BitCast;
9831 }
9832
9833 // U^ -> void*
9834 if (RHSType->getAs<BlockPointerType>()) {
9835 if (LHSPointer->getPointeeType()->isVoidType()) {
9836 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9837 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9838 ->getPointeeType()
9839 .getAddressSpace();
9840 Kind =
9841 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9843 }
9844 }
9845
9847 }
9848
9849 // Conversions to block pointers.
9850 if (isa<BlockPointerType>(LHSType)) {
9851 // U^ -> T^
9852 if (RHSType->isBlockPointerType()) {
9853 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9854 ->getPointeeType()
9855 .getAddressSpace();
9856 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9857 ->getPointeeType()
9858 .getAddressSpace();
9859 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9860 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9861 }
9862
9863 // int or null -> T^
9864 if (RHSType->isIntegerType()) {
9865 Kind = CK_IntegralToPointer; // FIXME: null
9867 }
9868
9869 // id -> T^
9870 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9871 Kind = CK_AnyPointerToBlockPointerCast;
9873 }
9874
9875 // void* -> T^
9876 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9877 if (RHSPT->getPointeeType()->isVoidType()) {
9878 Kind = CK_AnyPointerToBlockPointerCast;
9880 }
9881
9883 }
9884
9885 // Conversions to Objective-C pointers.
9886 if (isa<ObjCObjectPointerType>(LHSType)) {
9887 // A* -> B*
9888 if (RHSType->isObjCObjectPointerType()) {
9889 Kind = CK_BitCast;
9890 AssignConvertType result =
9891 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9892 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9894 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9896 return result;
9897 }
9898
9899 // int or null -> A*
9900 if (RHSType->isIntegerType()) {
9901 Kind = CK_IntegralToPointer; // FIXME: null
9903 }
9904
9905 // In general, C pointers are not compatible with ObjC object pointers,
9906 // with two exceptions:
9907 if (isa<PointerType>(RHSType)) {
9908 Kind = CK_CPointerToObjCPointerCast;
9909
9910 // - conversions from 'void*'
9911 if (RHSType->isVoidPointerType()) {
9913 }
9914
9915 // - conversions to 'Class' from its redefinition type
9916 if (LHSType->isObjCClassType() &&
9917 Context.hasSameType(RHSType,
9918 Context.getObjCClassRedefinitionType())) {
9920 }
9921
9923 }
9924
9925 // Only under strict condition T^ is compatible with an Objective-C pointer.
9926 if (RHSType->isBlockPointerType() &&
9928 if (ConvertRHS)
9930 Kind = CK_BlockPointerToObjCPointerCast;
9932 }
9933
9935 }
9936
9937 // Conversion to nullptr_t (C23 only)
9938 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9941 // null -> nullptr_t
9942 Kind = CK_NullToPointer;
9944 }
9945
9946 // Conversions from pointers that are not covered by the above.
9947 if (isa<PointerType>(RHSType)) {
9948 // T* -> _Bool
9949 if (LHSType == Context.BoolTy) {
9950 Kind = CK_PointerToBoolean;
9952 }
9953
9954 // T* -> int
9955 if (LHSType->isIntegerType()) {
9956 Kind = CK_PointerToIntegral;
9958 }
9959
9961 }
9962
9963 // Conversions from Objective-C pointers that are not covered by the above.
9964 if (isa<ObjCObjectPointerType>(RHSType)) {
9965 // T* -> _Bool
9966 if (LHSType == Context.BoolTy) {
9967 Kind = CK_PointerToBoolean;
9969 }
9970
9971 // T* -> int
9972 if (LHSType->isIntegerType()) {
9973 Kind = CK_PointerToIntegral;
9975 }
9976
9978 }
9979
9980 // struct A -> struct B
9981 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9982 if (Context.typesAreCompatible(LHSType, RHSType)) {
9983 Kind = CK_NoOp;
9985 }
9986 }
9987
9988 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9989 Kind = CK_IntToOCLSampler;
9991 }
9992
9994}
9995
9996/// Constructs a transparent union from an expression that is
9997/// used to initialize the transparent union.
9999 ExprResult &EResult, QualType UnionType,
10000 FieldDecl *Field) {
10001 // Build an initializer list that designates the appropriate member
10002 // of the transparent union.
10003 Expr *E = EResult.get();
10005 E, SourceLocation());
10006 Initializer->setType(UnionType);
10007 Initializer->setInitializedFieldInUnion(Field);
10008
10009 // Build a compound literal constructing a value of the transparent
10010 // union type from this initializer list.
10011 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10012 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10013 VK_PRValue, Initializer, false);
10014}
10015
10018 ExprResult &RHS) {
10019 QualType RHSType = RHS.get()->getType();
10020
10021 // If the ArgType is a Union type, we want to handle a potential
10022 // transparent_union GCC extension.
10023 const RecordType *UT = ArgType->getAsUnionType();
10024 if (!UT)
10026
10027 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10028 if (!UD->hasAttr<TransparentUnionAttr>())
10030
10031 // The field to initialize within the transparent union.
10032 FieldDecl *InitField = nullptr;
10033 // It's compatible if the expression matches any of the fields.
10034 for (auto *it : UD->fields()) {
10035 if (it->getType()->isPointerType()) {
10036 // If the transparent union contains a pointer type, we allow:
10037 // 1) void pointer
10038 // 2) null pointer constant
10039 if (RHSType->isPointerType())
10040 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10041 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10042 InitField = it;
10043 break;
10044 }
10045
10048 RHS = ImpCastExprToType(RHS.get(), it->getType(),
10049 CK_NullToPointer);
10050 InitField = it;
10051 break;
10052 }
10053 }
10054
10055 CastKind Kind;
10056 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) ==
10058 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10059 InitField = it;
10060 break;
10061 }
10062 }
10063
10064 if (!InitField)
10066
10067 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10069}
10070
10072 ExprResult &CallerRHS,
10073 bool Diagnose,
10074 bool DiagnoseCFAudited,
10075 bool ConvertRHS) {
10076 // We need to be able to tell the caller whether we diagnosed a problem, if
10077 // they ask us to issue diagnostics.
10078 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10079
10080 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10081 // we can't avoid *all* modifications at the moment, so we need some somewhere
10082 // to put the updated value.
10083 ExprResult LocalRHS = CallerRHS;
10084 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10085
10086 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10087 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10088 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10089 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10090 Diag(RHS.get()->getExprLoc(),
10091 diag::warn_noderef_to_dereferenceable_pointer)
10092 << RHS.get()->getSourceRange();
10093 }
10094 }
10095 }
10096
10097 if (getLangOpts().CPlusPlus) {
10098 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10099 // C++ 5.17p3: If the left operand is not of class type, the
10100 // expression is implicitly converted (C++ 4) to the
10101 // cv-unqualified type of the left operand.
10102 QualType RHSType = RHS.get()->getType();
10103 if (Diagnose) {
10104 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10106 } else {
10109 /*SuppressUserConversions=*/false,
10110 AllowedExplicit::None,
10111 /*InOverloadResolution=*/false,
10112 /*CStyle=*/false,
10113 /*AllowObjCWritebackConversion=*/false);
10114 if (ICS.isFailure())
10116 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10118 }
10119 if (RHS.isInvalid())
10122 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10123 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10125
10126 // Check if OBT is being discarded during assignment
10127 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10128 if (RHSType->isOverflowBehaviorType() &&
10129 !LHSType->isOverflowBehaviorType()) {
10131 }
10132
10133 return result;
10134 }
10135
10136 // FIXME: Currently, we fall through and treat C++ classes like C
10137 // structures.
10138 // FIXME: We also fall through for atomics; not sure what should
10139 // happen there, though.
10140 } else if (RHS.get()->getType() == Context.OverloadTy) {
10141 // As a set of extensions to C, we support overloading on functions. These
10142 // functions need to be resolved here.
10143 DeclAccessPair DAP;
10145 RHS.get(), LHSType, /*Complain=*/false, DAP))
10146 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10147 else
10149 }
10150
10151 // This check seems unnatural, however it is necessary to ensure the proper
10152 // conversion of functions/arrays. If the conversion were done for all
10153 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10154 // expressions that suppress this implicit conversion (&, sizeof). This needs
10155 // to happen before we check for null pointer conversions because C does not
10156 // undergo the same implicit conversions as C++ does above (by the calls to
10157 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10158 // lvalue to rvalue cast before checking for null pointer constraints. This
10159 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10160 //
10161 // Suppress this for references: C++ 8.5.3p5.
10162 if (!LHSType->isReferenceType()) {
10163 // FIXME: We potentially allocate here even if ConvertRHS is false.
10165 if (RHS.isInvalid())
10167 }
10168
10169 // The constraints are expressed in terms of the atomic, qualified, or
10170 // unqualified type of the LHS.
10171 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10172
10173 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10174 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10175 if ((LHSTypeAfterConversion->isPointerType() ||
10176 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10177 LHSTypeAfterConversion->isBlockPointerType()) &&
10178 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10182 if (Diagnose || ConvertRHS) {
10183 CastKind Kind;
10184 CXXCastPath Path;
10185 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10186 /*IgnoreBaseAccess=*/false, Diagnose);
10187
10188 // If there is a conversion of some kind, check to see what kind of
10189 // pointer conversion happened so we can diagnose a C++ compatibility
10190 // diagnostic if the conversion is invalid. This only matters if the RHS
10191 // is some kind of void pointer. We have a carve-out when the RHS is from
10192 // a macro expansion because the use of a macro may indicate different
10193 // code between C and C++. Consider: char *s = NULL; where NULL is
10194 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10195 // C++, which is valid in C++.
10196 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10197 !RHS.get()->getBeginLoc().isMacroID()) {
10198 QualType CanRHS =
10200 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10201 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10202 Ret = checkPointerTypesForAssignment(*this, CanLHS, CanRHS,
10203 RHS.get()->getExprLoc());
10204 // Anything that's not considered perfectly compatible would be
10205 // incompatible in C++.
10208 }
10209 }
10210
10211 if (ConvertRHS)
10212 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10213 }
10214 return Ret;
10215 }
10216 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10217 // unqualified bool, and the right operand is a pointer or its type is
10218 // nullptr_t.
10219 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10220 RHS.get()->getType()->isNullPtrType()) {
10221 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10222 // only handles nullptr -> _Bool due to needing an extra conversion
10223 // step.
10224 // We model this by converting from nullptr -> void * and then let the
10225 // conversion from void * -> _Bool happen naturally.
10226 if (Diagnose || ConvertRHS) {
10227 CastKind Kind;
10228 CXXCastPath Path;
10229 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10230 /*IgnoreBaseAccess=*/false, Diagnose);
10231 if (ConvertRHS)
10232 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10233 &Path);
10234 }
10235 }
10236
10237 // OpenCL queue_t type assignment.
10238 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10240 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10242 }
10243
10244 CastKind Kind;
10245 AssignConvertType result =
10246 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10247
10248 // If assigning a void * created by an allocation function call to some other
10249 // type, check that the allocated size is sufficient for that type.
10250 if (result != AssignConvertType::Incompatible &&
10251 RHS.get()->getType()->isVoidPointerType())
10252 CheckSufficientAllocSize(*this, LHSType, RHS.get());
10253
10254 // C99 6.5.16.1p2: The value of the right operand is converted to the
10255 // type of the assignment expression.
10256 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10257 // so that we can use references in built-in functions even in C.
10258 // The getNonReferenceType() call makes sure that the resulting expression
10259 // does not have reference type.
10260 if (result != AssignConvertType::Incompatible &&
10261 RHS.get()->getType() != LHSType) {
10263 Expr *E = RHS.get();
10264
10265 // Check for various Objective-C errors. If we are not reporting
10266 // diagnostics and just checking for errors, e.g., during overload
10267 // resolution, return Incompatible to indicate the failure.
10268 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10269 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
10271 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10272 if (!Diagnose)
10274 }
10275 if (getLangOpts().ObjC &&
10276 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10277 E->getType(), E, Diagnose) ||
10278 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10279 if (!Diagnose)
10281 // Replace the expression with a corrected version and continue so we
10282 // can find further errors.
10283 RHS = E;
10285 }
10286
10287 if (ConvertRHS)
10288 RHS = ImpCastExprToType(E, Ty, Kind);
10289 }
10290
10291 return result;
10292}
10293
10294namespace {
10295/// The original operand to an operator, prior to the application of the usual
10296/// arithmetic conversions and converting the arguments of a builtin operator
10297/// candidate.
10298struct OriginalOperand {
10299 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10300 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10301 Op = MTE->getSubExpr();
10302 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10303 Op = BTE->getSubExpr();
10304 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10305 Orig = ICE->getSubExprAsWritten();
10306 Conversion = ICE->getConversionFunction();
10307 }
10308 }
10309
10310 QualType getType() const { return Orig->getType(); }
10311
10312 Expr *Orig;
10313 NamedDecl *Conversion;
10314};
10315}
10316
10318 ExprResult &RHS) {
10319 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10320
10321 Diag(Loc, diag::err_typecheck_invalid_operands)
10322 << OrigLHS.getType() << OrigRHS.getType()
10323 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10324
10325 // If a user-defined conversion was applied to either of the operands prior
10326 // to applying the built-in operator rules, tell the user about it.
10327 if (OrigLHS.Conversion) {
10328 Diag(OrigLHS.Conversion->getLocation(),
10329 diag::note_typecheck_invalid_operands_converted)
10330 << 0 << LHS.get()->getType();
10331 }
10332 if (OrigRHS.Conversion) {
10333 Diag(OrigRHS.Conversion->getLocation(),
10334 diag::note_typecheck_invalid_operands_converted)
10335 << 1 << RHS.get()->getType();
10336 }
10337
10338 return QualType();
10339}
10340
10342 ExprResult &RHS) {
10343 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10344 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10345
10346 bool LHSNatVec = LHSType->isVectorType();
10347 bool RHSNatVec = RHSType->isVectorType();
10348
10349 if (!(LHSNatVec && RHSNatVec)) {
10350 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10351 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10352 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10353 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10354 << Vector->getSourceRange();
10355 return QualType();
10356 }
10357
10358 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10359 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10360 << RHS.get()->getSourceRange();
10361
10362 return QualType();
10363}
10364
10365/// Try to convert a value of non-vector type to a vector type by converting
10366/// the type to the element type of the vector and then performing a splat.
10367/// If the language is OpenCL, we only use conversions that promote scalar
10368/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10369/// for float->int.
10370///
10371/// OpenCL V2.0 6.2.6.p2:
10372/// An error shall occur if any scalar operand type has greater rank
10373/// than the type of the vector element.
10374///
10375/// \param scalar - if non-null, actually perform the conversions
10376/// \return true if the operation fails (but without diagnosing the failure)
10378 QualType scalarTy,
10379 QualType vectorEltTy,
10380 QualType vectorTy,
10381 unsigned &DiagID) {
10382 // The conversion to apply to the scalar before splatting it,
10383 // if necessary.
10384 CastKind scalarCast = CK_NoOp;
10385
10386 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
10387 scalarCast = CK_IntegralToBoolean;
10388 } else if (vectorEltTy->isIntegralType(S.Context)) {
10389 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10390 (scalarTy->isIntegerType() &&
10391 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10392 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10393 return true;
10394 }
10395 if (!scalarTy->isIntegralType(S.Context))
10396 return true;
10397 scalarCast = CK_IntegralCast;
10398 } else if (vectorEltTy->isRealFloatingType()) {
10399 if (scalarTy->isRealFloatingType()) {
10400 if (S.getLangOpts().OpenCL &&
10401 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10402 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10403 return true;
10404 }
10405 scalarCast = CK_FloatingCast;
10406 }
10407 else if (scalarTy->isIntegralType(S.Context))
10408 scalarCast = CK_IntegralToFloating;
10409 else
10410 return true;
10411 } else {
10412 return true;
10413 }
10414
10415 // Adjust scalar if desired.
10416 if (scalar) {
10417 if (scalarCast != CK_NoOp)
10418 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10419 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10420 }
10421 return false;
10422}
10423
10424/// Convert vector E to a vector with the same number of elements but different
10425/// element type.
10426static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10427 const auto *VecTy = E->getType()->getAs<VectorType>();
10428 assert(VecTy && "Expression E must be a vector");
10429 QualType NewVecTy =
10430 VecTy->isExtVectorType()
10431 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10432 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10433 VecTy->getVectorKind());
10434
10435 // Look through the implicit cast. Return the subexpression if its type is
10436 // NewVecTy.
10437 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10438 if (ICE->getSubExpr()->getType() == NewVecTy)
10439 return ICE->getSubExpr();
10440
10441 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10442 return S.ImpCastExprToType(E, NewVecTy, Cast);
10443}
10444
10445/// Test if a (constant) integer Int can be casted to another integer type
10446/// IntTy without losing precision.
10448 QualType OtherIntTy) {
10449 Expr *E = Int->get();
10451 return false;
10452
10453 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10454
10455 // Reject cases where the value of the Int is unknown as that would
10456 // possibly cause truncation, but accept cases where the scalar can be
10457 // demoted without loss of precision.
10458 Expr::EvalResult EVResult;
10459 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10460 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10461 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10462 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10463
10464 if (CstInt) {
10465 // If the scalar is constant and is of a higher order and has more active
10466 // bits that the vector element type, reject it.
10467 llvm::APSInt Result = EVResult.Val.getInt();
10468 unsigned NumBits = IntSigned
10469 ? (Result.isNegative() ? Result.getSignificantBits()
10470 : Result.getActiveBits())
10471 : Result.getActiveBits();
10472 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10473 return true;
10474
10475 // If the signedness of the scalar type and the vector element type
10476 // differs and the number of bits is greater than that of the vector
10477 // element reject it.
10478 return (IntSigned != OtherIntSigned &&
10479 NumBits > S.Context.getIntWidth(OtherIntTy));
10480 }
10481
10482 // Reject cases where the value of the scalar is not constant and it's
10483 // order is greater than that of the vector element type.
10484 return (Order < 0);
10485}
10486
10487/// Test if a (constant) integer Int can be casted to floating point type
10488/// FloatTy without losing precision.
10490 QualType FloatTy) {
10491 if (Int->get()->containsErrors())
10492 return false;
10493
10494 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10495
10496 // Determine if the integer constant can be expressed as a floating point
10497 // number of the appropriate type.
10498 Expr::EvalResult EVResult;
10499 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10500
10501 uint64_t Bits = 0;
10502 if (CstInt) {
10503 // Reject constants that would be truncated if they were converted to
10504 // the floating point type. Test by simple to/from conversion.
10505 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10506 // could be avoided if there was a convertFromAPInt method
10507 // which could signal back if implicit truncation occurred.
10508 llvm::APSInt Result = EVResult.Val.getInt();
10509 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10510 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10511 llvm::APFloat::rmTowardZero);
10512 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10514 bool Ignored = false;
10515 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10516 &Ignored);
10517 if (Result != ConvertBack)
10518 return true;
10519 } else {
10520 // Reject types that cannot be fully encoded into the mantissa of
10521 // the float.
10522 Bits = S.Context.getTypeSize(IntTy);
10523 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10524 S.Context.getFloatTypeSemantics(FloatTy));
10525 if (Bits > FloatPrec)
10526 return true;
10527 }
10528
10529 return false;
10530}
10531
10532/// Attempt to convert and splat Scalar into a vector whose types matches
10533/// Vector following GCC conversion rules. The rule is that implicit
10534/// conversion can occur when Scalar can be casted to match Vector's element
10535/// type without causing truncation of Scalar.
10537 ExprResult *Vector) {
10538 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10539 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10540 QualType VectorEltTy;
10541
10542 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10543 assert(!isa<ExtVectorType>(VT) &&
10544 "ExtVectorTypes should not be handled here!");
10545 VectorEltTy = VT->getElementType();
10546 } else if (VectorTy->isSveVLSBuiltinType()) {
10547 VectorEltTy =
10548 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10549 } else {
10550 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10551 }
10552
10553 // Reject cases where the vector element type or the scalar element type are
10554 // not integral or floating point types.
10555 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10556 return true;
10557
10558 // The conversion to apply to the scalar before splatting it,
10559 // if necessary.
10560 CastKind ScalarCast = CK_NoOp;
10561
10562 // Accept cases where the vector elements are integers and the scalar is
10563 // an integer.
10564 // FIXME: Notionally if the scalar was a floating point value with a precise
10565 // integral representation, we could cast it to an appropriate integer
10566 // type and then perform the rest of the checks here. GCC will perform
10567 // this conversion in some cases as determined by the input language.
10568 // We should accept it on a language independent basis.
10569 if (VectorEltTy->isIntegralType(S.Context) &&
10570 ScalarTy->isIntegralType(S.Context) &&
10571 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10572
10573 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10574 return true;
10575
10576 ScalarCast = CK_IntegralCast;
10577 } else if (VectorEltTy->isIntegralType(S.Context) &&
10578 ScalarTy->isRealFloatingType()) {
10579 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10580 ScalarCast = CK_FloatingToIntegral;
10581 else
10582 return true;
10583 } else if (VectorEltTy->isRealFloatingType()) {
10584 if (ScalarTy->isRealFloatingType()) {
10585
10586 // Reject cases where the scalar type is not a constant and has a higher
10587 // Order than the vector element type.
10588 llvm::APFloat Result(0.0);
10589
10590 // Determine whether this is a constant scalar. In the event that the
10591 // value is dependent (and thus cannot be evaluated by the constant
10592 // evaluator), skip the evaluation. This will then diagnose once the
10593 // expression is instantiated.
10594 bool CstScalar = Scalar->get()->isValueDependent() ||
10595 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10596 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10597 if (!CstScalar && Order < 0)
10598 return true;
10599
10600 // If the scalar cannot be safely casted to the vector element type,
10601 // reject it.
10602 if (CstScalar) {
10603 bool Truncated = false;
10604 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10605 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10606 if (Truncated)
10607 return true;
10608 }
10609
10610 ScalarCast = CK_FloatingCast;
10611 } else if (ScalarTy->isIntegralType(S.Context)) {
10612 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10613 return true;
10614
10615 ScalarCast = CK_IntegralToFloating;
10616 } else
10617 return true;
10618 } else if (ScalarTy->isEnumeralType())
10619 return true;
10620
10621 // Adjust scalar if desired.
10622 if (ScalarCast != CK_NoOp)
10623 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10624 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10625 return false;
10626}
10627
10629 SourceLocation Loc, bool IsCompAssign,
10630 bool AllowBothBool,
10631 bool AllowBoolConversions,
10632 bool AllowBoolOperation,
10633 bool ReportInvalid) {
10634 if (!IsCompAssign) {
10636 if (LHS.isInvalid())
10637 return QualType();
10638 }
10640 if (RHS.isInvalid())
10641 return QualType();
10642
10643 // For conversion purposes, we ignore any qualifiers.
10644 // For example, "const float" and "float" are equivalent.
10645 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10646 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10647
10648 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10649 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10650 assert(LHSVecType || RHSVecType);
10651
10652 if (getLangOpts().HLSL)
10653 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10654 IsCompAssign);
10655
10656 // Any operation with MFloat8 type is only possible with C intrinsics
10657 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10658 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10659 return InvalidOperands(Loc, LHS, RHS);
10660
10661 // AltiVec-style "vector bool op vector bool" combinations are allowed
10662 // for some operators but not others.
10663 if (!AllowBothBool && LHSVecType &&
10664 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10665 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10666 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10667
10668 // This operation may not be performed on boolean vectors.
10669 if (!AllowBoolOperation &&
10670 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10671 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10672
10673 // If the vector types are identical, return.
10674 if (Context.hasSameType(LHSType, RHSType))
10675 return Context.getCommonSugaredType(LHSType, RHSType);
10676
10677 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10678 if (LHSVecType && RHSVecType &&
10679 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10680 if (isa<ExtVectorType>(LHSVecType)) {
10681 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10682 return LHSType;
10683 }
10684
10685 if (!IsCompAssign)
10686 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10687 return RHSType;
10688 }
10689
10690 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10691 // can be mixed, with the result being the non-bool type. The non-bool
10692 // operand must have integer element type.
10693 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10694 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10695 (Context.getTypeSize(LHSVecType->getElementType()) ==
10696 Context.getTypeSize(RHSVecType->getElementType()))) {
10697 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10698 LHSVecType->getElementType()->isIntegerType() &&
10699 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10700 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10701 return LHSType;
10702 }
10703 if (!IsCompAssign &&
10704 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10705 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10706 RHSVecType->getElementType()->isIntegerType()) {
10707 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10708 return RHSType;
10709 }
10710 }
10711
10712 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10713 // invalid since the ambiguity can affect the ABI.
10714 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10715 unsigned &SVEorRVV) {
10716 const VectorType *VecType = SecondType->getAs<VectorType>();
10717 SVEorRVV = 0;
10718 if (FirstType->isSizelessBuiltinType() && VecType) {
10721 return true;
10727 SVEorRVV = 1;
10728 return true;
10729 }
10730 }
10731
10732 return false;
10733 };
10734
10735 unsigned SVEorRVV;
10736 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10737 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10738 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10739 << SVEorRVV << LHSType << RHSType;
10740 return QualType();
10741 }
10742
10743 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10744 // invalid since the ambiguity can affect the ABI.
10745 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10746 unsigned &SVEorRVV) {
10747 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10748 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10749
10750 SVEorRVV = 0;
10751 if (FirstVecType && SecondVecType) {
10752 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10753 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10754 SecondVecType->getVectorKind() ==
10756 return true;
10757 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10758 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10759 SecondVecType->getVectorKind() ==
10761 SecondVecType->getVectorKind() ==
10763 SecondVecType->getVectorKind() ==
10765 SVEorRVV = 1;
10766 return true;
10767 }
10768 }
10769 return false;
10770 }
10771
10772 if (SecondVecType &&
10773 SecondVecType->getVectorKind() == VectorKind::Generic) {
10774 if (FirstType->isSVESizelessBuiltinType())
10775 return true;
10776 if (FirstType->isRVVSizelessBuiltinType()) {
10777 SVEorRVV = 1;
10778 return true;
10779 }
10780 }
10781
10782 return false;
10783 };
10784
10785 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10786 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10787 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10788 << SVEorRVV << LHSType << RHSType;
10789 return QualType();
10790 }
10791
10792 // If there's a vector type and a scalar, try to convert the scalar to
10793 // the vector element type and splat.
10794 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10795 if (!RHSVecType) {
10796 if (isa<ExtVectorType>(LHSVecType)) {
10797 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10798 LHSVecType->getElementType(), LHSType,
10799 DiagID))
10800 return LHSType;
10801 } else {
10802 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10803 return LHSType;
10804 }
10805 }
10806 if (!LHSVecType) {
10807 if (isa<ExtVectorType>(RHSVecType)) {
10808 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10809 LHSType, RHSVecType->getElementType(),
10810 RHSType, DiagID))
10811 return RHSType;
10812 } else {
10813 if (LHS.get()->isLValue() ||
10814 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10815 return RHSType;
10816 }
10817 }
10818
10819 // FIXME: The code below also handles conversion between vectors and
10820 // non-scalars, we should break this down into fine grained specific checks
10821 // and emit proper diagnostics.
10822 QualType VecType = LHSVecType ? LHSType : RHSType;
10823 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10824 QualType OtherType = LHSVecType ? RHSType : LHSType;
10825 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10826 if (isLaxVectorConversion(OtherType, VecType)) {
10827 if (Context.getTargetInfo().getTriple().isPPC() &&
10828 anyAltivecTypes(RHSType, LHSType) &&
10829 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10830 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10831 // If we're allowing lax vector conversions, only the total (data) size
10832 // needs to be the same. For non compound assignment, if one of the types is
10833 // scalar, the result is always the vector type.
10834 if (!IsCompAssign) {
10835 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10836 return VecType;
10837 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10838 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10839 // type. Note that this is already done by non-compound assignments in
10840 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10841 // <1 x T> -> T. The result is also a vector type.
10842 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10843 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10844 ExprResult *RHSExpr = &RHS;
10845 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10846 return VecType;
10847 }
10848 }
10849
10850 // Okay, the expression is invalid.
10851
10852 // If there's a non-vector, non-real operand, diagnose that.
10853 if ((!RHSVecType && !RHSType->isRealType()) ||
10854 (!LHSVecType && !LHSType->isRealType())) {
10855 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10856 << LHSType << RHSType
10857 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10858 return QualType();
10859 }
10860
10861 // OpenCL V1.1 6.2.6.p1:
10862 // If the operands are of more than one vector type, then an error shall
10863 // occur. Implicit conversions between vector types are not permitted, per
10864 // section 6.2.1.
10865 if (getLangOpts().OpenCL &&
10866 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10867 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10868 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10869 << RHSType;
10870 return QualType();
10871 }
10872
10873
10874 // If there is a vector type that is not a ExtVector and a scalar, we reach
10875 // this point if scalar could not be converted to the vector's element type
10876 // without truncation.
10877 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10878 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10879 QualType Scalar = LHSVecType ? RHSType : LHSType;
10880 QualType Vector = LHSVecType ? LHSType : RHSType;
10881 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10882 Diag(Loc,
10883 diag::err_typecheck_vector_not_convertable_implict_truncation)
10884 << ScalarOrVector << Scalar << Vector;
10885
10886 return QualType();
10887 }
10888
10889 // Otherwise, use the generic diagnostic.
10890 Diag(Loc, DiagID)
10891 << LHSType << RHSType
10892 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10893 return QualType();
10894}
10895
10897 SourceLocation Loc,
10898 bool IsCompAssign,
10899 ArithConvKind OperationKind) {
10900 if (!IsCompAssign) {
10902 if (LHS.isInvalid())
10903 return QualType();
10904 }
10906 if (RHS.isInvalid())
10907 return QualType();
10908
10909 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10910 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10911
10912 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10913 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10914
10915 unsigned DiagID = diag::err_typecheck_invalid_operands;
10916 if ((OperationKind == ArithConvKind::Arithmetic) &&
10917 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10918 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10919 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10920 << RHS.get()->getSourceRange();
10921 return QualType();
10922 }
10923
10924 if (Context.hasSameType(LHSType, RHSType))
10925 return LHSType;
10926
10927 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10928 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10929 return LHSType;
10930 }
10931 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10932 if (LHS.get()->isLValue() ||
10933 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10934 return RHSType;
10935 }
10936
10937 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10938 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10939 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10940 << LHSType << RHSType << LHS.get()->getSourceRange()
10941 << RHS.get()->getSourceRange();
10942 return QualType();
10943 }
10944
10945 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10946 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10947 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10948 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10949 << LHSType << RHSType << LHS.get()->getSourceRange()
10950 << RHS.get()->getSourceRange();
10951 return QualType();
10952 }
10953
10954 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10955 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10956 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10957 bool ScalarOrVector =
10958 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10959
10960 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10961 << ScalarOrVector << Scalar << Vector;
10962
10963 return QualType();
10964 }
10965
10966 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10967 << RHS.get()->getSourceRange();
10968 return QualType();
10969}
10970
10971// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10972// expression. These are mainly cases where the null pointer is used as an
10973// integer instead of a pointer.
10975 SourceLocation Loc, bool IsCompare) {
10976 // The canonical way to check for a GNU null is with isNullPointerConstant,
10977 // but we use a bit of a hack here for speed; this is a relatively
10978 // hot path, and isNullPointerConstant is slow.
10979 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10980 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10981
10982 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10983
10984 // Avoid analyzing cases where the result will either be invalid (and
10985 // diagnosed as such) or entirely valid and not something to warn about.
10986 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10987 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10988 return;
10989
10990 // Comparison operations would not make sense with a null pointer no matter
10991 // what the other expression is.
10992 if (!IsCompare) {
10993 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10994 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10995 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10996 return;
10997 }
10998
10999 // The rest of the operations only make sense with a null pointer
11000 // if the other expression is a pointer.
11001 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11002 NonNullType->canDecayToPointerType())
11003 return;
11004
11005 S.Diag(Loc, diag::warn_null_in_comparison_operation)
11006 << LHSNull /* LHS is NULL */ << NonNullType
11007 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11008}
11009
11011 SourceLocation OpLoc) {
11012 // If the divisor is real, then this is real/real or complex/real division.
11013 // Either way there can be no precision loss.
11014 auto *CT = DivisorTy->getAs<ComplexType>();
11015 if (!CT)
11016 return;
11017
11018 QualType ElementType = CT->getElementType().getCanonicalType();
11019 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11021 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11022 return;
11023
11024 ASTContext &Ctx = S.getASTContext();
11025 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11026 const llvm::fltSemantics &ElementTypeSemantics =
11027 Ctx.getFloatTypeSemantics(ElementType);
11028 const llvm::fltSemantics &HigherElementTypeSemantics =
11029 Ctx.getFloatTypeSemantics(HigherElementType);
11030
11031 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11032 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11033 (HigherElementType == Ctx.LongDoubleTy &&
11034 !Ctx.getTargetInfo().hasLongDoubleType())) {
11035 // Retain the location of the first use of higher precision type.
11038 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11039 if (Type == HigherElementType) {
11040 Num++;
11041 return;
11042 }
11043 }
11044 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
11045 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
11046 }
11047}
11048
11050 SourceLocation Loc) {
11051 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
11052 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
11053 if (!LUE || !RUE)
11054 return;
11055 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11056 RUE->getKind() != UETT_SizeOf)
11057 return;
11058
11059 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11060 QualType LHSTy = LHSArg->getType();
11061 QualType RHSTy;
11062
11063 if (RUE->isArgumentType())
11064 RHSTy = RUE->getArgumentType().getNonReferenceType();
11065 else
11066 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11067
11068 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11069 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11070 return;
11071
11072 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11073 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11074 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11075 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11076 << LHSArgDecl;
11077 }
11078 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11079 QualType ArrayElemTy = ArrayTy->getElementType();
11080 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11081 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11082 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11083 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11084 return;
11085 S.Diag(Loc, diag::warn_division_sizeof_array)
11086 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11087 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11088 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11089 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11090 << LHSArgDecl;
11091 }
11092
11093 S.Diag(Loc, diag::note_precedence_silence) << RHS;
11094 }
11095}
11096
11098 ExprResult &RHS,
11099 SourceLocation Loc, bool IsDiv) {
11100 // Check for division/remainder by zero.
11101 Expr::EvalResult RHSValue;
11102 if (!RHS.get()->isValueDependent() &&
11103 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11104 RHSValue.Val.getInt() == 0)
11105 S.DiagRuntimeBehavior(Loc, RHS.get(),
11106 S.PDiag(diag::warn_remainder_division_by_zero)
11107 << IsDiv << RHS.get()->getSourceRange());
11108}
11109
11110static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11111 const ExprResult &LHS, const ExprResult &RHS,
11112 BinaryOperatorKind Opc) {
11113 if (!LHS.isUsable() || !RHS.isUsable())
11114 return;
11115 const Expr *LHSExpr = LHS.get();
11116 const Expr *RHSExpr = RHS.get();
11117 const QualType LHSType = LHSExpr->getType();
11118 const QualType RHSType = RHSExpr->getType();
11119 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11120 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11121 if (!LHSIsScoped && !RHSIsScoped)
11122 return;
11123 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11124 return;
11125 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11126 return;
11127 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11128 return;
11129 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11130 SourceLocation BeginLoc = expr->getBeginLoc();
11131 QualType IntType = type->castAs<EnumType>()
11132 ->getDecl()
11133 ->getDefinitionOrSelf()
11134 ->getIntegerType();
11135 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11136 S.Diag(BeginLoc, diag::note_no_implicit_conversion_for_scoped_enum)
11137 << FixItHint::CreateInsertion(BeginLoc, InsertionString)
11138 << FixItHint::CreateInsertion(expr->getEndLoc(), ")");
11139 };
11140 if (LHSIsScoped) {
11141 DiagnosticHelper(LHSExpr, LHSType);
11142 }
11143 if (RHSIsScoped) {
11144 DiagnosticHelper(RHSExpr, RHSType);
11145 }
11146}
11147
11149 SourceLocation Loc,
11150 BinaryOperatorKind Opc) {
11151 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11152 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11153
11154 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11155
11156 QualType LHSTy = LHS.get()->getType();
11157 QualType RHSTy = RHS.get()->getType();
11158 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11159 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11160 /*AllowBothBool*/ getLangOpts().AltiVec,
11161 /*AllowBoolConversions*/ false,
11162 /*AllowBooleanOperation*/ false,
11163 /*ReportInvalid*/ true);
11164 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11165 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11167 if (!IsDiv &&
11168 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11169 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11170 // For division, only matrix-by-scalar is supported. Other combinations with
11171 // matrix types are invalid.
11172 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11173 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11174
11176 LHS, RHS, Loc,
11178 if (LHS.isInvalid() || RHS.isInvalid())
11179 return QualType();
11180
11181 if (compType.isNull() || !compType->isArithmeticType()) {
11182 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11183 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11184 return ResultTy;
11185 }
11186 if (IsDiv) {
11187 DetectPrecisionLossInComplexDivision(*this, RHS.get()->getType(), Loc);
11188 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11189 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11190 }
11191 return compType;
11192}
11193
11195 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11196 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11197
11198 // Note: This check is here to simplify the double exclusions of
11199 // scalar and vector HLSL checks. No getLangOpts().HLSL
11200 // is needed since all languages exlcude doubles.
11201 if (LHS.get()->getType()->isDoubleType() ||
11202 RHS.get()->getType()->isDoubleType() ||
11203 (LHS.get()->getType()->isVectorType() && LHS.get()
11204 ->getType()
11205 ->getAs<VectorType>()
11206 ->getElementType()
11207 ->isDoubleType()) ||
11208 (RHS.get()->getType()->isVectorType() && RHS.get()
11209 ->getType()
11210 ->getAs<VectorType>()
11211 ->getElementType()
11212 ->isDoubleType()))
11213 return InvalidOperands(Loc, LHS, RHS);
11214
11215 if (LHS.get()->getType()->isVectorType() ||
11216 RHS.get()->getType()->isVectorType()) {
11217 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11218 RHS.get()->getType()->hasIntegerRepresentation()) ||
11219 (getLangOpts().HLSL &&
11220 (LHS.get()->getType()->hasFloatingRepresentation() ||
11222 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11223 /*AllowBothBool*/ getLangOpts().AltiVec,
11224 /*AllowBoolConversions*/ false,
11225 /*AllowBooleanOperation*/ false,
11226 /*ReportInvalid*/ true);
11227 return InvalidOperands(Loc, LHS, RHS);
11228 }
11229
11230 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11231 RHS.get()->getType()->isSveVLSBuiltinType()) {
11232 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11234 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11236
11237 return InvalidOperands(Loc, LHS, RHS);
11238 }
11239
11241 LHS, RHS, Loc,
11243 if (LHS.isInvalid() || RHS.isInvalid())
11244 return QualType();
11245
11246 if (compType.isNull() ||
11247 (!compType->isIntegerType() &&
11248 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11249 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11250 diagnoseScopedEnums(*this, Loc, LHS, RHS,
11251 IsCompAssign ? BO_RemAssign : BO_Rem);
11252 return ResultTy;
11253 }
11254 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11255 return compType;
11256}
11257
11258/// Diagnose invalid arithmetic on two void pointers.
11260 Expr *LHSExpr, Expr *RHSExpr) {
11261 S.Diag(Loc, S.getLangOpts().CPlusPlus
11262 ? diag::err_typecheck_pointer_arith_void_type
11263 : diag::ext_gnu_void_ptr)
11264 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11265 << RHSExpr->getSourceRange();
11266}
11267
11268/// Diagnose invalid arithmetic on a void pointer.
11270 Expr *Pointer) {
11271 S.Diag(Loc, S.getLangOpts().CPlusPlus
11272 ? diag::err_typecheck_pointer_arith_void_type
11273 : diag::ext_gnu_void_ptr)
11274 << 0 /* one pointer */ << Pointer->getSourceRange();
11275}
11276
11277/// Diagnose invalid arithmetic on a null pointer.
11278///
11279/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11280/// idiom, which we recognize as a GNU extension.
11281///
11283 Expr *Pointer, bool IsGNUIdiom) {
11284 if (IsGNUIdiom)
11285 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11286 << Pointer->getSourceRange();
11287 else
11288 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11289 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11290}
11291
11292/// Diagnose invalid subraction on a null pointer.
11293///
11295 Expr *Pointer, bool BothNull) {
11296 // Null - null is valid in C++ [expr.add]p7
11297 if (BothNull && S.getLangOpts().CPlusPlus)
11298 return;
11299
11300 // Is this s a macro from a system header?
11302 return;
11303
11305 S.PDiag(diag::warn_pointer_sub_null_ptr)
11306 << S.getLangOpts().CPlusPlus
11307 << Pointer->getSourceRange());
11308}
11309
11310/// Diagnose invalid arithmetic on two function pointers.
11312 Expr *LHS, Expr *RHS) {
11313 assert(LHS->getType()->isAnyPointerType());
11314 assert(RHS->getType()->isAnyPointerType());
11315 S.Diag(Loc, S.getLangOpts().CPlusPlus
11316 ? diag::err_typecheck_pointer_arith_function_type
11317 : diag::ext_gnu_ptr_func_arith)
11318 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11319 // We only show the second type if it differs from the first.
11321 RHS->getType())
11322 << RHS->getType()->getPointeeType()
11323 << LHS->getSourceRange() << RHS->getSourceRange();
11324}
11325
11326/// Diagnose invalid arithmetic on a function pointer.
11328 Expr *Pointer) {
11329 assert(Pointer->getType()->isAnyPointerType());
11330 S.Diag(Loc, S.getLangOpts().CPlusPlus
11331 ? diag::err_typecheck_pointer_arith_function_type
11332 : diag::ext_gnu_ptr_func_arith)
11333 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11334 << 0 /* one pointer, so only one type */
11335 << Pointer->getSourceRange();
11336}
11337
11338/// Emit error if Operand is incomplete pointer type
11339///
11340/// \returns True if pointer has incomplete type
11342 Expr *Operand) {
11343 QualType ResType = Operand->getType();
11344 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11345 ResType = ResAtomicType->getValueType();
11346
11347 assert(ResType->isAnyPointerType());
11348 QualType PointeeTy = ResType->getPointeeType();
11349 return S.RequireCompleteSizedType(
11350 Loc, PointeeTy,
11351 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11352 Operand->getSourceRange());
11353}
11354
11355/// Check the validity of an arithmetic pointer operand.
11356///
11357/// If the operand has pointer type, this code will check for pointer types
11358/// which are invalid in arithmetic operations. These will be diagnosed
11359/// appropriately, including whether or not the use is supported as an
11360/// extension.
11361///
11362/// \returns True when the operand is valid to use (even if as an extension).
11364 Expr *Operand) {
11365 QualType ResType = Operand->getType();
11366 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11367 ResType = ResAtomicType->getValueType();
11368
11369 if (!ResType->isAnyPointerType()) return true;
11370
11371 QualType PointeeTy = ResType->getPointeeType();
11372 if (PointeeTy->isVoidType()) {
11373 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11374 return !S.getLangOpts().CPlusPlus;
11375 }
11376 if (PointeeTy->isFunctionType()) {
11377 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11378 return !S.getLangOpts().CPlusPlus;
11379 }
11380
11381 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11382
11383 return true;
11384}
11385
11386/// Check the validity of a binary arithmetic operation w.r.t. pointer
11387/// operands.
11388///
11389/// This routine will diagnose any invalid arithmetic on pointer operands much
11390/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11391/// for emitting a single diagnostic even for operations where both LHS and RHS
11392/// are (potentially problematic) pointers.
11393///
11394/// \returns True when the operand is valid to use (even if as an extension).
11396 Expr *LHSExpr, Expr *RHSExpr) {
11397 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11398 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11399 if (!isLHSPointer && !isRHSPointer) return true;
11400
11401 QualType LHSPointeeTy, RHSPointeeTy;
11402 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11403 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11404
11405 // if both are pointers check if operation is valid wrt address spaces
11406 if (isLHSPointer && isRHSPointer) {
11407 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
11408 S.getASTContext())) {
11409 S.Diag(Loc,
11410 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11411 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11412 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11413 return false;
11414 }
11415 }
11416
11417 // Check for arithmetic on pointers to incomplete types.
11418 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11419 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11420 if (isLHSVoidPtr || isRHSVoidPtr) {
11421 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11422 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11423 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11424
11425 return !S.getLangOpts().CPlusPlus;
11426 }
11427
11428 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11429 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11430 if (isLHSFuncPtr || isRHSFuncPtr) {
11431 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11432 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11433 RHSExpr);
11434 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11435
11436 return !S.getLangOpts().CPlusPlus;
11437 }
11438
11439 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11440 return false;
11441 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11442 return false;
11443
11444 return true;
11445}
11446
11447/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11448/// literal.
11450 Expr *LHSExpr, Expr *RHSExpr) {
11451 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11452 Expr* IndexExpr = RHSExpr;
11453 if (!StrExpr) {
11454 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11455 IndexExpr = LHSExpr;
11456 }
11457
11458 bool IsStringPlusInt = StrExpr &&
11460 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11461 return;
11462
11463 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11464 Self.Diag(OpLoc, diag::warn_string_plus_int)
11465 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11466
11467 // Only print a fixit for "str" + int, not for int + "str".
11468 if (IndexExpr == RHSExpr) {
11469 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11470 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11471 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11473 << FixItHint::CreateInsertion(EndLoc, "]");
11474 } else
11475 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11476}
11477
11478/// Emit a warning when adding a char literal to a string.
11480 Expr *LHSExpr, Expr *RHSExpr) {
11481 const Expr *StringRefExpr = LHSExpr;
11482 const CharacterLiteral *CharExpr =
11483 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11484
11485 if (!CharExpr) {
11486 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11487 StringRefExpr = RHSExpr;
11488 }
11489
11490 if (!CharExpr || !StringRefExpr)
11491 return;
11492
11493 const QualType StringType = StringRefExpr->getType();
11494
11495 // Return if not a PointerType.
11496 if (!StringType->isAnyPointerType())
11497 return;
11498
11499 // Return if not a CharacterType.
11500 if (!StringType->getPointeeType()->isAnyCharacterType())
11501 return;
11502
11503 ASTContext &Ctx = Self.getASTContext();
11504 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11505
11506 const QualType CharType = CharExpr->getType();
11507 if (!CharType->isAnyCharacterType() &&
11508 CharType->isIntegerType() &&
11509 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11510 Self.Diag(OpLoc, diag::warn_string_plus_char)
11511 << DiagRange << Ctx.CharTy;
11512 } else {
11513 Self.Diag(OpLoc, diag::warn_string_plus_char)
11514 << DiagRange << CharExpr->getType();
11515 }
11516
11517 // Only print a fixit for str + char, not for char + str.
11518 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11519 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11520 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11521 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11523 << FixItHint::CreateInsertion(EndLoc, "]");
11524 } else {
11525 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11526 }
11527}
11528
11529/// Emit error when two pointers are incompatible.
11531 Expr *LHSExpr, Expr *RHSExpr) {
11532 assert(LHSExpr->getType()->isAnyPointerType());
11533 assert(RHSExpr->getType()->isAnyPointerType());
11534 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11535 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11536 << RHSExpr->getSourceRange();
11537}
11538
11539// C99 6.5.6
11542 QualType* CompLHSTy) {
11543 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11544
11545 if (LHS.get()->getType()->isVectorType() ||
11546 RHS.get()->getType()->isVectorType()) {
11547 QualType compType =
11548 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11549 /*AllowBothBool*/ getLangOpts().AltiVec,
11550 /*AllowBoolConversions*/ getLangOpts().ZVector,
11551 /*AllowBooleanOperation*/ false,
11552 /*ReportInvalid*/ true);
11553 if (CompLHSTy) *CompLHSTy = compType;
11554 return compType;
11555 }
11556
11557 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11558 RHS.get()->getType()->isSveVLSBuiltinType()) {
11559 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11561 if (CompLHSTy)
11562 *CompLHSTy = compType;
11563 return compType;
11564 }
11565
11566 if (LHS.get()->getType()->isConstantMatrixType() ||
11567 RHS.get()->getType()->isConstantMatrixType()) {
11568 QualType compType =
11569 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11570 if (CompLHSTy)
11571 *CompLHSTy = compType;
11572 return compType;
11573 }
11574
11576 LHS, RHS, Loc,
11578 if (LHS.isInvalid() || RHS.isInvalid())
11579 return QualType();
11580
11581 // Diagnose "string literal" '+' int and string '+' "char literal".
11582 if (Opc == BO_Add) {
11583 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11584 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11585 }
11586
11587 // handle the common case first (both operands are arithmetic).
11588 if (!compType.isNull() && compType->isArithmeticType()) {
11589 if (CompLHSTy) *CompLHSTy = compType;
11590 return compType;
11591 }
11592
11593 // Type-checking. Ultimately the pointer's going to be in PExp;
11594 // note that we bias towards the LHS being the pointer.
11595 Expr *PExp = LHS.get(), *IExp = RHS.get();
11596
11597 bool isObjCPointer;
11598 if (PExp->getType()->isPointerType()) {
11599 isObjCPointer = false;
11600 } else if (PExp->getType()->isObjCObjectPointerType()) {
11601 isObjCPointer = true;
11602 } else {
11603 std::swap(PExp, IExp);
11604 if (PExp->getType()->isPointerType()) {
11605 isObjCPointer = false;
11606 } else if (PExp->getType()->isObjCObjectPointerType()) {
11607 isObjCPointer = true;
11608 } else {
11609 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11610 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11611 return ResultTy;
11612 }
11613 }
11614 assert(PExp->getType()->isAnyPointerType());
11615
11616 if (!IExp->getType()->isIntegerType())
11617 return InvalidOperands(Loc, LHS, RHS);
11618
11619 // Adding to a null pointer results in undefined behavior.
11622 // In C++ adding zero to a null pointer is defined.
11623 Expr::EvalResult KnownVal;
11624 if (!getLangOpts().CPlusPlus ||
11625 (!IExp->isValueDependent() &&
11626 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11627 KnownVal.Val.getInt() != 0))) {
11628 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11630 Context, BO_Add, PExp, IExp);
11631 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11632 }
11633 }
11634
11635 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11636 return QualType();
11637
11638 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11639 return QualType();
11640
11641 // Arithmetic on label addresses is normally allowed, except when we add
11642 // a ptrauth signature to the addresses.
11643 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11644 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11645 << /*addition*/ 1;
11646 return QualType();
11647 }
11648
11649 // Check array bounds for pointer arithemtic
11650 CheckArrayAccess(PExp, IExp);
11651
11652 if (CompLHSTy) {
11653 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11654 if (LHSTy.isNull()) {
11655 LHSTy = LHS.get()->getType();
11656 if (Context.isPromotableIntegerType(LHSTy))
11657 LHSTy = Context.getPromotedIntegerType(LHSTy);
11658 }
11659 *CompLHSTy = LHSTy;
11660 }
11661
11662 return PExp->getType();
11663}
11664
11665// C99 6.5.6
11667 SourceLocation Loc,
11669 QualType *CompLHSTy) {
11670 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11671
11672 if (LHS.get()->getType()->isVectorType() ||
11673 RHS.get()->getType()->isVectorType()) {
11674 QualType compType =
11675 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11676 /*AllowBothBool*/ getLangOpts().AltiVec,
11677 /*AllowBoolConversions*/ getLangOpts().ZVector,
11678 /*AllowBooleanOperation*/ false,
11679 /*ReportInvalid*/ true);
11680 if (CompLHSTy) *CompLHSTy = compType;
11681 return compType;
11682 }
11683
11684 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11685 RHS.get()->getType()->isSveVLSBuiltinType()) {
11686 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11688 if (CompLHSTy)
11689 *CompLHSTy = compType;
11690 return compType;
11691 }
11692
11693 if (LHS.get()->getType()->isConstantMatrixType() ||
11694 RHS.get()->getType()->isConstantMatrixType()) {
11695 QualType compType =
11696 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11697 if (CompLHSTy)
11698 *CompLHSTy = compType;
11699 return compType;
11700 }
11701
11703 LHS, RHS, Loc,
11705 if (LHS.isInvalid() || RHS.isInvalid())
11706 return QualType();
11707
11708 // Enforce type constraints: C99 6.5.6p3.
11709
11710 // Handle the common case first (both operands are arithmetic).
11711 if (!compType.isNull() && compType->isArithmeticType()) {
11712 if (CompLHSTy) *CompLHSTy = compType;
11713 return compType;
11714 }
11715
11716 // Either ptr - int or ptr - ptr.
11717 if (LHS.get()->getType()->isAnyPointerType()) {
11718 QualType lpointee = LHS.get()->getType()->getPointeeType();
11719
11720 // Diagnose bad cases where we step over interface counts.
11721 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11722 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11723 return QualType();
11724
11725 // Arithmetic on label addresses is normally allowed, except when we add
11726 // a ptrauth signature to the addresses.
11727 if (isa<AddrLabelExpr>(LHS.get()) &&
11728 getLangOpts().PointerAuthIndirectGotos) {
11729 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11730 << /*subtraction*/ 0;
11731 return QualType();
11732 }
11733
11734 // The result type of a pointer-int computation is the pointer type.
11735 if (RHS.get()->getType()->isIntegerType()) {
11736 // Subtracting from a null pointer should produce a warning.
11737 // The last argument to the diagnose call says this doesn't match the
11738 // GNU int-to-pointer idiom.
11741 // In C++ adding zero to a null pointer is defined.
11742 Expr::EvalResult KnownVal;
11743 if (!getLangOpts().CPlusPlus ||
11744 (!RHS.get()->isValueDependent() &&
11745 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11746 KnownVal.Val.getInt() != 0))) {
11747 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11748 }
11749 }
11750
11751 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11752 return QualType();
11753
11754 // Check array bounds for pointer arithemtic
11755 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11756 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11757
11758 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11759 return LHS.get()->getType();
11760 }
11761
11762 // Handle pointer-pointer subtractions.
11763 if (const PointerType *RHSPTy
11764 = RHS.get()->getType()->getAs<PointerType>()) {
11765 QualType rpointee = RHSPTy->getPointeeType();
11766
11767 if (getLangOpts().CPlusPlus) {
11768 // Pointee types must be the same: C++ [expr.add]
11769 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11770 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11771 }
11772 } else {
11773 // Pointee types must be compatible C99 6.5.6p3
11774 if (!Context.typesAreCompatible(
11775 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11776 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11777 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11778 return QualType();
11779 }
11780 }
11781
11783 LHS.get(), RHS.get()))
11784 return QualType();
11785
11786 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11788 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11790
11791 // Subtracting nullptr or from nullptr is suspect
11792 if (LHSIsNullPtr)
11793 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11794 if (RHSIsNullPtr)
11795 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11796
11797 // The pointee type may have zero size. As an extension, a structure or
11798 // union may have zero size or an array may have zero length. In this
11799 // case subtraction does not make sense.
11800 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11801 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11802 if (ElementSize.isZero()) {
11803 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11804 << rpointee.getUnqualifiedType()
11805 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11806 }
11807 }
11808
11809 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11810 return Context.getPointerDiffType();
11811 }
11812 }
11813
11814 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11815 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11816 return ResultTy;
11817}
11818
11820 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11821 return ET->getDecl()->isScoped();
11822 return false;
11823}
11824
11827 QualType LHSType) {
11828 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11829 // so skip remaining warnings as we don't want to modify values within Sema.
11830 if (S.getLangOpts().OpenCL)
11831 return;
11832
11833 if (Opc == BO_Shr &&
11835 S.Diag(Loc, diag::warn_shift_bool) << LHS.get()->getSourceRange();
11836
11837 // Check right/shifter operand
11838 Expr::EvalResult RHSResult;
11839 if (RHS.get()->isValueDependent() ||
11840 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11841 return;
11842 llvm::APSInt Right = RHSResult.Val.getInt();
11843
11844 if (Right.isNegative()) {
11845 S.DiagRuntimeBehavior(Loc, RHS.get(),
11846 S.PDiag(diag::warn_shift_negative)
11847 << RHS.get()->getSourceRange());
11848 return;
11849 }
11850
11851 QualType LHSExprType = LHS.get()->getType();
11852 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11853 if (LHSExprType->isBitIntType())
11854 LeftSize = S.Context.getIntWidth(LHSExprType);
11855 else if (LHSExprType->isFixedPointType()) {
11856 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11857 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11858 }
11859 if (Right.uge(LeftSize)) {
11860 S.DiagRuntimeBehavior(Loc, RHS.get(),
11861 S.PDiag(diag::warn_shift_gt_typewidth)
11862 << RHS.get()->getSourceRange());
11863 return;
11864 }
11865
11866 // FIXME: We probably need to handle fixed point types specially here.
11867 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11868 return;
11869
11870 // When left shifting an ICE which is signed, we can check for overflow which
11871 // according to C++ standards prior to C++2a has undefined behavior
11872 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11873 // more than the maximum value representable in the result type, so never
11874 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11875 // expression is still probably a bug.)
11876 Expr::EvalResult LHSResult;
11877 if (LHS.get()->isValueDependent() ||
11879 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11880 return;
11881 llvm::APSInt Left = LHSResult.Val.getInt();
11882
11883 // Don't warn if signed overflow is defined, then all the rest of the
11884 // diagnostics will not be triggered because the behavior is defined.
11885 // Also don't warn in C++20 mode (and newer), as signed left shifts
11886 // always wrap and never overflow.
11887 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11888 return;
11889
11890 // If LHS does not have a non-negative value then, the
11891 // behavior is undefined before C++2a. Warn about it.
11892 if (Left.isNegative()) {
11893 S.DiagRuntimeBehavior(Loc, LHS.get(),
11894 S.PDiag(diag::warn_shift_lhs_negative)
11895 << LHS.get()->getSourceRange());
11896 return;
11897 }
11898
11899 llvm::APInt ResultBits =
11900 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11901 if (ResultBits.ule(LeftSize))
11902 return;
11903 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11904 Result = Result.shl(Right);
11905
11906 // Print the bit representation of the signed integer as an unsigned
11907 // hexadecimal number.
11908 SmallString<40> HexResult;
11909 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11910
11911 // If we are only missing a sign bit, this is less likely to result in actual
11912 // bugs -- if the result is cast back to an unsigned type, it will have the
11913 // expected value. Thus we place this behind a different warning that can be
11914 // turned off separately if needed.
11915 if (ResultBits - 1 == LeftSize) {
11916 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11917 << HexResult << LHSType
11918 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11919 return;
11920 }
11921
11922 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11923 << HexResult.str() << Result.getSignificantBits() << LHSType
11924 << Left.getBitWidth() << LHS.get()->getSourceRange()
11925 << RHS.get()->getSourceRange();
11926}
11927
11928/// Return the resulting type when a vector is shifted
11929/// by a scalar or vector shift amount.
11931 SourceLocation Loc, bool IsCompAssign) {
11932 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11933 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11934 !LHS.get()->getType()->isVectorType()) {
11935 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11936 << RHS.get()->getType() << LHS.get()->getType()
11937 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11938 return QualType();
11939 }
11940
11941 if (!IsCompAssign) {
11942 LHS = S.UsualUnaryConversions(LHS.get());
11943 if (LHS.isInvalid()) return QualType();
11944 }
11945
11946 RHS = S.UsualUnaryConversions(RHS.get());
11947 if (RHS.isInvalid()) return QualType();
11948
11949 QualType LHSType = LHS.get()->getType();
11950 // Note that LHS might be a scalar because the routine calls not only in
11951 // OpenCL case.
11952 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11953 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11954
11955 // Note that RHS might not be a vector.
11956 QualType RHSType = RHS.get()->getType();
11957 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11958 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11959
11960 // Do not allow shifts for boolean vectors.
11961 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11962 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11963 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11964 << LHS.get()->getType() << RHS.get()->getType()
11965 << LHS.get()->getSourceRange();
11966 return QualType();
11967 }
11968
11969 // The operands need to be integers.
11970 if (!LHSEleType->isIntegerType()) {
11971 S.Diag(Loc, diag::err_typecheck_expect_int)
11972 << LHS.get()->getType() << LHS.get()->getSourceRange();
11973 return QualType();
11974 }
11975
11976 if (!RHSEleType->isIntegerType()) {
11977 S.Diag(Loc, diag::err_typecheck_expect_int)
11978 << RHS.get()->getType() << RHS.get()->getSourceRange();
11979 return QualType();
11980 }
11981
11982 if (!LHSVecTy) {
11983 assert(RHSVecTy);
11984 if (IsCompAssign)
11985 return RHSType;
11986 if (LHSEleType != RHSEleType) {
11987 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11988 LHSEleType = RHSEleType;
11989 }
11990 QualType VecTy =
11991 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11992 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11993 LHSType = VecTy;
11994 } else if (RHSVecTy) {
11995 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11996 // are applied component-wise. So if RHS is a vector, then ensure
11997 // that the number of elements is the same as LHS...
11998 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11999 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12000 << LHS.get()->getType() << RHS.get()->getType()
12001 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12002 return QualType();
12003 }
12004 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12005 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12006 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12007 if (LHSBT != RHSBT &&
12008 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
12009 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
12010 << LHS.get()->getType() << RHS.get()->getType()
12011 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12012 }
12013 }
12014 } else {
12015 // ...else expand RHS to match the number of elements in LHS.
12016 QualType VecTy =
12017 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
12018 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12019 }
12020
12021 return LHSType;
12022}
12023
12025 ExprResult &RHS, SourceLocation Loc,
12026 bool IsCompAssign) {
12027 if (!IsCompAssign) {
12028 LHS = S.UsualUnaryConversions(LHS.get());
12029 if (LHS.isInvalid())
12030 return QualType();
12031 }
12032
12033 RHS = S.UsualUnaryConversions(RHS.get());
12034 if (RHS.isInvalid())
12035 return QualType();
12036
12037 QualType LHSType = LHS.get()->getType();
12038 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12039 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12040 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
12041 : LHSType;
12042
12043 // Note that RHS might not be a vector
12044 QualType RHSType = RHS.get()->getType();
12045 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12046 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12047 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
12048 : RHSType;
12049
12050 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12051 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12052 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12053 << LHSType << RHSType << LHS.get()->getSourceRange();
12054 return QualType();
12055 }
12056
12057 if (!LHSEleType->isIntegerType()) {
12058 S.Diag(Loc, diag::err_typecheck_expect_int)
12059 << LHS.get()->getType() << LHS.get()->getSourceRange();
12060 return QualType();
12061 }
12062
12063 if (!RHSEleType->isIntegerType()) {
12064 S.Diag(Loc, diag::err_typecheck_expect_int)
12065 << RHS.get()->getType() << RHS.get()->getSourceRange();
12066 return QualType();
12067 }
12068
12069 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12070 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
12071 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
12072 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12073 << LHSType << RHSType << LHS.get()->getSourceRange()
12074 << RHS.get()->getSourceRange();
12075 return QualType();
12076 }
12077
12078 if (!LHSType->isSveVLSBuiltinType()) {
12079 assert(RHSType->isSveVLSBuiltinType());
12080 if (IsCompAssign)
12081 return RHSType;
12082 if (LHSEleType != RHSEleType) {
12083 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
12084 LHSEleType = RHSEleType;
12085 }
12086 const llvm::ElementCount VecSize =
12087 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
12088 QualType VecTy =
12089 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
12090 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
12091 LHSType = VecTy;
12092 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12093 if (S.Context.getTypeSize(RHSBuiltinTy) !=
12094 S.Context.getTypeSize(LHSBuiltinTy)) {
12095 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12096 << LHSType << RHSType << LHS.get()->getSourceRange()
12097 << RHS.get()->getSourceRange();
12098 return QualType();
12099 }
12100 } else {
12101 const llvm::ElementCount VecSize =
12102 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
12103 if (LHSEleType != RHSEleType) {
12104 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
12105 RHSEleType = LHSEleType;
12106 }
12107 QualType VecTy =
12108 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
12109 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12110 }
12111
12112 return LHSType;
12113}
12114
12115// C99 6.5.7
12118 bool IsCompAssign) {
12119 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12120
12121 // Vector shifts promote their scalar inputs to vector type.
12122 if (LHS.get()->getType()->isVectorType() ||
12123 RHS.get()->getType()->isVectorType()) {
12124 if (LangOpts.ZVector) {
12125 // The shift operators for the z vector extensions work basically
12126 // like general shifts, except that neither the LHS nor the RHS is
12127 // allowed to be a "vector bool".
12128 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12129 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12130 return InvalidOperands(Loc, LHS, RHS);
12131 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12132 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12133 return InvalidOperands(Loc, LHS, RHS);
12134 }
12135 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12136 }
12137
12138 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12139 RHS.get()->getType()->isSveVLSBuiltinType())
12140 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12141
12142 // Shifts don't perform usual arithmetic conversions, they just do integer
12143 // promotions on each operand. C99 6.5.7p3
12144
12145 // For the LHS, do usual unary conversions, but then reset them away
12146 // if this is a compound assignment.
12147 ExprResult OldLHS = LHS;
12148 LHS = UsualUnaryConversions(LHS.get());
12149 if (LHS.isInvalid())
12150 return QualType();
12151 QualType LHSType = LHS.get()->getType();
12152 if (IsCompAssign) LHS = OldLHS;
12153
12154 // The RHS is simpler.
12155 RHS = UsualUnaryConversions(RHS.get());
12156 if (RHS.isInvalid())
12157 return QualType();
12158 QualType RHSType = RHS.get()->getType();
12159
12160 // C99 6.5.7p2: Each of the operands shall have integer type.
12161 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12162 if ((!LHSType->isFixedPointOrIntegerType() &&
12163 !LHSType->hasIntegerRepresentation()) ||
12164 !RHSType->hasIntegerRepresentation()) {
12165 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12166 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
12167 return ResultTy;
12168 }
12169
12170 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12171
12172 // "The type of the result is that of the promoted left operand."
12173 return LHSType;
12174}
12175
12176/// Diagnose bad pointer comparisons.
12178 ExprResult &LHS, ExprResult &RHS,
12179 bool IsError) {
12180 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12181 : diag::ext_typecheck_comparison_of_distinct_pointers)
12182 << LHS.get()->getType() << RHS.get()->getType()
12183 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12184}
12185
12186/// Returns false if the pointers are converted to a composite type,
12187/// true otherwise.
12189 ExprResult &LHS, ExprResult &RHS) {
12190 // C++ [expr.rel]p2:
12191 // [...] Pointer conversions (4.10) and qualification
12192 // conversions (4.4) are performed on pointer operands (or on
12193 // a pointer operand and a null pointer constant) to bring
12194 // them to their composite pointer type. [...]
12195 //
12196 // C++ [expr.eq]p1 uses the same notion for (in)equality
12197 // comparisons of pointers.
12198
12199 QualType LHSType = LHS.get()->getType();
12200 QualType RHSType = RHS.get()->getType();
12201 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12202 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12203
12204 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12205 if (T.isNull()) {
12206 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12207 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12208 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12209 else
12210 S.InvalidOperands(Loc, LHS, RHS);
12211 return true;
12212 }
12213
12214 return false;
12215}
12216
12218 ExprResult &LHS,
12219 ExprResult &RHS,
12220 bool IsError) {
12221 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12222 : diag::ext_typecheck_comparison_of_fptr_to_void)
12223 << LHS.get()->getType() << RHS.get()->getType()
12224 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12225}
12226
12228 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12229 case Stmt::ObjCArrayLiteralClass:
12230 case Stmt::ObjCDictionaryLiteralClass:
12231 case Stmt::ObjCStringLiteralClass:
12232 case Stmt::ObjCBoxedExprClass:
12233 return true;
12234 default:
12235 // Note that ObjCBoolLiteral is NOT an object literal!
12236 return false;
12237 }
12238}
12239
12240static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12243
12244 // If this is not actually an Objective-C object, bail out.
12245 if (!Type)
12246 return false;
12247
12248 // Get the LHS object's interface type.
12249 QualType InterfaceType = Type->getPointeeType();
12250
12251 // If the RHS isn't an Objective-C object, bail out.
12252 if (!RHS->getType()->isObjCObjectPointerType())
12253 return false;
12254
12255 // Try to find the -isEqual: method.
12256 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12257 ObjCMethodDecl *Method =
12258 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
12259 /*IsInstance=*/true);
12260 if (!Method) {
12261 if (Type->isObjCIdType()) {
12262 // For 'id', just check the global pool.
12263 Method =
12265 /*receiverId=*/true);
12266 } else {
12267 // Check protocols.
12268 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
12269 /*IsInstance=*/true);
12270 }
12271 }
12272
12273 if (!Method)
12274 return false;
12275
12276 QualType T = Method->parameters()[0]->getType();
12277 if (!T->isObjCObjectPointerType())
12278 return false;
12279
12280 QualType R = Method->getReturnType();
12281 if (!R->isScalarType())
12282 return false;
12283
12284 return true;
12285}
12286
12288 ExprResult &LHS, ExprResult &RHS,
12290 Expr *Literal;
12291 Expr *Other;
12292 if (isObjCObjectLiteral(LHS)) {
12293 Literal = LHS.get();
12294 Other = RHS.get();
12295 } else {
12296 Literal = RHS.get();
12297 Other = LHS.get();
12298 }
12299
12300 // Don't warn on comparisons against nil.
12301 Other = Other->IgnoreParenCasts();
12302 if (Other->isNullPointerConstant(S.getASTContext(),
12304 return;
12305
12306 // This should be kept in sync with warn_objc_literal_comparison.
12307 // LK_String should always be after the other literals, since it has its own
12308 // warning flag.
12309 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
12310 assert(LiteralKind != SemaObjC::LK_Block);
12311 if (LiteralKind == SemaObjC::LK_None) {
12312 llvm_unreachable("Unknown Objective-C object literal kind");
12313 }
12314
12315 if (LiteralKind == SemaObjC::LK_String)
12316 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12317 << Literal->getSourceRange();
12318 else
12319 S.Diag(Loc, diag::warn_objc_literal_comparison)
12320 << LiteralKind << Literal->getSourceRange();
12321
12323 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12324 SourceLocation Start = LHS.get()->getBeginLoc();
12326 CharSourceRange OpRange =
12328
12329 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12330 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12331 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12332 << FixItHint::CreateInsertion(End, "]");
12333 }
12334}
12335
12336/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12338 ExprResult &RHS, SourceLocation Loc,
12339 BinaryOperatorKind Opc) {
12340 // Check that left hand side is !something.
12341 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12342 if (!UO || UO->getOpcode() != UO_LNot) return;
12343
12344 // Only check if the right hand side is non-bool arithmetic type.
12345 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12346
12347 // Make sure that the something in !something is not bool.
12348 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12349 if (SubExpr->isKnownToHaveBooleanValue()) return;
12350
12351 // Emit warning.
12352 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12353 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12354 << Loc << IsBitwiseOp;
12355
12356 // First note suggest !(x < y)
12357 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12358 SourceLocation FirstClose = RHS.get()->getEndLoc();
12359 FirstClose = S.getLocForEndOfToken(FirstClose);
12360 if (FirstClose.isInvalid())
12361 FirstOpen = SourceLocation();
12362 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12363 << IsBitwiseOp
12364 << FixItHint::CreateInsertion(FirstOpen, "(")
12365 << FixItHint::CreateInsertion(FirstClose, ")");
12366
12367 // Second note suggests (!x) < y
12368 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12369 SourceLocation SecondClose = LHS.get()->getEndLoc();
12370 SecondClose = S.getLocForEndOfToken(SecondClose);
12371 if (SecondClose.isInvalid())
12372 SecondOpen = SourceLocation();
12373 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12374 << FixItHint::CreateInsertion(SecondOpen, "(")
12375 << FixItHint::CreateInsertion(SecondClose, ")");
12376}
12377
12378// Returns true if E refers to a non-weak array.
12379static bool checkForArray(const Expr *E) {
12380 const ValueDecl *D = nullptr;
12381 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12382 D = DR->getDecl();
12383 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12384 if (Mem->isImplicitAccess())
12385 D = Mem->getMemberDecl();
12386 }
12387 if (!D)
12388 return false;
12389 return D->getType()->isArrayType() && !D->isWeak();
12390}
12391
12392/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12393/// pointer and size is an unsigned integer. Return whether the result is
12394/// always true/false.
12395static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12396 const Expr *RHS,
12397 BinaryOperatorKind Opc) {
12398 if (!LHS->getType()->isPointerType() ||
12399 S.getLangOpts().PointerOverflowDefined)
12400 return std::nullopt;
12401
12402 // Canonicalize to >= or < predicate.
12403 switch (Opc) {
12404 case BO_GE:
12405 case BO_LT:
12406 break;
12407 case BO_GT:
12408 std::swap(LHS, RHS);
12409 Opc = BO_LT;
12410 break;
12411 case BO_LE:
12412 std::swap(LHS, RHS);
12413 Opc = BO_GE;
12414 break;
12415 default:
12416 return std::nullopt;
12417 }
12418
12419 auto *BO = dyn_cast<BinaryOperator>(LHS);
12420 if (!BO || BO->getOpcode() != BO_Add)
12421 return std::nullopt;
12422
12423 Expr *Other;
12424 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
12425 Other = BO->getRHS();
12426 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
12427 Other = BO->getLHS();
12428 else
12429 return std::nullopt;
12430
12431 if (!Other->getType()->isUnsignedIntegerType())
12432 return std::nullopt;
12433
12434 return Opc == BO_GE;
12435}
12436
12437/// Diagnose some forms of syntactically-obvious tautological comparison.
12439 Expr *LHS, Expr *RHS,
12440 BinaryOperatorKind Opc) {
12441 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12442 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12443
12444 QualType LHSType = LHS->getType();
12445 QualType RHSType = RHS->getType();
12446 if (LHSType->hasFloatingRepresentation() ||
12447 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12449 return;
12450
12451 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12452 // Tautological diagnostics.
12453 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12454 return;
12455
12456 // Comparisons between two array types are ill-formed for operator<=>, so
12457 // we shouldn't emit any additional warnings about it.
12458 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12459 return;
12460
12461 // For non-floating point types, check for self-comparisons of the form
12462 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12463 // often indicate logic errors in the program.
12464 //
12465 // NOTE: Don't warn about comparison expressions resulting from macro
12466 // expansion. Also don't warn about comparisons which are only self
12467 // comparisons within a template instantiation. The warnings should catch
12468 // obvious cases in the definition of the template anyways. The idea is to
12469 // warn when the typed comparison operator will always evaluate to the same
12470 // result.
12471
12472 // Used for indexing into %select in warn_comparison_always
12473 enum {
12474 AlwaysConstant,
12475 AlwaysTrue,
12476 AlwaysFalse,
12477 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12478 };
12479
12480 // C++1a [array.comp]:
12481 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12482 // operands of array type.
12483 // C++2a [depr.array.comp]:
12484 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12485 // operands of array type are deprecated.
12486 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12487 RHSStripped->getType()->isArrayType()) {
12488 auto IsDeprArrayComparionIgnored =
12489 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
12490 auto DiagID = S.getLangOpts().CPlusPlus26
12491 ? diag::warn_array_comparison_cxx26
12492 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12493 ? diag::warn_array_comparison
12494 : diag::warn_depr_array_comparison;
12495 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12496 << LHSStripped->getType() << RHSStripped->getType();
12497 // Carry on to produce the tautological comparison warning, if this
12498 // expression is potentially-evaluated, we can resolve the array to a
12499 // non-weak declaration, and so on.
12500 }
12501
12502 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12503 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12504 unsigned Result;
12505 switch (Opc) {
12506 case BO_EQ:
12507 case BO_LE:
12508 case BO_GE:
12509 Result = AlwaysTrue;
12510 break;
12511 case BO_NE:
12512 case BO_LT:
12513 case BO_GT:
12514 Result = AlwaysFalse;
12515 break;
12516 case BO_Cmp:
12517 Result = AlwaysEqual;
12518 break;
12519 default:
12520 Result = AlwaysConstant;
12521 break;
12522 }
12523 S.DiagRuntimeBehavior(Loc, nullptr,
12524 S.PDiag(diag::warn_comparison_always)
12525 << 0 /*self-comparison*/
12526 << Result);
12527 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12528 // What is it always going to evaluate to?
12529 unsigned Result;
12530 switch (Opc) {
12531 case BO_EQ: // e.g. array1 == array2
12532 Result = AlwaysFalse;
12533 break;
12534 case BO_NE: // e.g. array1 != array2
12535 Result = AlwaysTrue;
12536 break;
12537 default: // e.g. array1 <= array2
12538 // The best we can say is 'a constant'
12539 Result = AlwaysConstant;
12540 break;
12541 }
12542 S.DiagRuntimeBehavior(Loc, nullptr,
12543 S.PDiag(diag::warn_comparison_always)
12544 << 1 /*array comparison*/
12545 << Result);
12546 } else if (std::optional<bool> Res =
12547 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12548 S.DiagRuntimeBehavior(Loc, nullptr,
12549 S.PDiag(diag::warn_comparison_always)
12550 << 2 /*pointer comparison*/
12551 << (*Res ? AlwaysTrue : AlwaysFalse));
12552 }
12553 }
12554
12555 if (isa<CastExpr>(LHSStripped))
12556 LHSStripped = LHSStripped->IgnoreParenCasts();
12557 if (isa<CastExpr>(RHSStripped))
12558 RHSStripped = RHSStripped->IgnoreParenCasts();
12559
12560 // Warn about comparisons against a string constant (unless the other
12561 // operand is null); the user probably wants string comparison function.
12562 Expr *LiteralString = nullptr;
12563 Expr *LiteralStringStripped = nullptr;
12564 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12565 !RHSStripped->isNullPointerConstant(S.Context,
12567 LiteralString = LHS;
12568 LiteralStringStripped = LHSStripped;
12569 } else if ((isa<StringLiteral>(RHSStripped) ||
12570 isa<ObjCEncodeExpr>(RHSStripped)) &&
12571 !LHSStripped->isNullPointerConstant(S.Context,
12573 LiteralString = RHS;
12574 LiteralStringStripped = RHSStripped;
12575 }
12576
12577 if (LiteralString) {
12578 S.DiagRuntimeBehavior(Loc, nullptr,
12579 S.PDiag(diag::warn_stringcompare)
12580 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12581 << LiteralString->getSourceRange());
12582 }
12583}
12584
12586 switch (CK) {
12587 default: {
12588#ifndef NDEBUG
12589 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12590 << "\n";
12591#endif
12592 llvm_unreachable("unhandled cast kind");
12593 }
12594 case CK_UserDefinedConversion:
12595 return ICK_Identity;
12596 case CK_LValueToRValue:
12597 return ICK_Lvalue_To_Rvalue;
12598 case CK_ArrayToPointerDecay:
12599 return ICK_Array_To_Pointer;
12600 case CK_FunctionToPointerDecay:
12602 case CK_IntegralCast:
12604 case CK_FloatingCast:
12606 case CK_IntegralToFloating:
12607 case CK_FloatingToIntegral:
12608 return ICK_Floating_Integral;
12609 case CK_IntegralComplexCast:
12610 case CK_FloatingComplexCast:
12611 case CK_FloatingComplexToIntegralComplex:
12612 case CK_IntegralComplexToFloatingComplex:
12614 case CK_FloatingComplexToReal:
12615 case CK_FloatingRealToComplex:
12616 case CK_IntegralComplexToReal:
12617 case CK_IntegralRealToComplex:
12618 return ICK_Complex_Real;
12619 case CK_HLSLArrayRValue:
12620 return ICK_HLSL_Array_RValue;
12621 }
12622}
12623
12625 QualType FromType,
12626 SourceLocation Loc) {
12627 // Check for a narrowing implicit conversion.
12630 SCS.setToType(0, FromType);
12631 SCS.setToType(1, ToType);
12632 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12633 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12634
12635 APValue PreNarrowingValue;
12636 QualType PreNarrowingType;
12637 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12638 PreNarrowingType,
12639 /*IgnoreFloatToIntegralConversion*/ true)) {
12641 // Implicit conversion to a narrower type, but the expression is
12642 // value-dependent so we can't tell whether it's actually narrowing.
12643 case NK_Not_Narrowing:
12644 return false;
12645
12647 // Implicit conversion to a narrower type, and the value is not a constant
12648 // expression.
12649 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12650 << /*Constant*/ 1
12651 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12652 return true;
12653
12655 // Implicit conversion to a narrower type, and the value is not a constant
12656 // expression.
12657 case NK_Type_Narrowing:
12658 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12659 << /*Constant*/ 0 << FromType << ToType;
12660 // TODO: It's not a constant expression, but what if the user intended it
12661 // to be? Can we produce notes to help them figure out why it isn't?
12662 return true;
12663 }
12664 llvm_unreachable("unhandled case in switch");
12665}
12666
12668 ExprResult &LHS,
12669 ExprResult &RHS,
12670 SourceLocation Loc) {
12671 QualType LHSType = LHS.get()->getType();
12672 QualType RHSType = RHS.get()->getType();
12673 // Dig out the original argument type and expression before implicit casts
12674 // were applied. These are the types/expressions we need to check the
12675 // [expr.spaceship] requirements against.
12676 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12677 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12678 QualType LHSStrippedType = LHSStripped.get()->getType();
12679 QualType RHSStrippedType = RHSStripped.get()->getType();
12680
12681 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12682 // other is not, the program is ill-formed.
12683 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12684 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12685 return QualType();
12686 }
12687
12688 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12689 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12690 RHSStrippedType->isEnumeralType();
12691 if (NumEnumArgs == 1) {
12692 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12693 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12694 if (OtherTy->hasFloatingRepresentation()) {
12695 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12696 return QualType();
12697 }
12698 }
12699 if (NumEnumArgs == 2) {
12700 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12701 // type E, the operator yields the result of converting the operands
12702 // to the underlying type of E and applying <=> to the converted operands.
12703 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12704 S.InvalidOperands(Loc, LHS, RHS);
12705 return QualType();
12706 }
12707 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12708 assert(IntType->isArithmeticType());
12709
12710 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12711 // promote the boolean type, and all other promotable integer types, to
12712 // avoid this.
12713 if (S.Context.isPromotableIntegerType(IntType))
12714 IntType = S.Context.getPromotedIntegerType(IntType);
12715
12716 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12717 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12718 LHSType = RHSType = IntType;
12719 }
12720
12721 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12722 // usual arithmetic conversions are applied to the operands.
12723 QualType Type =
12725 if (LHS.isInvalid() || RHS.isInvalid())
12726 return QualType();
12727 if (Type.isNull()) {
12728 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12729 diagnoseScopedEnums(S, Loc, LHS, RHS, BO_Cmp);
12730 return ResultTy;
12731 }
12732
12733 std::optional<ComparisonCategoryType> CCT =
12735 if (!CCT)
12736 return S.InvalidOperands(Loc, LHS, RHS);
12737
12738 bool HasNarrowing = checkThreeWayNarrowingConversion(
12739 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12740 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12741 RHS.get()->getBeginLoc());
12742 if (HasNarrowing)
12743 return QualType();
12744
12745 assert(!Type.isNull() && "composite type for <=> has not been set");
12746
12749}
12750
12752 ExprResult &RHS,
12753 SourceLocation Loc,
12754 BinaryOperatorKind Opc) {
12755 if (Opc == BO_Cmp)
12756 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12757
12758 // C99 6.5.8p3 / C99 6.5.9p4
12759 QualType Type =
12761 if (LHS.isInvalid() || RHS.isInvalid())
12762 return QualType();
12763 if (Type.isNull()) {
12764 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12765 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12766 return ResultTy;
12767 }
12768 assert(Type->isArithmeticType() || Type->isEnumeralType());
12769
12771 return S.InvalidOperands(Loc, LHS, RHS);
12772
12773 // Check for comparisons of floating point operands using != and ==.
12775 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12776
12777 // The result of comparisons is 'bool' in C++, 'int' in C.
12779}
12780
12782 if (!NullE.get()->getType()->isAnyPointerType())
12783 return;
12784 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12785 if (!E.get()->getType()->isAnyPointerType() &&
12789 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12790 if (CL->getValue() == 0)
12791 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12792 << NullValue
12794 NullValue ? "NULL" : "(void *)0");
12795 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12796 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12797 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12798 if (T == Context.CharTy)
12799 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12800 << NullValue
12802 NullValue ? "NULL" : "(void *)0");
12803 }
12804 }
12805}
12806
12807// C99 6.5.8, C++ [expr.rel]
12809 SourceLocation Loc,
12810 BinaryOperatorKind Opc) {
12811 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12812 bool IsThreeWay = Opc == BO_Cmp;
12813 bool IsOrdered = IsRelational || IsThreeWay;
12814 auto IsAnyPointerType = [](ExprResult E) {
12815 QualType Ty = E.get()->getType();
12816 return Ty->isPointerType() || Ty->isMemberPointerType();
12817 };
12818
12819 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12820 // type, array-to-pointer, ..., conversions are performed on both operands to
12821 // bring them to their composite type.
12822 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12823 // any type-related checks.
12824 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12826 if (LHS.isInvalid())
12827 return QualType();
12829 if (RHS.isInvalid())
12830 return QualType();
12831 } else {
12832 LHS = DefaultLvalueConversion(LHS.get());
12833 if (LHS.isInvalid())
12834 return QualType();
12835 RHS = DefaultLvalueConversion(RHS.get());
12836 if (RHS.isInvalid())
12837 return QualType();
12838 }
12839
12840 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12844 }
12845
12846 // Handle vector comparisons separately.
12847 if (LHS.get()->getType()->isVectorType() ||
12848 RHS.get()->getType()->isVectorType())
12849 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12850
12851 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12852 RHS.get()->getType()->isSveVLSBuiltinType())
12853 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12854
12855 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12856 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12857
12858 QualType LHSType = LHS.get()->getType();
12859 QualType RHSType = RHS.get()->getType();
12860 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12861 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12862 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12863
12864 if ((LHSType->isPointerType() &&
12866 (RHSType->isPointerType() &&
12868 return InvalidOperands(Loc, LHS, RHS);
12869
12870 const Expr::NullPointerConstantKind LHSNullKind =
12872 const Expr::NullPointerConstantKind RHSNullKind =
12874 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12875 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12876
12877 auto computeResultTy = [&]() {
12878 if (Opc != BO_Cmp)
12879 return QualType(Context.getLogicalOperationType());
12880 assert(getLangOpts().CPlusPlus);
12881 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12882
12883 QualType CompositeTy = LHS.get()->getType();
12884 assert(!CompositeTy->isReferenceType());
12885
12886 std::optional<ComparisonCategoryType> CCT =
12888 if (!CCT)
12889 return InvalidOperands(Loc, LHS, RHS);
12890
12891 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12892 // P0946R0: Comparisons between a null pointer constant and an object
12893 // pointer result in std::strong_equality, which is ill-formed under
12894 // P1959R0.
12895 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12896 << (LHSIsNull ? LHS.get()->getSourceRange()
12897 : RHS.get()->getSourceRange());
12898 return QualType();
12899 }
12900
12903 };
12904
12905 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12906 bool IsEquality = Opc == BO_EQ;
12907 if (RHSIsNull)
12908 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12909 RHS.get()->getSourceRange());
12910 else
12911 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12912 LHS.get()->getSourceRange());
12913 }
12914
12915 if (IsOrdered && LHSType->isFunctionPointerType() &&
12916 RHSType->isFunctionPointerType()) {
12917 // Valid unless a relational comparison of function pointers
12918 bool IsError = Opc == BO_Cmp;
12919 auto DiagID =
12920 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12921 : getLangOpts().CPlusPlus
12922 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12923 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12924 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12925 << RHS.get()->getSourceRange();
12926 if (IsError)
12927 return QualType();
12928 }
12929
12930 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12931 (RHSType->isIntegerType() && !RHSIsNull)) {
12932 // Skip normal pointer conversion checks in this case; we have better
12933 // diagnostics for this below.
12934 } else if (getLangOpts().CPlusPlus) {
12935 // Equality comparison of a function pointer to a void pointer is invalid,
12936 // but we allow it as an extension.
12937 // FIXME: If we really want to allow this, should it be part of composite
12938 // pointer type computation so it works in conditionals too?
12939 if (!IsOrdered &&
12940 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12941 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12942 // This is a gcc extension compatibility comparison.
12943 // In a SFINAE context, we treat this as a hard error to maintain
12944 // conformance with the C++ standard.
12945 bool IsError = isSFINAEContext();
12946 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, IsError);
12947
12948 if (IsError)
12949 return QualType();
12950
12951 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12952 return computeResultTy();
12953 }
12954
12955 // C++ [expr.eq]p2:
12956 // If at least one operand is a pointer [...] bring them to their
12957 // composite pointer type.
12958 // C++ [expr.spaceship]p6
12959 // If at least one of the operands is of pointer type, [...] bring them
12960 // to their composite pointer type.
12961 // C++ [expr.rel]p2:
12962 // If both operands are pointers, [...] bring them to their composite
12963 // pointer type.
12964 // For <=>, the only valid non-pointer types are arrays and functions, and
12965 // we already decayed those, so this is really the same as the relational
12966 // comparison rule.
12967 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12968 (IsOrdered ? 2 : 1) &&
12969 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12970 RHSType->isObjCObjectPointerType()))) {
12971 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12972 return QualType();
12973 return computeResultTy();
12974 }
12975 } else if (LHSType->isPointerType() &&
12976 RHSType->isPointerType()) { // C99 6.5.8p2
12977 // All of the following pointer-related warnings are GCC extensions, except
12978 // when handling null pointer constants.
12979 QualType LCanPointeeTy =
12981 QualType RCanPointeeTy =
12983
12984 // C99 6.5.9p2 and C99 6.5.8p2
12985 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12986 RCanPointeeTy.getUnqualifiedType())) {
12987 if (IsRelational) {
12988 // Pointers both need to point to complete or incomplete types
12989 if ((LCanPointeeTy->isIncompleteType() !=
12990 RCanPointeeTy->isIncompleteType()) &&
12991 !getLangOpts().C11) {
12992 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12993 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12994 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12995 << RCanPointeeTy->isIncompleteType();
12996 }
12997 }
12998 } else if (!IsRelational &&
12999 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13000 // Valid unless comparison between non-null pointer and function pointer
13001 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13002 && !LHSIsNull && !RHSIsNull)
13003 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
13004 /*isError*/false);
13005 } else {
13006 // Invalid
13007 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
13008 }
13009 if (LCanPointeeTy != RCanPointeeTy) {
13010 // Treat NULL constant as a special case in OpenCL.
13011 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13012 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
13013 getASTContext())) {
13014 Diag(Loc,
13015 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13016 << LHSType << RHSType << 0 /* comparison */
13017 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13018 }
13019 }
13020 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13021 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13022 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13023 : CK_BitCast;
13024
13025 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13026 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13027 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13028 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13029 bool ChangingCFIUncheckedCallee =
13030 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13031
13032 if (LHSIsNull && !RHSIsNull)
13033 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
13034 else if (!ChangingCFIUncheckedCallee)
13035 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
13036 }
13037 return computeResultTy();
13038 }
13039
13040
13041 // C++ [expr.eq]p4:
13042 // Two operands of type std::nullptr_t or one operand of type
13043 // std::nullptr_t and the other a null pointer constant compare
13044 // equal.
13045 // C23 6.5.9p5:
13046 // If both operands have type nullptr_t or one operand has type nullptr_t
13047 // and the other is a null pointer constant, they compare equal if the
13048 // former is a null pointer.
13049 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13050 if (LHSType->isNullPtrType()) {
13051 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13052 return computeResultTy();
13053 }
13054 if (RHSType->isNullPtrType()) {
13055 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13056 return computeResultTy();
13057 }
13058 }
13059
13060 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13061 // C23 6.5.9p6:
13062 // Otherwise, at least one operand is a pointer. If one is a pointer and
13063 // the other is a null pointer constant or has type nullptr_t, they
13064 // compare equal
13065 if (LHSIsNull && RHSType->isPointerType()) {
13066 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13067 return computeResultTy();
13068 }
13069 if (RHSIsNull && LHSType->isPointerType()) {
13070 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13071 return computeResultTy();
13072 }
13073 }
13074
13075 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13076 // These aren't covered by the composite pointer type rules.
13077 if (!IsOrdered && RHSType->isNullPtrType() &&
13078 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13079 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13080 return computeResultTy();
13081 }
13082 if (!IsOrdered && LHSType->isNullPtrType() &&
13083 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13084 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13085 return computeResultTy();
13086 }
13087
13088 if (getLangOpts().CPlusPlus) {
13089 if (IsRelational &&
13090 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13091 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13092 // HACK: Relational comparison of nullptr_t against a pointer type is
13093 // invalid per DR583, but we allow it within std::less<> and friends,
13094 // since otherwise common uses of it break.
13095 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13096 // friends to have std::nullptr_t overload candidates.
13097 DeclContext *DC = CurContext;
13098 if (isa<FunctionDecl>(DC))
13099 DC = DC->getParent();
13100 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
13101 if (CTSD->isInStdNamespace() &&
13102 llvm::StringSwitch<bool>(CTSD->getName())
13103 .Cases({"less", "less_equal", "greater", "greater_equal"}, true)
13104 .Default(false)) {
13105 if (RHSType->isNullPtrType())
13106 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13107 else
13108 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13109 return computeResultTy();
13110 }
13111 }
13112 }
13113
13114 // C++ [expr.eq]p2:
13115 // If at least one operand is a pointer to member, [...] bring them to
13116 // their composite pointer type.
13117 if (!IsOrdered &&
13118 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13119 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13120 return QualType();
13121 else
13122 return computeResultTy();
13123 }
13124 }
13125
13126 // Handle block pointer types.
13127 if (!IsOrdered && LHSType->isBlockPointerType() &&
13128 RHSType->isBlockPointerType()) {
13129 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13130 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13131
13132 if (!LHSIsNull && !RHSIsNull &&
13133 !Context.typesAreCompatible(lpointee, rpointee)) {
13134 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13135 << LHSType << RHSType << LHS.get()->getSourceRange()
13136 << RHS.get()->getSourceRange();
13137 }
13138 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13139 return computeResultTy();
13140 }
13141
13142 // Allow block pointers to be compared with null pointer constants.
13143 if (!IsOrdered
13144 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13145 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13146 if (!LHSIsNull && !RHSIsNull) {
13147 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13149 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13150 ->getPointeeType()->isVoidType())))
13151 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13152 << LHSType << RHSType << LHS.get()->getSourceRange()
13153 << RHS.get()->getSourceRange();
13154 }
13155 if (LHSIsNull && !RHSIsNull)
13156 LHS = ImpCastExprToType(LHS.get(), RHSType,
13157 RHSType->isPointerType() ? CK_BitCast
13158 : CK_AnyPointerToBlockPointerCast);
13159 else
13160 RHS = ImpCastExprToType(RHS.get(), LHSType,
13161 LHSType->isPointerType() ? CK_BitCast
13162 : CK_AnyPointerToBlockPointerCast);
13163 return computeResultTy();
13164 }
13165
13166 if (LHSType->isObjCObjectPointerType() ||
13167 RHSType->isObjCObjectPointerType()) {
13168 const PointerType *LPT = LHSType->getAs<PointerType>();
13169 const PointerType *RPT = RHSType->getAs<PointerType>();
13170 if (LPT || RPT) {
13171 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13172 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13173
13174 if (!LPtrToVoid && !RPtrToVoid &&
13175 !Context.typesAreCompatible(LHSType, RHSType)) {
13176 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13177 /*isError*/false);
13178 }
13179 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13180 // the RHS, but we have test coverage for this behavior.
13181 // FIXME: Consider using convertPointersToCompositeType in C++.
13182 if (LHSIsNull && !RHSIsNull) {
13183 Expr *E = LHS.get();
13184 if (getLangOpts().ObjCAutoRefCount)
13185 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
13187 LHS = ImpCastExprToType(E, RHSType,
13188 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13189 }
13190 else {
13191 Expr *E = RHS.get();
13192 if (getLangOpts().ObjCAutoRefCount)
13193 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
13195 /*Diagnose=*/true,
13196 /*DiagnoseCFAudited=*/false, Opc);
13197 RHS = ImpCastExprToType(E, LHSType,
13198 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13199 }
13200 return computeResultTy();
13201 }
13202 if (LHSType->isObjCObjectPointerType() &&
13203 RHSType->isObjCObjectPointerType()) {
13204 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13205 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13206 /*isError*/false);
13208 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13209
13210 if (LHSIsNull && !RHSIsNull)
13211 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13212 else
13213 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13214 return computeResultTy();
13215 }
13216
13217 if (!IsOrdered && LHSType->isBlockPointerType() &&
13219 LHS = ImpCastExprToType(LHS.get(), RHSType,
13220 CK_BlockPointerToObjCPointerCast);
13221 return computeResultTy();
13222 } else if (!IsOrdered &&
13224 RHSType->isBlockPointerType()) {
13225 RHS = ImpCastExprToType(RHS.get(), LHSType,
13226 CK_BlockPointerToObjCPointerCast);
13227 return computeResultTy();
13228 }
13229 }
13230 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13231 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13232 unsigned DiagID = 0;
13233 bool isError = false;
13234 if (LangOpts.DebuggerSupport) {
13235 // Under a debugger, allow the comparison of pointers to integers,
13236 // since users tend to want to compare addresses.
13237 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13238 (RHSIsNull && RHSType->isIntegerType())) {
13239 if (IsOrdered) {
13240 isError = getLangOpts().CPlusPlus;
13241 DiagID =
13242 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13243 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13244 }
13245 } else if (getLangOpts().CPlusPlus) {
13246 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13247 isError = true;
13248 } else if (IsOrdered)
13249 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13250 else
13251 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13252
13253 if (DiagID) {
13254 Diag(Loc, DiagID)
13255 << LHSType << RHSType << LHS.get()->getSourceRange()
13256 << RHS.get()->getSourceRange();
13257 if (isError)
13258 return QualType();
13259 }
13260
13261 if (LHSType->isIntegerType())
13262 LHS = ImpCastExprToType(LHS.get(), RHSType,
13263 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13264 else
13265 RHS = ImpCastExprToType(RHS.get(), LHSType,
13266 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13267 return computeResultTy();
13268 }
13269
13270 // Handle block pointers.
13271 if (!IsOrdered && RHSIsNull
13272 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13273 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13274 return computeResultTy();
13275 }
13276 if (!IsOrdered && LHSIsNull
13277 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13278 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13279 return computeResultTy();
13280 }
13281
13282 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13283 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13284 return computeResultTy();
13285 }
13286
13287 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13288 return computeResultTy();
13289 }
13290
13291 if (LHSIsNull && RHSType->isQueueT()) {
13292 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13293 return computeResultTy();
13294 }
13295
13296 if (LHSType->isQueueT() && RHSIsNull) {
13297 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13298 return computeResultTy();
13299 }
13300 }
13301
13302 return InvalidOperands(Loc, LHS, RHS);
13303}
13304
13306 const VectorType *VTy = V->castAs<VectorType>();
13307 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13308
13309 if (isa<ExtVectorType>(VTy)) {
13310 if (VTy->isExtVectorBoolType())
13311 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13312 if (TypeSize == Context.getTypeSize(Context.CharTy))
13313 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13314 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13315 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13316 if (TypeSize == Context.getTypeSize(Context.IntTy))
13317 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13318 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13319 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13320 if (TypeSize == Context.getTypeSize(Context.LongTy))
13321 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13322 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13323 "Unhandled vector element size in vector compare");
13324 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13325 }
13326
13327 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13328 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13330 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13331 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13333 if (TypeSize == Context.getTypeSize(Context.LongTy))
13334 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13336 if (TypeSize == Context.getTypeSize(Context.IntTy))
13337 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13339 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13340 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13342 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13343 "Unhandled vector element size in vector compare");
13344 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13346}
13347
13349 const BuiltinType *VTy = V->castAs<BuiltinType>();
13350 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13351
13352 const QualType ETy = V->getSveEltType(Context);
13353 const auto TypeSize = Context.getTypeSize(ETy);
13354
13355 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13356 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13357 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13358}
13359
13361 SourceLocation Loc,
13362 BinaryOperatorKind Opc) {
13363 if (Opc == BO_Cmp) {
13364 Diag(Loc, diag::err_three_way_vector_comparison);
13365 return QualType();
13366 }
13367
13368 // Check to make sure we're operating on vectors of the same type and width,
13369 // Allowing one side to be a scalar of element type.
13370 QualType vType =
13371 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13372 /*AllowBothBool*/ true,
13373 /*AllowBoolConversions*/ getLangOpts().ZVector,
13374 /*AllowBooleanOperation*/ true,
13375 /*ReportInvalid*/ true);
13376 if (vType.isNull())
13377 return vType;
13378
13379 QualType LHSType = LHS.get()->getType();
13380
13381 // Determine the return type of a vector compare. By default clang will return
13382 // a scalar for all vector compares except vector bool and vector pixel.
13383 // With the gcc compiler we will always return a vector type and with the xl
13384 // compiler we will always return a scalar type. This switch allows choosing
13385 // which behavior is prefered.
13386 if (getLangOpts().AltiVec) {
13387 switch (getLangOpts().getAltivecSrcCompat()) {
13389 // If AltiVec, the comparison results in a numeric type, i.e.
13390 // bool for C++, int for C
13391 if (vType->castAs<VectorType>()->getVectorKind() ==
13393 return Context.getLogicalOperationType();
13394 else
13395 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13396 break;
13398 // For GCC we always return the vector type.
13399 break;
13401 return Context.getLogicalOperationType();
13402 break;
13403 }
13404 }
13405
13406 // For non-floating point types, check for self-comparisons of the form
13407 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13408 // often indicate logic errors in the program.
13409 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13410
13411 // Check for comparisons of floating point operands using != and ==.
13412 if (LHSType->hasFloatingRepresentation()) {
13413 assert(RHS.get()->getType()->hasFloatingRepresentation());
13414 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13415 }
13416
13417 // Return a signed type for the vector.
13418 return GetSignedVectorType(vType);
13419}
13420
13422 ExprResult &RHS,
13423 SourceLocation Loc,
13424 BinaryOperatorKind Opc) {
13425 if (Opc == BO_Cmp) {
13426 Diag(Loc, diag::err_three_way_vector_comparison);
13427 return QualType();
13428 }
13429
13430 // Check to make sure we're operating on vectors of the same type and width,
13431 // Allowing one side to be a scalar of element type.
13433 LHS, RHS, Loc, /*isCompAssign*/ false, ArithConvKind::Comparison);
13434
13435 if (vType.isNull())
13436 return vType;
13437
13438 QualType LHSType = LHS.get()->getType();
13439
13440 // For non-floating point types, check for self-comparisons of the form
13441 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13442 // often indicate logic errors in the program.
13443 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13444
13445 // Check for comparisons of floating point operands using != and ==.
13446 if (LHSType->hasFloatingRepresentation()) {
13447 assert(RHS.get()->getType()->hasFloatingRepresentation());
13448 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13449 }
13450
13451 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13452 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13453
13454 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13455 RHSBuiltinTy->isSVEBool())
13456 return LHSType;
13457
13458 // Return a signed type for the vector.
13459 return GetSignedSizelessVectorType(vType);
13460}
13461
13462static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13463 const ExprResult &XorRHS,
13464 const SourceLocation Loc) {
13465 // Do not diagnose macros.
13466 if (Loc.isMacroID())
13467 return;
13468
13469 // Do not diagnose if both LHS and RHS are macros.
13470 if (XorLHS.get()->getExprLoc().isMacroID() &&
13471 XorRHS.get()->getExprLoc().isMacroID())
13472 return;
13473
13474 bool Negative = false;
13475 bool ExplicitPlus = false;
13476 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13477 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13478
13479 if (!LHSInt)
13480 return;
13481 if (!RHSInt) {
13482 // Check negative literals.
13483 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13484 UnaryOperatorKind Opc = UO->getOpcode();
13485 if (Opc != UO_Minus && Opc != UO_Plus)
13486 return;
13487 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13488 if (!RHSInt)
13489 return;
13490 Negative = (Opc == UO_Minus);
13491 ExplicitPlus = !Negative;
13492 } else {
13493 return;
13494 }
13495 }
13496
13497 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13498 llvm::APInt RightSideValue = RHSInt->getValue();
13499 if (LeftSideValue != 2 && LeftSideValue != 10)
13500 return;
13501
13502 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13503 return;
13504
13506 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13507 llvm::StringRef ExprStr =
13509
13510 CharSourceRange XorRange =
13512 llvm::StringRef XorStr =
13514 // Do not diagnose if xor keyword/macro is used.
13515 if (XorStr == "xor")
13516 return;
13517
13518 std::string LHSStr = std::string(Lexer::getSourceText(
13519 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13520 S.getSourceManager(), S.getLangOpts()));
13521 std::string RHSStr = std::string(Lexer::getSourceText(
13522 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13523 S.getSourceManager(), S.getLangOpts()));
13524
13525 if (Negative) {
13526 RightSideValue = -RightSideValue;
13527 RHSStr = "-" + RHSStr;
13528 } else if (ExplicitPlus) {
13529 RHSStr = "+" + RHSStr;
13530 }
13531
13532 StringRef LHSStrRef = LHSStr;
13533 StringRef RHSStrRef = RHSStr;
13534 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13535 // literals.
13536 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13537 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13538 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13539 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13540 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13541 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13542 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13543 return;
13544
13545 bool SuggestXor =
13546 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13547 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13548 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13549 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13550 std::string SuggestedExpr = "1 << " + RHSStr;
13551 bool Overflow = false;
13552 llvm::APInt One = (LeftSideValue - 1);
13553 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13554 if (Overflow) {
13555 if (RightSideIntValue < 64)
13556 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13557 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13558 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13559 else if (RightSideIntValue == 64)
13560 S.Diag(Loc, diag::warn_xor_used_as_pow)
13561 << ExprStr << toString(XorValue, 10, true);
13562 else
13563 return;
13564 } else {
13565 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13566 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13567 << toString(PowValue, 10, true)
13569 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13570 }
13571
13572 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13573 << ("0x2 ^ " + RHSStr) << SuggestXor;
13574 } else if (LeftSideValue == 10) {
13575 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13576 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13577 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13578 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13579 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13580 << ("0xA ^ " + RHSStr) << SuggestXor;
13581 }
13582}
13583
13585 SourceLocation Loc,
13586 BinaryOperatorKind Opc) {
13587 // Ensure that either both operands are of the same vector type, or
13588 // one operand is of a vector type and the other is of its element type.
13589 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13590 /*AllowBothBool*/ true,
13591 /*AllowBoolConversions*/ false,
13592 /*AllowBooleanOperation*/ false,
13593 /*ReportInvalid*/ false);
13594 if (vType.isNull())
13595 return InvalidOperands(Loc, LHS, RHS);
13596 if (getLangOpts().OpenCL &&
13597 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13599 return InvalidOperands(Loc, LHS, RHS);
13600 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13601 // usage of the logical operators && and || with vectors in C. This
13602 // check could be notionally dropped.
13603 if (!getLangOpts().CPlusPlus &&
13604 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13605 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13606 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13607 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13608 // `select` functions.
13609 if (getLangOpts().HLSL &&
13610 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13611 (void)InvalidOperands(Loc, LHS, RHS);
13612 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13613 return QualType();
13614 }
13615
13616 return GetSignedVectorType(LHS.get()->getType());
13617}
13618
13620 SourceLocation Loc,
13621 BinaryOperatorKind Opc) {
13622
13623 if (!getLangOpts().HLSL) {
13624 assert(false && "Logical operands are not supported in C\\C++");
13625 return QualType();
13626 }
13627
13628 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13629 (void)InvalidOperands(Loc, LHS, RHS);
13630 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13631 return QualType();
13632 }
13633 SemaRef.Diag(LHS.get()->getBeginLoc(), diag::err_hlsl_langstd_unimplemented)
13634 << getLangOpts().getHLSLVersion();
13635 return QualType();
13636}
13637
13639 SourceLocation Loc,
13640 bool IsCompAssign) {
13641 if (!IsCompAssign) {
13643 if (LHS.isInvalid())
13644 return QualType();
13645 }
13647 if (RHS.isInvalid())
13648 return QualType();
13649
13650 // For conversion purposes, we ignore any qualifiers.
13651 // For example, "const float" and "float" are equivalent.
13652 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13653 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13654
13655 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13656 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13657 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13658
13659 if (Context.hasSameType(LHSType, RHSType))
13660 return Context.getCommonSugaredType(LHSType, RHSType);
13661
13662 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13663 // case we have to return InvalidOperands.
13664 ExprResult OriginalLHS = LHS;
13665 ExprResult OriginalRHS = RHS;
13666 if (LHSMatType && !RHSMatType) {
13667 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13668 if (!RHS.isInvalid())
13669 return LHSType;
13670
13671 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13672 }
13673
13674 if (!LHSMatType && RHSMatType) {
13675 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13676 if (!LHS.isInvalid())
13677 return RHSType;
13678 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13679 }
13680
13681 return InvalidOperands(Loc, LHS, RHS);
13682}
13683
13685 SourceLocation Loc,
13686 bool IsCompAssign) {
13687 if (!IsCompAssign) {
13689 if (LHS.isInvalid())
13690 return QualType();
13691 }
13693 if (RHS.isInvalid())
13694 return QualType();
13695
13696 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13697 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13698 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13699
13700 if (LHSMatType && RHSMatType) {
13701 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13702 return InvalidOperands(Loc, LHS, RHS);
13703
13704 if (Context.hasSameType(LHSMatType, RHSMatType))
13705 return Context.getCommonSugaredType(
13706 LHS.get()->getType().getUnqualifiedType(),
13707 RHS.get()->getType().getUnqualifiedType());
13708
13709 QualType LHSELTy = LHSMatType->getElementType(),
13710 RHSELTy = RHSMatType->getElementType();
13711 if (!Context.hasSameType(LHSELTy, RHSELTy))
13712 return InvalidOperands(Loc, LHS, RHS);
13713
13714 return Context.getConstantMatrixType(
13715 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13716 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13717 }
13718 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13719}
13720
13722 switch (Opc) {
13723 default:
13724 return false;
13725 case BO_And:
13726 case BO_AndAssign:
13727 case BO_Or:
13728 case BO_OrAssign:
13729 case BO_Xor:
13730 case BO_XorAssign:
13731 return true;
13732 }
13733}
13734
13736 SourceLocation Loc,
13737 BinaryOperatorKind Opc) {
13738 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13739
13740 bool IsCompAssign =
13741 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13742
13743 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13744
13745 if (LHS.get()->getType()->isVectorType() ||
13746 RHS.get()->getType()->isVectorType()) {
13747 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13749 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13750 /*AllowBothBool*/ true,
13751 /*AllowBoolConversions*/ getLangOpts().ZVector,
13752 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13753 /*ReportInvalid*/ true);
13754 return InvalidOperands(Loc, LHS, RHS);
13755 }
13756
13757 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13758 RHS.get()->getType()->isSveVLSBuiltinType()) {
13759 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13761 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13763 return InvalidOperands(Loc, LHS, RHS);
13764 }
13765
13766 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13767 RHS.get()->getType()->isSveVLSBuiltinType()) {
13768 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13770 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13772 return InvalidOperands(Loc, LHS, RHS);
13773 }
13774
13775 if (Opc == BO_And)
13776 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13777
13778 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13780 return InvalidOperands(Loc, LHS, RHS);
13781
13782 ExprResult LHSResult = LHS, RHSResult = RHS;
13784 LHSResult, RHSResult, Loc,
13786 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13787 return QualType();
13788 LHS = LHSResult.get();
13789 RHS = RHSResult.get();
13790
13791 if (Opc == BO_Xor)
13792 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13793
13794 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13795 return compType;
13796 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13797 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13798 return ResultTy;
13799}
13800
13801// C99 6.5.[13,14]
13803 SourceLocation Loc,
13804 BinaryOperatorKind Opc) {
13805 // Check vector operands differently.
13806 if (LHS.get()->getType()->isVectorType() ||
13807 RHS.get()->getType()->isVectorType())
13808 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13809
13810 if (LHS.get()->getType()->isConstantMatrixType() ||
13811 RHS.get()->getType()->isConstantMatrixType())
13812 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
13813
13814 bool EnumConstantInBoolContext = false;
13815 for (const ExprResult &HS : {LHS, RHS}) {
13816 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13817 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13818 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13819 EnumConstantInBoolContext = true;
13820 }
13821 }
13822
13823 if (EnumConstantInBoolContext)
13824 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13825
13826 // WebAssembly tables can't be used with logical operators.
13827 QualType LHSTy = LHS.get()->getType();
13828 QualType RHSTy = RHS.get()->getType();
13829 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13830 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13831 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13832 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13833 return InvalidOperands(Loc, LHS, RHS);
13834 }
13835
13836 // Diagnose cases where the user write a logical and/or but probably meant a
13837 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13838 // is a constant.
13839 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13840 !LHS.get()->getType()->isBooleanType() &&
13841 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13842 // Don't warn in macros or template instantiations.
13843 !Loc.isMacroID() && !inTemplateInstantiation()) {
13844 // If the RHS can be constant folded, and if it constant folds to something
13845 // that isn't 0 or 1 (which indicate a potential logical operation that
13846 // happened to fold to true/false) then warn.
13847 // Parens on the RHS are ignored.
13848 Expr::EvalResult EVResult;
13849 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13850 llvm::APSInt Result = EVResult.Val.getInt();
13851 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13852 !RHS.get()->getExprLoc().isMacroID()) ||
13853 (Result != 0 && Result != 1)) {
13854 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13855 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13856 // Suggest replacing the logical operator with the bitwise version
13857 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13858 << (Opc == BO_LAnd ? "&" : "|")
13861 Opc == BO_LAnd ? "&" : "|");
13862 if (Opc == BO_LAnd)
13863 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13864 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13867 RHS.get()->getEndLoc()));
13868 }
13869 }
13870 }
13871
13872 if (!Context.getLangOpts().CPlusPlus) {
13873 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13874 // not operate on the built-in scalar and vector float types.
13875 if (Context.getLangOpts().OpenCL &&
13876 Context.getLangOpts().OpenCLVersion < 120) {
13877 if (LHS.get()->getType()->isFloatingType() ||
13878 RHS.get()->getType()->isFloatingType())
13879 return InvalidOperands(Loc, LHS, RHS);
13880 }
13881
13882 LHS = UsualUnaryConversions(LHS.get());
13883 if (LHS.isInvalid())
13884 return QualType();
13885
13886 RHS = UsualUnaryConversions(RHS.get());
13887 if (RHS.isInvalid())
13888 return QualType();
13889
13890 if (!LHS.get()->getType()->isScalarType() ||
13891 !RHS.get()->getType()->isScalarType())
13892 return InvalidOperands(Loc, LHS, RHS);
13893
13894 return Context.IntTy;
13895 }
13896
13897 // The following is safe because we only use this method for
13898 // non-overloadable operands.
13899
13900 // C++ [expr.log.and]p1
13901 // C++ [expr.log.or]p1
13902 // The operands are both contextually converted to type bool.
13904 if (LHSRes.isInvalid()) {
13905 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13906 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13907 return ResultTy;
13908 }
13909 LHS = LHSRes;
13910
13912 if (RHSRes.isInvalid()) {
13913 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13914 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13915 return ResultTy;
13916 }
13917 RHS = RHSRes;
13918
13919 // C++ [expr.log.and]p2
13920 // C++ [expr.log.or]p2
13921 // The result is a bool.
13922 return Context.BoolTy;
13923}
13924
13925static bool IsReadonlyMessage(Expr *E, Sema &S) {
13926 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13927 if (!ME) return false;
13928 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13929 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13931 if (!Base) return false;
13932 return Base->getMethodDecl() != nullptr;
13933}
13934
13935/// Is the given expression (which must be 'const') a reference to a
13936/// variable which was originally non-const, but which has become
13937/// 'const' due to being captured within a block?
13940 assert(E->isLValue() && E->getType().isConstQualified());
13941 E = E->IgnoreParens();
13942
13943 // Must be a reference to a declaration from an enclosing scope.
13944 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13945 if (!DRE) return NCCK_None;
13947
13948 ValueDecl *Value = dyn_cast<ValueDecl>(DRE->getDecl());
13949
13950 // The declaration must be a value which is not declared 'const'.
13951 if (!Value || Value->getType().isConstQualified())
13952 return NCCK_None;
13953
13954 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
13955 if (Binding) {
13956 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
13957 assert(!isa<BlockDecl>(Binding->getDeclContext()));
13958 return NCCK_Lambda;
13959 }
13960
13961 VarDecl *Var = dyn_cast<VarDecl>(Value);
13962 if (!Var)
13963 return NCCK_None;
13964 if (Var->getType()->isReferenceType())
13965 return NCCK_None;
13966
13967 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
13968
13969 // Decide whether the first capture was for a block or a lambda.
13970 DeclContext *DC = S.CurContext, *Prev = nullptr;
13971 // Decide whether the first capture was for a block or a lambda.
13972 while (DC) {
13973 // For init-capture, it is possible that the variable belongs to the
13974 // template pattern of the current context.
13975 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13976 if (Var->isInitCapture() &&
13977 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
13978 break;
13979 if (DC == Var->getDeclContext())
13980 break;
13981 Prev = DC;
13982 DC = DC->getParent();
13983 }
13984 // Unless we have an init-capture, we've gone one step too far.
13985 if (!Var->isInitCapture())
13986 DC = Prev;
13987 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13988}
13989
13990static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13991 Ty = Ty.getNonReferenceType();
13992 if (IsDereference && Ty->isPointerType())
13993 Ty = Ty->getPointeeType();
13994 return !Ty.isConstQualified();
13995}
13996
13997// Update err_typecheck_assign_const and note_typecheck_assign_const
13998// when this enum is changed.
13999enum {
14004 ConstUnknown, // Keep as last element
14005};
14006
14007/// Emit the "read-only variable not assignable" error and print notes to give
14008/// more information about why the variable is not assignable, such as pointing
14009/// to the declaration of a const variable, showing that a method is const, or
14010/// that the function is returning a const reference.
14011static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14012 SourceLocation Loc) {
14013 SourceRange ExprRange = E->getSourceRange();
14014
14015 // Only emit one error on the first const found. All other consts will emit
14016 // a note to the error.
14017 bool DiagnosticEmitted = false;
14018
14019 // Track if the current expression is the result of a dereference, and if the
14020 // next checked expression is the result of a dereference.
14021 bool IsDereference = false;
14022 bool NextIsDereference = false;
14023
14024 // Loop to process MemberExpr chains.
14025 while (true) {
14026 IsDereference = NextIsDereference;
14027
14029 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14030 NextIsDereference = ME->isArrow();
14031 const ValueDecl *VD = ME->getMemberDecl();
14032 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
14033 // Mutable fields can be modified even if the class is const.
14034 if (Field->isMutable()) {
14035 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14036 break;
14037 }
14038
14039 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
14040 if (!DiagnosticEmitted) {
14041 S.Diag(Loc, diag::err_typecheck_assign_const)
14042 << ExprRange << ConstMember << false /*static*/ << Field
14043 << Field->getType();
14044 DiagnosticEmitted = true;
14045 }
14046 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14047 << ConstMember << false /*static*/ << Field << Field->getType()
14048 << Field->getSourceRange();
14049 }
14050 E = ME->getBase();
14051 continue;
14052 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
14053 if (VDecl->getType().isConstQualified()) {
14054 if (!DiagnosticEmitted) {
14055 S.Diag(Loc, diag::err_typecheck_assign_const)
14056 << ExprRange << ConstMember << true /*static*/ << VDecl
14057 << VDecl->getType();
14058 DiagnosticEmitted = true;
14059 }
14060 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14061 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14062 << VDecl->getSourceRange();
14063 }
14064 // Static fields do not inherit constness from parents.
14065 break;
14066 }
14067 break; // End MemberExpr
14068 } else if (const ArraySubscriptExpr *ASE =
14069 dyn_cast<ArraySubscriptExpr>(E)) {
14070 E = ASE->getBase()->IgnoreParenImpCasts();
14071 continue;
14072 } else if (const ExtVectorElementExpr *EVE =
14073 dyn_cast<ExtVectorElementExpr>(E)) {
14074 E = EVE->getBase()->IgnoreParenImpCasts();
14075 continue;
14076 }
14077 break;
14078 }
14079
14080 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
14081 // Function calls
14082 const FunctionDecl *FD = CE->getDirectCallee();
14083 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
14084 if (!DiagnosticEmitted) {
14085 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14086 << ConstFunction << FD;
14087 DiagnosticEmitted = true;
14088 }
14090 diag::note_typecheck_assign_const)
14091 << ConstFunction << FD << FD->getReturnType()
14092 << FD->getReturnTypeSourceRange();
14093 }
14094 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14095 // Point to variable declaration.
14096 if (const ValueDecl *VD = DRE->getDecl()) {
14097 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
14098 if (!DiagnosticEmitted) {
14099 S.Diag(Loc, diag::err_typecheck_assign_const)
14100 << ExprRange << ConstVariable << VD << VD->getType();
14101 DiagnosticEmitted = true;
14102 }
14103 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14104 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14105 }
14106 }
14107 } else if (isa<CXXThisExpr>(E)) {
14108 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14109 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
14110 if (MD->isConst()) {
14111 if (!DiagnosticEmitted) {
14112 S.Diag(Loc, diag::err_typecheck_assign_const_method)
14113 << ExprRange << MD;
14114 DiagnosticEmitted = true;
14115 }
14116 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const_method)
14117 << MD << MD->getSourceRange();
14118 }
14119 }
14120 }
14121 }
14122
14123 if (DiagnosticEmitted)
14124 return;
14125
14126 // Can't determine a more specific message, so display the generic error.
14127 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14128}
14129
14135
14137 const RecordType *Ty,
14138 SourceLocation Loc, SourceRange Range,
14139 OriginalExprKind OEK,
14140 bool &DiagnosticEmitted) {
14141 std::vector<const RecordType *> RecordTypeList;
14142 RecordTypeList.push_back(Ty);
14143 unsigned NextToCheckIndex = 0;
14144 // We walk the record hierarchy breadth-first to ensure that we print
14145 // diagnostics in field nesting order.
14146 while (RecordTypeList.size() > NextToCheckIndex) {
14147 bool IsNested = NextToCheckIndex > 0;
14148 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14149 ->getDecl()
14151 ->fields()) {
14152 // First, check every field for constness.
14153 QualType FieldTy = Field->getType();
14154 if (FieldTy.isConstQualified()) {
14155 if (!DiagnosticEmitted) {
14156 S.Diag(Loc, diag::err_typecheck_assign_const)
14157 << Range << NestedConstMember << OEK << VD
14158 << IsNested << Field;
14159 DiagnosticEmitted = true;
14160 }
14161 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14162 << NestedConstMember << IsNested << Field
14163 << FieldTy << Field->getSourceRange();
14164 }
14165
14166 // Then we append it to the list to check next in order.
14167 FieldTy = FieldTy.getCanonicalType();
14168 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14169 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14170 RecordTypeList.push_back(FieldRecTy);
14171 }
14172 }
14173 ++NextToCheckIndex;
14174 }
14175}
14176
14177/// Emit an error for the case where a record we are trying to assign to has a
14178/// const-qualified field somewhere in its hierarchy.
14179static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14180 SourceLocation Loc) {
14181 QualType Ty = E->getType();
14182 assert(Ty->isRecordType() && "lvalue was not record?");
14183 SourceRange Range = E->getSourceRange();
14184 const auto *RTy = Ty->getAsCanonical<RecordType>();
14185 bool DiagEmitted = false;
14186
14187 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14188 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14189 Range, OEK_Member, DiagEmitted);
14190 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14191 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14192 Range, OEK_Variable, DiagEmitted);
14193 else
14194 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14195 Range, OEK_LValue, DiagEmitted);
14196 if (!DiagEmitted)
14197 DiagnoseConstAssignment(S, E, Loc);
14198}
14199
14200/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14201/// emit an error and return true. If so, return false.
14203 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14204
14206
14207 SourceLocation OrigLoc = Loc;
14209 &Loc);
14210 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14212 if (IsLV == Expr::MLV_Valid)
14213 return false;
14214
14215 unsigned DiagID = 0;
14216 bool NeedType = false;
14217 switch (IsLV) { // C99 6.5.16p2
14219 // Use a specialized diagnostic when we're assigning to an object
14220 // from an enclosing function or block.
14222 if (NCCK == NCCK_Block)
14223 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14224 else
14225 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14226 break;
14227 }
14228
14229 // In ARC, use some specialized diagnostics for occasions where we
14230 // infer 'const'. These are always pseudo-strong variables.
14231 if (S.getLangOpts().ObjCAutoRefCount) {
14232 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14233 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14234 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14235
14236 // Use the normal diagnostic if it's pseudo-__strong but the
14237 // user actually wrote 'const'.
14238 if (var->isARCPseudoStrong() &&
14239 (!var->getTypeSourceInfo() ||
14240 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14241 // There are three pseudo-strong cases:
14242 // - self
14243 ObjCMethodDecl *method = S.getCurMethodDecl();
14244 if (method && var == method->getSelfDecl()) {
14245 DiagID = method->isClassMethod()
14246 ? diag::err_typecheck_arc_assign_self_class_method
14247 : diag::err_typecheck_arc_assign_self;
14248
14249 // - Objective-C externally_retained attribute.
14250 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14251 isa<ParmVarDecl>(var)) {
14252 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14253
14254 // - fast enumeration variables
14255 } else {
14256 DiagID = diag::err_typecheck_arr_assign_enumeration;
14257 }
14258
14259 SourceRange Assign;
14260 if (Loc != OrigLoc)
14261 Assign = SourceRange(OrigLoc, OrigLoc);
14262 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14263 // We need to preserve the AST regardless, so migration tool
14264 // can do its job.
14265 return false;
14266 }
14267 }
14268 }
14269
14270 // If none of the special cases above are triggered, then this is a
14271 // simple const assignment.
14272 if (DiagID == 0) {
14273 DiagnoseConstAssignment(S, E, Loc);
14274 return true;
14275 }
14276
14277 break;
14279 DiagnoseConstAssignment(S, E, Loc);
14280 return true;
14283 return true;
14286 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14287 NeedType = true;
14288 break;
14290 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14291 NeedType = true;
14292 break;
14294 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14295 break;
14296 case Expr::MLV_Valid:
14297 llvm_unreachable("did not take early return for MLV_Valid");
14301 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14302 break;
14305 return S.RequireCompleteType(Loc, E->getType(),
14306 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14308 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14309 break;
14311 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14312 break;
14314 llvm_unreachable("readonly properties should be processed differently");
14316 DiagID = diag::err_readonly_message_assignment;
14317 break;
14319 DiagID = diag::err_no_subobject_property_setting;
14320 break;
14321 }
14322
14323 SourceRange Assign;
14324 if (Loc != OrigLoc)
14325 Assign = SourceRange(OrigLoc, OrigLoc);
14326 if (NeedType)
14327 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14328 else
14329 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14330 return true;
14331}
14332
14333static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14334 SourceLocation Loc,
14335 Sema &Sema) {
14337 return;
14339 return;
14340 if (Loc.isInvalid() || Loc.isMacroID())
14341 return;
14342 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14343 return;
14344
14345 // C / C++ fields
14346 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14347 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14348 if (ML && MR) {
14349 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14350 return;
14351 const ValueDecl *LHSDecl =
14353 const ValueDecl *RHSDecl =
14355 if (LHSDecl != RHSDecl)
14356 return;
14357 if (LHSDecl->getType().isVolatileQualified())
14358 return;
14359 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14360 if (RefTy->getPointeeType().isVolatileQualified())
14361 return;
14362
14363 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14364 }
14365
14366 // Objective-C instance variables
14367 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14368 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14369 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14370 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14371 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14372 if (RL && RR && RL->getDecl() == RR->getDecl())
14373 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14374 }
14375}
14376
14377// C99 6.5.16.1
14379 SourceLocation Loc,
14380 QualType CompoundType,
14381 BinaryOperatorKind Opc) {
14382 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14383
14384 // Verify that LHS is a modifiable lvalue, and emit error if not.
14385 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14386 return QualType();
14387
14388 QualType LHSType = LHSExpr->getType();
14389 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14390 CompoundType;
14391
14392 if (RHS.isUsable()) {
14393 // Even if this check fails don't return early to allow the best
14394 // possible error recovery and to allow any subsequent diagnostics to
14395 // work.
14396 const ValueDecl *Assignee = nullptr;
14397 bool ShowFullyQualifiedAssigneeName = false;
14398 // In simple cases describe what is being assigned to
14399 if (auto *DR = dyn_cast<DeclRefExpr>(LHSExpr->IgnoreParenCasts())) {
14400 Assignee = DR->getDecl();
14401 } else if (auto *ME = dyn_cast<MemberExpr>(LHSExpr->IgnoreParenCasts())) {
14402 Assignee = ME->getMemberDecl();
14403 ShowFullyQualifiedAssigneeName = true;
14404 }
14405
14407 LHSType, RHS.get(), AssignmentAction::Assigning, Loc, Assignee,
14408 ShowFullyQualifiedAssigneeName);
14409 }
14410
14411 // OpenCL v1.2 s6.1.1.1 p2:
14412 // The half data type can only be used to declare a pointer to a buffer that
14413 // contains half values
14414 if (getLangOpts().OpenCL &&
14415 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14416 LHSType->isHalfType()) {
14417 Diag(Loc, diag::err_opencl_half_load_store) << 1
14418 << LHSType.getUnqualifiedType();
14419 return QualType();
14420 }
14421
14422 // WebAssembly tables can't be used on RHS of an assignment expression.
14423 if (RHSType->isWebAssemblyTableType()) {
14424 Diag(Loc, diag::err_wasm_table_art) << 0;
14425 return QualType();
14426 }
14427
14428 AssignConvertType ConvTy;
14429 if (CompoundType.isNull()) {
14430 Expr *RHSCheck = RHS.get();
14431
14432 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14433
14434 QualType LHSTy(LHSType);
14435 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14436 if (RHS.isInvalid())
14437 return QualType();
14438 // Special case of NSObject attributes on c-style pointer types.
14440 ((Context.isObjCNSObjectType(LHSType) &&
14441 RHSType->isObjCObjectPointerType()) ||
14442 (Context.isObjCNSObjectType(RHSType) &&
14443 LHSType->isObjCObjectPointerType())))
14445
14446 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14447 Diag(Loc, diag::err_objc_object_assignment) << LHSType;
14448
14449 // If the RHS is a unary plus or minus, check to see if they = and + are
14450 // right next to each other. If so, the user may have typo'd "x =+ 4"
14451 // instead of "x += 4".
14452 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14453 RHSCheck = ICE->getSubExpr();
14454 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14455 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14456 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14457 // Only if the two operators are exactly adjacent.
14458 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14459 // And there is a space or other character before the subexpr of the
14460 // unary +/-. We don't want to warn on "x=-1".
14461 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14462 UO->getSubExpr()->getBeginLoc().isFileID()) {
14463 Diag(Loc, diag::warn_not_compound_assign)
14464 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14465 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14466 }
14467 }
14468
14469 if (IsAssignConvertCompatible(ConvTy)) {
14470 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14471 // Warn about retain cycles where a block captures the LHS, but
14472 // not if the LHS is a simple variable into which the block is
14473 // being stored...unless that variable can be captured by reference!
14474 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14475 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14476 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14477 ObjC().checkRetainCycles(LHSExpr, RHS.get());
14478 }
14479
14480 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14482 // It is safe to assign a weak reference into a strong variable.
14483 // Although this code can still have problems:
14484 // id x = self.weakProp;
14485 // id y = self.weakProp;
14486 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14487 // paths through the function. This should be revisited if
14488 // -Wrepeated-use-of-weak is made flow-sensitive.
14489 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14490 // variable, which will be valid for the current autorelease scope.
14491 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14492 RHS.get()->getBeginLoc()))
14494
14495 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14496 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14497 }
14498 }
14499 } else {
14500 // Compound assignment "x += y"
14501 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14502 }
14503
14504 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
14506 return QualType();
14507
14508 CheckForNullPointerDereference(*this, LHSExpr);
14509
14510 AssignedEntity AE{LHSExpr};
14511 checkAssignmentLifetime(*this, AE, RHS.get());
14512
14513 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14514 if (CompoundType.isNull()) {
14515 // C++2a [expr.ass]p5:
14516 // A simple-assignment whose left operand is of a volatile-qualified
14517 // type is deprecated unless the assignment is either a discarded-value
14518 // expression or an unevaluated operand
14519 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14520 }
14521 }
14522
14523 // C11 6.5.16p3: The type of an assignment expression is the type of the
14524 // left operand would have after lvalue conversion.
14525 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14526 // qualified type, the value has the unqualified version of the type of the
14527 // lvalue; additionally, if the lvalue has atomic type, the value has the
14528 // non-atomic version of the type of the lvalue.
14529 // C++ 5.17p1: the type of the assignment expression is that of its left
14530 // operand.
14531 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14532}
14533
14534// Scenarios to ignore if expression E is:
14535// 1. an explicit cast expression into void
14536// 2. a function call expression that returns void
14537static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14538 E = E->IgnoreParens();
14539
14540 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14541 if (CE->getCastKind() == CK_ToVoid) {
14542 return true;
14543 }
14544
14545 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14546 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14547 CE->getSubExpr()->getType()->isDependentType()) {
14548 return true;
14549 }
14550 }
14551
14552 if (const auto *CE = dyn_cast<CallExpr>(E))
14553 return CE->getCallReturnType(Context)->isVoidType();
14554 return false;
14555}
14556
14558 // No warnings in macros
14559 if (Loc.isMacroID())
14560 return;
14561
14562 // Don't warn in template instantiations.
14564 return;
14565
14566 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14567 // instead, skip more than needed, then call back into here with the
14568 // CommaVisitor in SemaStmt.cpp.
14569 // The listed locations are the initialization and increment portions
14570 // of a for loop. The additional checks are on the condition of
14571 // if statements, do/while loops, and for loops.
14572 // Differences in scope flags for C89 mode requires the extra logic.
14573 const unsigned ForIncrementFlags =
14574 getLangOpts().C99 || getLangOpts().CPlusPlus
14577 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14578 const unsigned ScopeFlags = getCurScope()->getFlags();
14579 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14580 (ScopeFlags & ForInitFlags) == ForInitFlags)
14581 return;
14582
14583 // If there are multiple comma operators used together, get the RHS of the
14584 // of the comma operator as the LHS.
14585 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14586 if (BO->getOpcode() != BO_Comma)
14587 break;
14588 LHS = BO->getRHS();
14589 }
14590
14591 // Only allow some expressions on LHS to not warn.
14592 if (IgnoreCommaOperand(LHS, Context))
14593 return;
14594
14595 Diag(Loc, diag::warn_comma_operator);
14596 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14597 << LHS->getSourceRange()
14599 LangOpts.CPlusPlus ? "static_cast<void>("
14600 : "(void)(")
14601 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14602 ")");
14603}
14604
14605// C99 6.5.17
14607 SourceLocation Loc) {
14608 LHS = S.CheckPlaceholderExpr(LHS.get());
14609 RHS = S.CheckPlaceholderExpr(RHS.get());
14610 if (LHS.isInvalid() || RHS.isInvalid())
14611 return QualType();
14612
14613 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14614 // operands, but not unary promotions.
14615 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14616
14617 // So we treat the LHS as a ignored value, and in C++ we allow the
14618 // containing site to determine what should be done with the RHS.
14619 LHS = S.IgnoredValueConversions(LHS.get());
14620 if (LHS.isInvalid())
14621 return QualType();
14622
14623 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14624
14625 if (!S.getLangOpts().CPlusPlus) {
14627 if (RHS.isInvalid())
14628 return QualType();
14629 if (!RHS.get()->getType()->isVoidType())
14630 S.RequireCompleteType(Loc, RHS.get()->getType(),
14631 diag::err_incomplete_type);
14632 }
14633
14634 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14635 S.DiagnoseCommaOperator(LHS.get(), Loc);
14636
14637 return RHS.get()->getType();
14638}
14639
14640/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14641/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14644 ExprObjectKind &OK,
14645 SourceLocation OpLoc, bool IsInc,
14646 bool IsPrefix) {
14647 QualType ResType = Op->getType();
14648 // Atomic types can be used for increment / decrement where the non-atomic
14649 // versions can, so ignore the _Atomic() specifier for the purpose of
14650 // checking.
14651 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14652 ResType = ResAtomicType->getValueType();
14653
14654 assert(!ResType.isNull() && "no type for increment/decrement expression");
14655
14656 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14657 // Decrement of bool is not allowed.
14658 if (!IsInc) {
14659 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14660 return QualType();
14661 }
14662 // Increment of bool sets it to true, but is deprecated.
14663 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14664 : diag::warn_increment_bool)
14665 << Op->getSourceRange();
14666 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14667 // Error on enum increments and decrements in C++ mode
14668 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14669 return QualType();
14670 } else if (ResType->isRealType()) {
14671 // OK!
14672 } else if (ResType->isPointerType()) {
14673 // C99 6.5.2.4p2, 6.5.6p2
14674 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14675 return QualType();
14676 } else if (ResType->isOverflowBehaviorType()) {
14677 // OK!
14678 } else if (ResType->isObjCObjectPointerType()) {
14679 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14680 // Otherwise, we just need a complete type.
14681 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14682 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14683 return QualType();
14684 } else if (ResType->isAnyComplexType()) {
14685 // C99 does not support ++/-- on complex types, we allow as an extension.
14686 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14687 : diag::ext_c2y_increment_complex)
14688 << IsInc << Op->getSourceRange();
14689 } else if (ResType->isPlaceholderType()) {
14691 if (PR.isInvalid()) return QualType();
14692 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14693 IsInc, IsPrefix);
14694 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14695 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14696 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14697 (ResType->castAs<VectorType>()->getVectorKind() !=
14699 // The z vector extensions allow ++ and -- for non-bool vectors.
14700 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14701 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14702 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14703 } else {
14704 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14705 << ResType << int(IsInc) << Op->getSourceRange();
14706 return QualType();
14707 }
14708 // At this point, we know we have a real, complex or pointer type.
14709 // Now make sure the operand is a modifiable lvalue.
14710 if (CheckForModifiableLvalue(Op, OpLoc, S))
14711 return QualType();
14712 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14713 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14714 // An operand with volatile-qualified type is deprecated
14715 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14716 << IsInc << ResType;
14717 }
14718 // In C++, a prefix increment is the same type as the operand. Otherwise
14719 // (in C or with postfix), the increment is the unqualified type of the
14720 // operand.
14721 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14722 VK = VK_LValue;
14723 OK = Op->getObjectKind();
14724 return ResType;
14725 } else {
14726 VK = VK_PRValue;
14727 return ResType.getUnqualifiedType();
14728 }
14729}
14730
14731/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14732/// This routine allows us to typecheck complex/recursive expressions
14733/// where the declaration is needed for type checking. We only need to
14734/// handle cases when the expression references a function designator
14735/// or is an lvalue. Here are some examples:
14736/// - &(x) => x
14737/// - &*****f => f for f a function designator.
14738/// - &s.xx => s
14739/// - &s.zz[1].yy -> s, if zz is an array
14740/// - *(x + 1) -> x, if x is an array
14741/// - &"123"[2] -> 0
14742/// - & __real__ x -> x
14743///
14744/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14745/// members.
14747 switch (E->getStmtClass()) {
14748 case Stmt::DeclRefExprClass:
14749 return cast<DeclRefExpr>(E)->getDecl();
14750 case Stmt::MemberExprClass:
14751 // If this is an arrow operator, the address is an offset from
14752 // the base's value, so the object the base refers to is
14753 // irrelevant.
14754 if (cast<MemberExpr>(E)->isArrow())
14755 return nullptr;
14756 // Otherwise, the expression refers to a part of the base
14757 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14758 case Stmt::ArraySubscriptExprClass: {
14759 // FIXME: This code shouldn't be necessary! We should catch the implicit
14760 // promotion of register arrays earlier.
14761 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14762 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14763 if (ICE->getSubExpr()->getType()->isArrayType())
14764 return getPrimaryDecl(ICE->getSubExpr());
14765 }
14766 return nullptr;
14767 }
14768 case Stmt::UnaryOperatorClass: {
14770
14771 switch(UO->getOpcode()) {
14772 case UO_Real:
14773 case UO_Imag:
14774 case UO_Extension:
14775 return getPrimaryDecl(UO->getSubExpr());
14776 default:
14777 return nullptr;
14778 }
14779 }
14780 case Stmt::ParenExprClass:
14781 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14782 case Stmt::ImplicitCastExprClass:
14783 // If the result of an implicit cast is an l-value, we care about
14784 // the sub-expression; otherwise, the result here doesn't matter.
14785 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14786 case Stmt::CXXUuidofExprClass:
14787 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14788 default:
14789 return nullptr;
14790 }
14791}
14792
14793namespace {
14794enum {
14795 AO_Bit_Field = 0,
14796 AO_Vector_Element = 1,
14797 AO_Property_Expansion = 2,
14798 AO_Register_Variable = 3,
14799 AO_Matrix_Element = 4,
14800 AO_No_Error = 5
14801};
14802}
14803/// Diagnose invalid operand for address of operations.
14804///
14805/// \param Type The type of operand which cannot have its address taken.
14807 Expr *E, unsigned Type) {
14808 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14809}
14810
14812 const Expr *Op,
14813 const CXXMethodDecl *MD) {
14814 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14815
14816 if (Op != DRE)
14817 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14818 << Op->getSourceRange();
14819
14820 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14821 if (isa<CXXDestructorDecl>(MD))
14822 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14823 << DRE->getSourceRange();
14824
14825 if (DRE->getQualifier())
14826 return false;
14827
14828 if (MD->getParent()->getName().empty())
14829 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14830 << DRE->getSourceRange();
14831
14832 SmallString<32> Str;
14833 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14834 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14835 << DRE->getSourceRange()
14836 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14837}
14838
14840 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14841 if (PTy->getKind() == BuiltinType::Overload) {
14842 Expr *E = OrigOp.get()->IgnoreParens();
14843 if (!isa<OverloadExpr>(E)) {
14844 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14845 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14846 << OrigOp.get()->getSourceRange();
14847 return QualType();
14848 }
14849
14853 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14854 << OrigOp.get()->getSourceRange();
14855 return QualType();
14856 }
14857
14858 return Context.OverloadTy;
14859 }
14860
14861 if (PTy->getKind() == BuiltinType::UnknownAny)
14862 return Context.UnknownAnyTy;
14863
14864 if (PTy->getKind() == BuiltinType::BoundMember) {
14865 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14866 << OrigOp.get()->getSourceRange();
14867 return QualType();
14868 }
14869
14870 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14871 if (OrigOp.isInvalid()) return QualType();
14872 }
14873
14874 if (OrigOp.get()->isTypeDependent())
14875 return Context.DependentTy;
14876
14877 assert(!OrigOp.get()->hasPlaceholderType());
14878
14879 // Make sure to ignore parentheses in subsequent checks
14880 Expr *op = OrigOp.get()->IgnoreParens();
14881
14882 // In OpenCL captures for blocks called as lambda functions
14883 // are located in the private address space. Blocks used in
14884 // enqueue_kernel can be located in a different address space
14885 // depending on a vendor implementation. Thus preventing
14886 // taking an address of the capture to avoid invalid AS casts.
14887 if (LangOpts.OpenCL) {
14888 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14889 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14890 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14891 return QualType();
14892 }
14893 }
14894
14895 if (getLangOpts().C99) {
14896 // Implement C99-only parts of addressof rules.
14897 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14898 if (uOp->getOpcode() == UO_Deref)
14899 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14900 // (assuming the deref expression is valid).
14901 return uOp->getSubExpr()->getType();
14902 }
14903 // Technically, there should be a check for array subscript
14904 // expressions here, but the result of one is always an lvalue anyway.
14905 }
14906 ValueDecl *dcl = getPrimaryDecl(op);
14907
14908 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14909 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14910 op->getBeginLoc()))
14911 return QualType();
14912
14914 unsigned AddressOfError = AO_No_Error;
14915
14916 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14917 bool IsError = isSFINAEContext();
14918 Diag(OpLoc, IsError ? diag::err_typecheck_addrof_temporary
14919 : diag::ext_typecheck_addrof_temporary)
14920 << op->getType() << op->getSourceRange();
14921 if (IsError)
14922 return QualType();
14923 // Materialize the temporary as an lvalue so that we can take its address.
14924 OrigOp = op =
14925 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14926 } else if (isa<ObjCSelectorExpr>(op)) {
14927 return Context.getPointerType(op->getType());
14928 } else if (lval == Expr::LV_MemberFunction) {
14929 // If it's an instance method, make a member pointer.
14930 // The expression must have exactly the form &A::foo.
14931
14932 // If the underlying expression isn't a decl ref, give up.
14933 if (!isa<DeclRefExpr>(op)) {
14934 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14935 << OrigOp.get()->getSourceRange();
14936 return QualType();
14937 }
14938 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14940
14941 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14942 QualType MPTy = Context.getMemberPointerType(
14943 op->getType(), DRE->getQualifier(), MD->getParent());
14944
14945 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14946 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14947 // When pointer authentication is enabled, argument and return types of
14948 // vitual member functions must be complete. This is because vitrual
14949 // member function pointers are implemented using virtual dispatch
14950 // thunks and the thunks cannot be emitted if the argument or return
14951 // types are incomplete.
14952 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14953 SourceLocation DeclRefLoc,
14954 SourceLocation RetArgTypeLoc) {
14955 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
14956 Diag(DeclRefLoc,
14957 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14958 Diag(RetArgTypeLoc,
14959 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14960 << T;
14961 return true;
14962 }
14963 return false;
14964 };
14965 QualType RetTy = MD->getReturnType();
14966 bool IsIncomplete =
14967 !RetTy->isVoidType() &&
14968 ReturnOrParamTypeIsIncomplete(
14969 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14970 for (auto *PVD : MD->parameters())
14971 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14972 PVD->getBeginLoc());
14973 if (IsIncomplete)
14974 return QualType();
14975 }
14976
14977 // Under the MS ABI, lock down the inheritance model now.
14978 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14979 (void)isCompleteType(OpLoc, MPTy);
14980 return MPTy;
14981 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14982 // C99 6.5.3.2p1
14983 // The operand must be either an l-value or a function designator
14984 if (!op->getType()->isFunctionType()) {
14985 // Use a special diagnostic for loads from property references.
14986 if (isa<PseudoObjectExpr>(op)) {
14987 AddressOfError = AO_Property_Expansion;
14988 } else {
14989 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14990 << op->getType() << op->getSourceRange();
14991 return QualType();
14992 }
14993 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14994 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14995 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14996 }
14997
14998 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14999 // The operand cannot be a bit-field
15000 AddressOfError = AO_Bit_Field;
15001 } else if (op->getObjectKind() == OK_VectorComponent) {
15002 // The operand cannot be an element of a vector
15003 AddressOfError = AO_Vector_Element;
15004 } else if (op->getObjectKind() == OK_MatrixComponent) {
15005 // The operand cannot be an element of a matrix.
15006 AddressOfError = AO_Matrix_Element;
15007 } else if (dcl) { // C99 6.5.3.2p1
15008 // We have an lvalue with a decl. Make sure the decl is not declared
15009 // with the register storage-class specifier.
15010 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
15011 // in C++ it is not error to take address of a register
15012 // variable (c++03 7.1.1P3)
15013 if (vd->getStorageClass() == SC_Register &&
15015 AddressOfError = AO_Register_Variable;
15016 }
15017 } else if (isa<MSPropertyDecl>(dcl)) {
15018 AddressOfError = AO_Property_Expansion;
15019 } else if (isa<FunctionTemplateDecl>(dcl)) {
15020 return Context.OverloadTy;
15021 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
15022 // Okay: we can take the address of a field.
15023 // Could be a pointer to member, though, if there is an explicit
15024 // scope qualifier for the class.
15025
15026 // [C++26] [expr.prim.id.general]
15027 // If an id-expression E denotes a non-static non-type member
15028 // of some class C [...] and if E is a qualified-id, E is
15029 // not the un-parenthesized operand of the unary & operator [...]
15030 // the id-expression is transformed into a class member access expression.
15031 if (auto *DRE = dyn_cast<DeclRefExpr>(op);
15032 DRE && DRE->getQualifier() && !isa<ParenExpr>(OrigOp.get())) {
15033 DeclContext *Ctx = dcl->getDeclContext();
15034 if (Ctx && Ctx->isRecord()) {
15035 if (dcl->getType()->isReferenceType()) {
15036 Diag(OpLoc,
15037 diag::err_cannot_form_pointer_to_member_of_reference_type)
15038 << dcl->getDeclName() << dcl->getType();
15039 return QualType();
15040 }
15041
15042 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
15043 Ctx = Ctx->getParent();
15044
15045 QualType MPTy = Context.getMemberPointerType(
15046 op->getType(), DRE->getQualifier(), cast<CXXRecordDecl>(Ctx));
15047 // Under the MS ABI, lock down the inheritance model now.
15048 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15049 (void)isCompleteType(OpLoc, MPTy);
15050 return MPTy;
15051 }
15052 }
15056 llvm_unreachable("Unknown/unexpected decl type");
15057 }
15058
15059 if (AddressOfError != AO_No_Error) {
15060 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
15061 return QualType();
15062 }
15063
15064 if (lval == Expr::LV_IncompleteVoidType) {
15065 // Taking the address of a void variable is technically illegal, but we
15066 // allow it in cases which are otherwise valid.
15067 // Example: "extern void x; void* y = &x;".
15068 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
15069 }
15070
15071 // If the operand has type "type", the result has type "pointer to type".
15072 if (op->getType()->isObjCObjectType())
15073 return Context.getObjCObjectPointerType(op->getType());
15074
15075 // Cannot take the address of WebAssembly references or tables.
15076 if (Context.getTargetInfo().getTriple().isWasm()) {
15077 QualType OpTy = op->getType();
15078 if (OpTy.isWebAssemblyReferenceType()) {
15079 Diag(OpLoc, diag::err_wasm_ca_reference)
15080 << 1 << OrigOp.get()->getSourceRange();
15081 return QualType();
15082 }
15083 if (OpTy->isWebAssemblyTableType()) {
15084 Diag(OpLoc, diag::err_wasm_table_pr)
15085 << 1 << OrigOp.get()->getSourceRange();
15086 return QualType();
15087 }
15088 }
15089
15090 CheckAddressOfPackedMember(op);
15091
15092 return Context.getPointerType(op->getType());
15093}
15094
15095static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15096 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
15097 if (!DRE)
15098 return;
15099 const Decl *D = DRE->getDecl();
15100 if (!D)
15101 return;
15102 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
15103 if (!Param)
15104 return;
15105 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
15106 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15107 return;
15108 if (FunctionScopeInfo *FD = S.getCurFunction())
15109 FD->ModifiedNonNullParams.insert(Param);
15110}
15111
15112/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15114 SourceLocation OpLoc,
15115 bool IsAfterAmp = false) {
15116 ExprResult ConvResult = S.UsualUnaryConversions(Op);
15117 if (ConvResult.isInvalid())
15118 return QualType();
15119 Op = ConvResult.get();
15120 QualType OpTy = Op->getType();
15121 QualType Result;
15122
15124 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15125 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
15126 Op->getSourceRange());
15127 }
15128
15129 if (const PointerType *PT = OpTy->getAs<PointerType>())
15130 {
15131 Result = PT->getPointeeType();
15132 }
15133 else if (const ObjCObjectPointerType *OPT =
15135 Result = OPT->getPointeeType();
15136 else {
15138 if (PR.isInvalid()) return QualType();
15139 if (PR.get() != Op)
15140 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
15141 }
15142
15143 if (Result.isNull()) {
15144 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
15145 << OpTy << Op->getSourceRange();
15146 return QualType();
15147 }
15148
15149 if (Result->isVoidType()) {
15150 // C++ [expr.unary.op]p1:
15151 // [...] the expression to which [the unary * operator] is applied shall
15152 // be a pointer to an object type, or a pointer to a function type
15153 LangOptions LO = S.getLangOpts();
15154 if (LO.CPlusPlus)
15155 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
15156 << OpTy << Op->getSourceRange();
15157 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15158 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
15159 << OpTy << Op->getSourceRange();
15160 }
15161
15162 // Dereferences are usually l-values...
15163 VK = VK_LValue;
15164
15165 // ...except that certain expressions are never l-values in C.
15166 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15167 VK = VK_PRValue;
15168
15169 return Result;
15170}
15171
15172BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15174 switch (Kind) {
15175 default: llvm_unreachable("Unknown binop!");
15176 case tok::periodstar: Opc = BO_PtrMemD; break;
15177 case tok::arrowstar: Opc = BO_PtrMemI; break;
15178 case tok::star: Opc = BO_Mul; break;
15179 case tok::slash: Opc = BO_Div; break;
15180 case tok::percent: Opc = BO_Rem; break;
15181 case tok::plus: Opc = BO_Add; break;
15182 case tok::minus: Opc = BO_Sub; break;
15183 case tok::lessless: Opc = BO_Shl; break;
15184 case tok::greatergreater: Opc = BO_Shr; break;
15185 case tok::lessequal: Opc = BO_LE; break;
15186 case tok::less: Opc = BO_LT; break;
15187 case tok::greaterequal: Opc = BO_GE; break;
15188 case tok::greater: Opc = BO_GT; break;
15189 case tok::exclaimequal: Opc = BO_NE; break;
15190 case tok::equalequal: Opc = BO_EQ; break;
15191 case tok::spaceship: Opc = BO_Cmp; break;
15192 case tok::amp: Opc = BO_And; break;
15193 case tok::caret: Opc = BO_Xor; break;
15194 case tok::pipe: Opc = BO_Or; break;
15195 case tok::ampamp: Opc = BO_LAnd; break;
15196 case tok::pipepipe: Opc = BO_LOr; break;
15197 case tok::equal: Opc = BO_Assign; break;
15198 case tok::starequal: Opc = BO_MulAssign; break;
15199 case tok::slashequal: Opc = BO_DivAssign; break;
15200 case tok::percentequal: Opc = BO_RemAssign; break;
15201 case tok::plusequal: Opc = BO_AddAssign; break;
15202 case tok::minusequal: Opc = BO_SubAssign; break;
15203 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15204 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15205 case tok::ampequal: Opc = BO_AndAssign; break;
15206 case tok::caretequal: Opc = BO_XorAssign; break;
15207 case tok::pipeequal: Opc = BO_OrAssign; break;
15208 case tok::comma: Opc = BO_Comma; break;
15209 }
15210 return Opc;
15211}
15212
15214 tok::TokenKind Kind) {
15216 switch (Kind) {
15217 default: llvm_unreachable("Unknown unary op!");
15218 case tok::plusplus: Opc = UO_PreInc; break;
15219 case tok::minusminus: Opc = UO_PreDec; break;
15220 case tok::amp: Opc = UO_AddrOf; break;
15221 case tok::star: Opc = UO_Deref; break;
15222 case tok::plus: Opc = UO_Plus; break;
15223 case tok::minus: Opc = UO_Minus; break;
15224 case tok::tilde: Opc = UO_Not; break;
15225 case tok::exclaim: Opc = UO_LNot; break;
15226 case tok::kw___real: Opc = UO_Real; break;
15227 case tok::kw___imag: Opc = UO_Imag; break;
15228 case tok::kw___extension__: Opc = UO_Extension; break;
15229 }
15230 return Opc;
15231}
15232
15233const FieldDecl *
15235 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15236 // common for setters.
15237 // struct A {
15238 // int X;
15239 // -void setX(int X) { X = X; }
15240 // +void setX(int X) { this->X = X; }
15241 // };
15242
15243 // Only consider parameters for self assignment fixes.
15244 if (!isa<ParmVarDecl>(SelfAssigned))
15245 return nullptr;
15246 const auto *Method =
15247 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15248 if (!Method)
15249 return nullptr;
15250
15251 const CXXRecordDecl *Parent = Method->getParent();
15252 // In theory this is fixable if the lambda explicitly captures this, but
15253 // that's added complexity that's rarely going to be used.
15254 if (Parent->isLambda())
15255 return nullptr;
15256
15257 // FIXME: Use an actual Lookup operation instead of just traversing fields
15258 // in order to get base class fields.
15259 auto Field =
15260 llvm::find_if(Parent->fields(),
15261 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15262 return F->getDeclName() == Name;
15263 });
15264 return (Field != Parent->field_end()) ? *Field : nullptr;
15265}
15266
15267/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15268/// This warning suppressed in the event of macro expansions.
15269static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15270 SourceLocation OpLoc, bool IsBuiltin) {
15272 return;
15273 if (S.isUnevaluatedContext())
15274 return;
15275 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15276 return;
15277 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15278 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15279 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15280 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15281 if (!LHSDeclRef || !RHSDeclRef ||
15282 LHSDeclRef->getLocation().isMacroID() ||
15283 RHSDeclRef->getLocation().isMacroID())
15284 return;
15285 const ValueDecl *LHSDecl =
15286 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15287 const ValueDecl *RHSDecl =
15288 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15289 if (LHSDecl != RHSDecl)
15290 return;
15291 if (LHSDecl->getType().isVolatileQualified())
15292 return;
15293 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15294 if (RefTy->getPointeeType().isVolatileQualified())
15295 return;
15296
15297 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15298 : diag::warn_self_assignment_overloaded)
15299 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15300 << RHSExpr->getSourceRange();
15301 if (const FieldDecl *SelfAssignField =
15303 Diag << 1 << SelfAssignField
15304 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15305 else
15306 Diag << 0;
15307}
15308
15309/// Check if a bitwise-& is performed on an Objective-C pointer. This
15310/// is usually indicative of introspection within the Objective-C pointer.
15312 SourceLocation OpLoc) {
15313 if (!S.getLangOpts().ObjC)
15314 return;
15315
15316 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15317 const Expr *LHS = L.get();
15318 const Expr *RHS = R.get();
15319
15321 ObjCPointerExpr = LHS;
15322 OtherExpr = RHS;
15323 }
15324 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15325 ObjCPointerExpr = RHS;
15326 OtherExpr = LHS;
15327 }
15328
15329 // This warning is deliberately made very specific to reduce false
15330 // positives with logic that uses '&' for hashing. This logic mainly
15331 // looks for code trying to introspect into tagged pointers, which
15332 // code should generally never do.
15333 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15334 unsigned Diag = diag::warn_objc_pointer_masking;
15335 // Determine if we are introspecting the result of performSelectorXXX.
15336 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15337 // Special case messages to -performSelector and friends, which
15338 // can return non-pointer values boxed in a pointer value.
15339 // Some clients may wish to silence warnings in this subcase.
15340 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15341 Selector S = ME->getSelector();
15342 StringRef SelArg0 = S.getNameForSlot(0);
15343 if (SelArg0.starts_with("performSelector"))
15344 Diag = diag::warn_objc_pointer_masking_performSelector;
15345 }
15346
15347 S.Diag(OpLoc, Diag)
15348 << ObjCPointerExpr->getSourceRange();
15349 }
15350}
15351
15352// This helper function promotes a binary operator's operands (which are of a
15353// half vector type) to a vector of floats and then truncates the result to
15354// a vector of either half or short.
15356 BinaryOperatorKind Opc, QualType ResultTy,
15358 bool IsCompAssign, SourceLocation OpLoc,
15359 FPOptionsOverride FPFeatures) {
15360 auto &Context = S.getASTContext();
15361 assert((isVector(ResultTy, Context.HalfTy) ||
15362 isVector(ResultTy, Context.ShortTy)) &&
15363 "Result must be a vector of half or short");
15364 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15365 isVector(RHS.get()->getType(), Context.HalfTy) &&
15366 "both operands expected to be a half vector");
15367
15368 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15369 QualType BinOpResTy = RHS.get()->getType();
15370
15371 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15372 // change BinOpResTy to a vector of ints.
15373 if (isVector(ResultTy, Context.ShortTy))
15374 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15375
15376 if (IsCompAssign)
15377 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15378 ResultTy, VK, OK, OpLoc, FPFeatures,
15379 BinOpResTy, BinOpResTy);
15380
15381 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15382 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15383 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15384 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15385}
15386
15387/// Returns true if conversion between vectors of halfs and vectors of floats
15388/// is needed.
15389static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15390 Expr *E0, Expr *E1 = nullptr) {
15391 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15393 return false;
15394
15395 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15396 QualType Ty = E->IgnoreImplicit()->getType();
15397
15398 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15399 // to vectors of floats. Although the element type of the vectors is __fp16,
15400 // the vectors shouldn't be treated as storage-only types. See the
15401 // discussion here: https://reviews.llvm.org/rG825235c140e7
15402 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15403 if (VT->getVectorKind() == VectorKind::Neon)
15404 return false;
15405 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15406 }
15407 return false;
15408 };
15409
15410 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15411}
15412
15414 BinaryOperatorKind Opc, Expr *LHSExpr,
15415 Expr *RHSExpr, bool ForFoldExpression) {
15416 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15417 // The syntax only allows initializer lists on the RHS of assignment,
15418 // so we don't need to worry about accepting invalid code for
15419 // non-assignment operators.
15420 // C++11 5.17p9:
15421 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15422 // of x = {} is x = T().
15424 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15425 InitializedEntity Entity =
15427 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15428 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15429 if (Init.isInvalid())
15430 return Init;
15431 RHSExpr = Init.get();
15432 }
15433
15434 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15435 QualType ResultTy; // Result type of the binary operator.
15436 // The following two variables are used for compound assignment operators
15437 QualType CompLHSTy; // Type of LHS after promotions for computation
15438 QualType CompResultTy; // Type of computation result
15441 bool ConvertHalfVec = false;
15442
15443 if (!LHS.isUsable() || !RHS.isUsable())
15444 return ExprError();
15445
15446 if (getLangOpts().OpenCL) {
15447 QualType LHSTy = LHSExpr->getType();
15448 QualType RHSTy = RHSExpr->getType();
15449 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15450 // the ATOMIC_VAR_INIT macro.
15451 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15452 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15453 if (BO_Assign == Opc)
15454 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15455 else
15456 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15457 return ExprError();
15458 }
15459
15460 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15461 // only with a builtin functions and therefore should be disallowed here.
15462 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15463 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15464 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15465 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15466 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15467 return ExprError();
15468 }
15469 }
15470
15471 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15472 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15473
15474 switch (Opc) {
15475 case BO_Assign:
15476 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15477 if (getLangOpts().CPlusPlus &&
15478 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15479 VK = LHS.get()->getValueKind();
15480 OK = LHS.get()->getObjectKind();
15481 }
15482 if (!ResultTy.isNull()) {
15483 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15484 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15485
15486 // Avoid copying a block to the heap if the block is assigned to a local
15487 // auto variable that is declared in the same scope as the block. This
15488 // optimization is unsafe if the local variable is declared in an outer
15489 // scope. For example:
15490 //
15491 // BlockTy b;
15492 // {
15493 // b = ^{...};
15494 // }
15495 // // It is unsafe to invoke the block here if it wasn't copied to the
15496 // // heap.
15497 // b();
15498
15499 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15500 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15501 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15502 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15503 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15504
15506 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15508 }
15509 RecordModifiableNonNullParam(*this, LHS.get());
15510 break;
15511 case BO_PtrMemD:
15512 case BO_PtrMemI:
15513 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15514 Opc == BO_PtrMemI);
15515 break;
15516 case BO_Mul:
15517 case BO_Div:
15518 ConvertHalfVec = true;
15519 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15520 break;
15521 case BO_Rem:
15522 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15523 break;
15524 case BO_Add:
15525 ConvertHalfVec = true;
15526 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15527 break;
15528 case BO_Sub:
15529 ConvertHalfVec = true;
15530 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);
15531 break;
15532 case BO_Shl:
15533 case BO_Shr:
15534 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15535 break;
15536 case BO_LE:
15537 case BO_LT:
15538 case BO_GE:
15539 case BO_GT:
15540 ConvertHalfVec = true;
15541 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15542
15543 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
15544 !ForFoldExpression && BI && BI->isComparisonOp())
15545 Diag(OpLoc, diag::warn_consecutive_comparison)
15546 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
15547
15548 break;
15549 case BO_EQ:
15550 case BO_NE:
15551 ConvertHalfVec = true;
15552 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15553 break;
15554 case BO_Cmp:
15555 ConvertHalfVec = true;
15556 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15557 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15558 break;
15559 case BO_And:
15560 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15561 [[fallthrough]];
15562 case BO_Xor:
15563 case BO_Or:
15564 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15565 break;
15566 case BO_LAnd:
15567 case BO_LOr:
15568 ConvertHalfVec = true;
15569 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15570 break;
15571 case BO_MulAssign:
15572 case BO_DivAssign:
15573 ConvertHalfVec = true;
15574 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15575 CompLHSTy = CompResultTy;
15576 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15577 ResultTy =
15578 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15579 break;
15580 case BO_RemAssign:
15581 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15582 CompLHSTy = CompResultTy;
15583 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15584 ResultTy =
15585 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15586 break;
15587 case BO_AddAssign:
15588 ConvertHalfVec = true;
15589 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15590 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15591 ResultTy =
15592 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15593 break;
15594 case BO_SubAssign:
15595 ConvertHalfVec = true;
15596 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15597 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15598 ResultTy =
15599 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15600 break;
15601 case BO_ShlAssign:
15602 case BO_ShrAssign:
15603 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15604 CompLHSTy = CompResultTy;
15605 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15606 ResultTy =
15607 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15608 break;
15609 case BO_AndAssign:
15610 case BO_OrAssign: // fallthrough
15611 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15612 [[fallthrough]];
15613 case BO_XorAssign:
15614 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15615 CompLHSTy = CompResultTy;
15616 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15617 ResultTy =
15618 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15619 break;
15620 case BO_Comma:
15621 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15622 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15623 VK = RHS.get()->getValueKind();
15624 OK = RHS.get()->getObjectKind();
15625 }
15626 break;
15627 }
15628 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15629 return ExprError();
15630
15631 // Some of the binary operations require promoting operands of half vector to
15632 // float vectors and truncating the result back to half vector. For now, we do
15633 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15634 // arm64).
15635 assert(
15636 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15637 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15638 "both sides are half vectors or neither sides are");
15639 ConvertHalfVec =
15640 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15641
15642 // Check for array bounds violations for both sides of the BinaryOperator
15643 CheckArrayAccess(LHS.get());
15644 CheckArrayAccess(RHS.get());
15645
15646 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15647 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15648 &Context.Idents.get("object_setClass"),
15650 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15651 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15652 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15654 "object_setClass(")
15655 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15656 ",")
15657 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15658 }
15659 else
15660 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15661 }
15662 else if (const ObjCIvarRefExpr *OIRE =
15663 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15664 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15665
15666 // Opc is not a compound assignment if CompResultTy is null.
15667 if (CompResultTy.isNull()) {
15668 if (ConvertHalfVec)
15669 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15670 OpLoc, CurFPFeatureOverrides());
15671 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15672 VK, OK, OpLoc, CurFPFeatureOverrides());
15673 }
15674
15675 // Handle compound assignments.
15676 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15678 VK = VK_LValue;
15679 OK = LHS.get()->getObjectKind();
15680 }
15681
15682 // The LHS is not converted to the result type for fixed-point compound
15683 // assignment as the common type is computed on demand. Reset the CompLHSTy
15684 // to the LHS type we would have gotten after unary conversions.
15685 if (CompResultTy->isFixedPointType())
15686 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15687
15688 if (ConvertHalfVec)
15689 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15690 OpLoc, CurFPFeatureOverrides());
15691
15693 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15694 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15695}
15696
15697/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15698/// operators are mixed in a way that suggests that the programmer forgot that
15699/// comparison operators have higher precedence. The most typical example of
15700/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15702 SourceLocation OpLoc, Expr *LHSExpr,
15703 Expr *RHSExpr) {
15704 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15705 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15706
15707 // Check that one of the sides is a comparison operator and the other isn't.
15708 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15709 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15710 if (isLeftComp == isRightComp)
15711 return;
15712
15713 // Bitwise operations are sometimes used as eager logical ops.
15714 // Don't diagnose this.
15715 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15716 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15717 if (isLeftBitwise || isRightBitwise)
15718 return;
15719
15720 SourceRange DiagRange = isLeftComp
15721 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15722 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15723 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15724 SourceRange ParensRange =
15725 isLeftComp
15726 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15727 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15728
15729 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15730 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15731 SuggestParentheses(Self, OpLoc,
15732 Self.PDiag(diag::note_precedence_silence) << OpStr,
15733 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15734 SuggestParentheses(Self, OpLoc,
15735 Self.PDiag(diag::note_precedence_bitwise_first)
15737 ParensRange);
15738}
15739
15740/// It accepts a '&&' expr that is inside a '||' one.
15741/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15742/// in parentheses.
15743static void
15745 BinaryOperator *Bop) {
15746 assert(Bop->getOpcode() == BO_LAnd);
15747 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15748 << Bop->getSourceRange() << OpLoc;
15750 Self.PDiag(diag::note_precedence_silence)
15751 << Bop->getOpcodeStr(),
15752 Bop->getSourceRange());
15753}
15754
15755/// Look for '&&' in the left hand of a '||' expr.
15757 Expr *LHSExpr, Expr *RHSExpr) {
15758 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15759 if (Bop->getOpcode() == BO_LAnd) {
15760 // If it's "string_literal && a || b" don't warn since the precedence
15761 // doesn't matter.
15762 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15763 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15764 } else if (Bop->getOpcode() == BO_LOr) {
15765 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15766 // If it's "a || b && string_literal || c" we didn't warn earlier for
15767 // "a || b && string_literal", but warn now.
15768 if (RBop->getOpcode() == BO_LAnd &&
15769 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15770 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15771 }
15772 }
15773 }
15774}
15775
15776/// Look for '&&' in the right hand of a '||' expr.
15778 Expr *LHSExpr, Expr *RHSExpr) {
15779 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15780 if (Bop->getOpcode() == BO_LAnd) {
15781 // If it's "a || b && string_literal" don't warn since the precedence
15782 // doesn't matter.
15783 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15784 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15785 }
15786 }
15787}
15788
15789/// Look for bitwise op in the left or right hand of a bitwise op with
15790/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15791/// the '&' expression in parentheses.
15793 SourceLocation OpLoc, Expr *SubExpr) {
15794 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15795 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15796 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15797 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15798 << Bop->getSourceRange() << OpLoc;
15799 SuggestParentheses(S, Bop->getOperatorLoc(),
15800 S.PDiag(diag::note_precedence_silence)
15801 << Bop->getOpcodeStr(),
15802 Bop->getSourceRange());
15803 }
15804 }
15805}
15806
15808 Expr *SubExpr, StringRef Shift) {
15809 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15810 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15811 StringRef Op = Bop->getOpcodeStr();
15812 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15813 << Bop->getSourceRange() << OpLoc << Shift << Op;
15814 SuggestParentheses(S, Bop->getOperatorLoc(),
15815 S.PDiag(diag::note_precedence_silence) << Op,
15816 Bop->getSourceRange());
15817 }
15818 }
15819}
15820
15822 Expr *LHSExpr, Expr *RHSExpr) {
15823 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15824 if (!OCE)
15825 return;
15826
15827 FunctionDecl *FD = OCE->getDirectCallee();
15828 if (!FD || !FD->isOverloadedOperator())
15829 return;
15830
15832 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15833 return;
15834
15835 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15836 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15837 << (Kind == OO_LessLess);
15839 S.PDiag(diag::note_precedence_silence)
15840 << (Kind == OO_LessLess ? "<<" : ">>"),
15841 OCE->getSourceRange());
15843 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15844 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15845}
15846
15847/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15848/// precedence.
15850 SourceLocation OpLoc, Expr *LHSExpr,
15851 Expr *RHSExpr){
15852 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15854 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15855
15856 // Diagnose "arg1 & arg2 | arg3"
15857 if ((Opc == BO_Or || Opc == BO_Xor) &&
15858 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15859 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15860 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15861 }
15862
15863 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15864 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15865 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15866 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15867 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15868 }
15869
15870 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15871 || Opc == BO_Shr) {
15872 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15873 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15874 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15875 }
15876
15877 // Warn on overloaded shift operators and comparisons, such as:
15878 // cout << 5 == 4;
15880 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15881}
15882
15884 tok::TokenKind Kind,
15885 Expr *LHSExpr, Expr *RHSExpr) {
15886 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15887 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15888 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15889
15890 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15891 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15892
15896
15897 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
15898 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
15899
15900 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15901}
15902
15904 UnresolvedSetImpl &Functions) {
15906 if (OverOp != OO_None && OverOp != OO_Equal)
15907 LookupOverloadedOperatorName(OverOp, S, Functions);
15908
15909 // In C++20 onwards, we may have a second operator to look up.
15910 if (getLangOpts().CPlusPlus20) {
15912 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15913 }
15914}
15915
15916/// Build an overloaded binary operator expression in the given scope.
15919 Expr *LHS, Expr *RHS) {
15920 switch (Opc) {
15921 case BO_Assign:
15922 // In the non-overloaded case, we warn about self-assignment (x = x) for
15923 // both simple assignment and certain compound assignments where algebra
15924 // tells us the operation yields a constant result. When the operator is
15925 // overloaded, we can't do the latter because we don't want to assume that
15926 // those algebraic identities still apply; for example, a path-building
15927 // library might use operator/= to append paths. But it's still reasonable
15928 // to assume that simple assignment is just moving/copying values around
15929 // and so self-assignment is likely a bug.
15930 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15931 [[fallthrough]];
15932 case BO_DivAssign:
15933 case BO_RemAssign:
15934 case BO_SubAssign:
15935 case BO_AndAssign:
15936 case BO_OrAssign:
15937 case BO_XorAssign:
15938 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15939 break;
15940 default:
15941 break;
15942 }
15943
15944 // Find all of the overloaded operators visible from this point.
15945 UnresolvedSet<16> Functions;
15946 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15947
15948 // Build the (potentially-overloaded, potentially-dependent)
15949 // binary operation.
15950 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15951}
15952
15954 BinaryOperatorKind Opc, Expr *LHSExpr,
15955 Expr *RHSExpr, bool ForFoldExpression) {
15956 if (!LHSExpr || !RHSExpr)
15957 return ExprError();
15958
15959 // We want to end up calling one of SemaPseudoObject::checkAssignment
15960 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15961 // both expressions are overloadable or either is type-dependent),
15962 // or CreateBuiltinBinOp (in any other case). We also want to get
15963 // any placeholder types out of the way.
15964
15965 // Handle pseudo-objects in the LHS.
15966 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15967 // Assignments with a pseudo-object l-value need special analysis.
15968 if (pty->getKind() == BuiltinType::PseudoObject &&
15970 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15971
15972 // Don't resolve overloads if the other type is overloadable.
15973 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15974 // We can't actually test that if we still have a placeholder,
15975 // though. Fortunately, none of the exceptions we see in that
15976 // code below are valid when the LHS is an overload set. Note
15977 // that an overload set can be dependently-typed, but it never
15978 // instantiates to having an overloadable type.
15979 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15980 if (resolvedRHS.isInvalid()) return ExprError();
15981 RHSExpr = resolvedRHS.get();
15982
15983 if (RHSExpr->isTypeDependent() ||
15984 RHSExpr->getType()->isOverloadableType())
15985 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15986 }
15987
15988 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15989 // template, diagnose the missing 'template' keyword instead of diagnosing
15990 // an invalid use of a bound member function.
15991 //
15992 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15993 // to C++1z [over.over]/1.4, but we already checked for that case above.
15994 if (Opc == BO_LT && inTemplateInstantiation() &&
15995 (pty->getKind() == BuiltinType::BoundMember ||
15996 pty->getKind() == BuiltinType::Overload)) {
15997 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15998 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15999 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
16000 return isa<FunctionTemplateDecl>(ND);
16001 })) {
16002 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16003 : OE->getNameLoc(),
16004 diag::err_template_kw_missing)
16005 << OE->getName().getAsIdentifierInfo();
16006 return ExprError();
16007 }
16008 }
16009
16010 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
16011 if (LHS.isInvalid()) return ExprError();
16012 LHSExpr = LHS.get();
16013 }
16014
16015 // Handle pseudo-objects in the RHS.
16016 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16017 // An overload in the RHS can potentially be resolved by the type
16018 // being assigned to.
16019 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16020 if (getLangOpts().CPlusPlus &&
16021 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16022 LHSExpr->getType()->isOverloadableType()))
16023 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16024
16025 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16026 ForFoldExpression);
16027 }
16028
16029 // Don't resolve overloads if the other type is overloadable.
16030 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16031 LHSExpr->getType()->isOverloadableType())
16032 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16033
16034 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16035 if (!resolvedRHS.isUsable()) return ExprError();
16036 RHSExpr = resolvedRHS.get();
16037 }
16038
16039 if (getLangOpts().HLSL && (LHSExpr->getType()->isHLSLResourceRecord() ||
16040 LHSExpr->getType()->isHLSLResourceRecordArray())) {
16041 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, OpLoc))
16042 return ExprError();
16043 }
16044
16045 if (getLangOpts().CPlusPlus) {
16046 // Otherwise, build an overloaded op if either expression is type-dependent
16047 // or has an overloadable type.
16048 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16049 LHSExpr->getType()->isOverloadableType() ||
16050 RHSExpr->getType()->isOverloadableType())
16051 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16052 }
16053
16054 if (getLangOpts().RecoveryAST &&
16055 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16056 assert(!getLangOpts().CPlusPlus);
16057 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16058 "Should only occur in error-recovery path.");
16060 // C [6.15.16] p3:
16061 // An assignment expression has the value of the left operand after the
16062 // assignment, but is not an lvalue.
16064 Context, LHSExpr, RHSExpr, Opc,
16066 OpLoc, CurFPFeatureOverrides());
16067 QualType ResultType;
16068 switch (Opc) {
16069 case BO_Assign:
16070 ResultType = LHSExpr->getType().getUnqualifiedType();
16071 break;
16072 case BO_LT:
16073 case BO_GT:
16074 case BO_LE:
16075 case BO_GE:
16076 case BO_EQ:
16077 case BO_NE:
16078 case BO_LAnd:
16079 case BO_LOr:
16080 // These operators have a fixed result type regardless of operands.
16081 ResultType = Context.IntTy;
16082 break;
16083 case BO_Comma:
16084 ResultType = RHSExpr->getType();
16085 break;
16086 default:
16087 ResultType = Context.DependentTy;
16088 break;
16089 }
16090 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
16091 VK_PRValue, OK_Ordinary, OpLoc,
16093 }
16094
16095 // Build a built-in binary operation.
16096 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16097}
16098
16100 if (T.isNull() || T->isDependentType())
16101 return false;
16102
16103 if (!Ctx.isPromotableIntegerType(T))
16104 return true;
16105
16106 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
16107}
16108
16110 UnaryOperatorKind Opc, Expr *InputExpr,
16111 bool IsAfterAmp) {
16112 ExprResult Input = InputExpr;
16115 QualType resultType;
16116 bool CanOverflow = false;
16117
16118 bool ConvertHalfVec = false;
16119 if (getLangOpts().OpenCL) {
16120 QualType Ty = InputExpr->getType();
16121 // The only legal unary operation for atomics is '&'.
16122 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16123 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16124 // only with a builtin functions and therefore should be disallowed here.
16125 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16126 || Ty->isBlockPointerType())) {
16127 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16128 << InputExpr->getType()
16129 << Input.get()->getSourceRange());
16130 }
16131 }
16132
16133 if (getLangOpts().HLSL && OpLoc.isValid()) {
16134 if (Opc == UO_AddrOf)
16135 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
16136 if (Opc == UO_Deref)
16137 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
16138 }
16139
16140 if (InputExpr->isTypeDependent() &&
16141 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
16142 resultType = Context.DependentTy;
16143 } else {
16144 switch (Opc) {
16145 case UO_PreInc:
16146 case UO_PreDec:
16147 case UO_PostInc:
16148 case UO_PostDec:
16149 resultType =
16150 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
16151 Opc == UO_PreInc || Opc == UO_PostInc,
16152 Opc == UO_PreInc || Opc == UO_PreDec);
16153 CanOverflow = isOverflowingIntegerType(Context, resultType);
16154 break;
16155 case UO_AddrOf:
16156 resultType = CheckAddressOfOperand(Input, OpLoc);
16157 CheckAddressOfNoDeref(InputExpr);
16158 RecordModifiableNonNullParam(*this, InputExpr);
16159 break;
16160 case UO_Deref: {
16162 if (Input.isInvalid())
16163 return ExprError();
16164 resultType =
16165 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
16166 break;
16167 }
16168 case UO_Plus:
16169 case UO_Minus:
16170 CanOverflow = Opc == UO_Minus &&
16172 Input = UsualUnaryConversions(Input.get());
16173 if (Input.isInvalid())
16174 return ExprError();
16175 // Unary plus and minus require promoting an operand of half vector to a
16176 // float vector and truncating the result back to a half vector. For now,
16177 // we do this only when HalfArgsAndReturns is set (that is, when the
16178 // target is arm or arm64).
16179 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
16180
16181 // If the operand is a half vector, promote it to a float vector.
16182 if (ConvertHalfVec)
16183 Input = convertVector(Input.get(), Context.FloatTy, *this);
16184 resultType = Input.get()->getType();
16185 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16186 break;
16187 else if (resultType->isVectorType() &&
16188 // The z vector extensions don't allow + or - with bool vectors.
16189 (!Context.getLangOpts().ZVector ||
16190 resultType->castAs<VectorType>()->getVectorKind() !=
16192 break;
16193 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16194 break;
16195 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16196 Opc == UO_Plus && resultType->isPointerType())
16197 break;
16198
16199 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16200 << resultType << Input.get()->getSourceRange());
16201
16202 case UO_Not: // bitwise complement
16203 Input = UsualUnaryConversions(Input.get());
16204 if (Input.isInvalid())
16205 return ExprError();
16206 resultType = Input.get()->getType();
16207 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16208 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16209 // C99 does not support '~' for complex conjugation.
16210 Diag(OpLoc, diag::ext_integer_complement_complex)
16211 << resultType << Input.get()->getSourceRange();
16212 else if (resultType->hasIntegerRepresentation())
16213 break;
16214 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16215 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16216 // on vector float types.
16217 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16218 if (!T->isIntegerType())
16219 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16220 << resultType << Input.get()->getSourceRange());
16221 } else {
16222 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16223 << resultType << Input.get()->getSourceRange());
16224 }
16225 break;
16226
16227 case UO_LNot: // logical negation
16228 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16230 if (Input.isInvalid())
16231 return ExprError();
16232 resultType = Input.get()->getType();
16233
16234 // Though we still have to promote half FP to float...
16235 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16236 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
16237 .get();
16238 resultType = Context.FloatTy;
16239 }
16240
16241 // WebAsembly tables can't be used in unary expressions.
16242 if (resultType->isPointerType() &&
16244 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16245 << resultType << Input.get()->getSourceRange());
16246 }
16247
16248 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16249 // C99 6.5.3.3p1: ok, fallthrough;
16250 if (Context.getLangOpts().CPlusPlus) {
16251 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16252 // operand contextually converted to bool.
16253 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16254 ScalarTypeToBooleanCastKind(resultType));
16255 } else if (Context.getLangOpts().OpenCL &&
16256 Context.getLangOpts().OpenCLVersion < 120) {
16257 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16258 // operate on scalar float types.
16259 if (!resultType->isIntegerType() && !resultType->isPointerType())
16260 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16261 << resultType << Input.get()->getSourceRange());
16262 }
16263 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16264 !resultType->hasBooleanRepresentation()) {
16265 // HLSL unary logical 'not' behaves like C++, which states that the
16266 // operand is converted to bool and the result is bool, however HLSL
16267 // extends this property to vectors.
16268 const VectorType *VTy = resultType->castAs<VectorType>();
16269 resultType =
16270 Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
16271
16272 Input = ImpCastExprToType(
16273 Input.get(), resultType,
16275 .get();
16276 break;
16277 } else if (resultType->isExtVectorType()) {
16278 if (Context.getLangOpts().OpenCL &&
16279 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16280 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16281 // operate on vector float types.
16282 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16283 if (!T->isIntegerType())
16284 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16285 << resultType << Input.get()->getSourceRange());
16286 }
16287 // Vector logical not returns the signed variant of the operand type.
16288 resultType = GetSignedVectorType(resultType);
16289 break;
16290 } else if (Context.getLangOpts().CPlusPlus &&
16291 resultType->isVectorType()) {
16292 const VectorType *VTy = resultType->castAs<VectorType>();
16293 if (VTy->getVectorKind() != VectorKind::Generic)
16294 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16295 << resultType << Input.get()->getSourceRange());
16296
16297 // Vector logical not returns the signed variant of the operand type.
16298 resultType = GetSignedVectorType(resultType);
16299 break;
16300 } else {
16301 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16302 << resultType << Input.get()->getSourceRange());
16303 }
16304
16305 // LNot always has type int. C99 6.5.3.3p5.
16306 // In C++, it's bool. C++ 5.3.1p8
16307 resultType = Context.getLogicalOperationType();
16308 break;
16309 case UO_Real:
16310 case UO_Imag:
16311 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16312 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16313 // ordinary complex l-values to ordinary l-values and all other values to
16314 // r-values.
16315 if (Input.isInvalid())
16316 return ExprError();
16317 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16318 if (Input.get()->isGLValue() &&
16319 Input.get()->getObjectKind() == OK_Ordinary)
16320 VK = Input.get()->getValueKind();
16321 } else if (!getLangOpts().CPlusPlus) {
16322 // In C, a volatile scalar is read by __imag. In C++, it is not.
16323 Input = DefaultLvalueConversion(Input.get());
16324 }
16325 break;
16326 case UO_Extension:
16327 resultType = Input.get()->getType();
16328 VK = Input.get()->getValueKind();
16329 OK = Input.get()->getObjectKind();
16330 break;
16331 case UO_Coawait:
16332 // It's unnecessary to represent the pass-through operator co_await in the
16333 // AST; just return the input expression instead.
16334 assert(!Input.get()->getType()->isDependentType() &&
16335 "the co_await expression must be non-dependant before "
16336 "building operator co_await");
16337 return Input;
16338 }
16339 }
16340 if (resultType.isNull() || Input.isInvalid())
16341 return ExprError();
16342
16343 // Check for array bounds violations in the operand of the UnaryOperator,
16344 // except for the '*' and '&' operators that have to be handled specially
16345 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16346 // that are explicitly defined as valid by the standard).
16347 if (Opc != UO_AddrOf && Opc != UO_Deref)
16348 CheckArrayAccess(Input.get());
16349
16350 auto *UO =
16351 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16352 OpLoc, CanOverflow, CurFPFeatureOverrides());
16353
16354 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16355 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16357 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16358
16359 // Convert the result back to a half vector.
16360 if (ConvertHalfVec)
16361 return convertVector(UO, Context.HalfTy, *this);
16362 return UO;
16363}
16364
16366 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16367 if (!DRE->getQualifier())
16368 return false;
16369
16370 ValueDecl *VD = DRE->getDecl();
16371 if (!VD->isCXXClassMember())
16372 return false;
16373
16375 return true;
16376 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16377 return Method->isImplicitObjectMemberFunction();
16378
16379 return false;
16380 }
16381
16382 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16383 if (!ULE->getQualifier())
16384 return false;
16385
16386 for (NamedDecl *D : ULE->decls()) {
16387 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16388 if (Method->isImplicitObjectMemberFunction())
16389 return true;
16390 } else {
16391 // Overload set does not contain methods.
16392 break;
16393 }
16394 }
16395
16396 return false;
16397 }
16398
16399 return false;
16400}
16401
16403 UnaryOperatorKind Opc, Expr *Input,
16404 bool IsAfterAmp) {
16405 // First things first: handle placeholders so that the
16406 // overloaded-operator check considers the right type.
16407 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16408 // Increment and decrement of pseudo-object references.
16409 if (pty->getKind() == BuiltinType::PseudoObject &&
16411 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
16412
16413 // extension is always a builtin operator.
16414 if (Opc == UO_Extension)
16415 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16416
16417 // & gets special logic for several kinds of placeholder.
16418 // The builtin code knows what to do.
16419 if (Opc == UO_AddrOf &&
16420 (pty->getKind() == BuiltinType::Overload ||
16421 pty->getKind() == BuiltinType::UnknownAny ||
16422 pty->getKind() == BuiltinType::BoundMember))
16423 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16424
16425 // Anything else needs to be handled now.
16427 if (Result.isInvalid()) return ExprError();
16428 Input = Result.get();
16429 }
16430
16431 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16433 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16434 // Find all of the overloaded operators visible from this point.
16435 UnresolvedSet<16> Functions;
16437 if (S && OverOp != OO_None)
16438 LookupOverloadedOperatorName(OverOp, S, Functions);
16439
16440 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16441 }
16442
16443 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16444}
16445
16447 Expr *Input, bool IsAfterAmp) {
16448 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16449 IsAfterAmp);
16450}
16451
16453 LabelDecl *TheDecl) {
16454 TheDecl->markUsed(Context);
16455 // Create the AST node. The address of a label always has type 'void*'.
16456 auto *Res = new (Context) AddrLabelExpr(
16457 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16458
16459 if (getCurFunction())
16460 getCurFunction()->AddrLabels.push_back(Res);
16461
16462 return Res;
16463}
16464
16467 // Make sure we diagnose jumping into a statement expression.
16469}
16470
16472 // Note that function is also called by TreeTransform when leaving a
16473 // StmtExpr scope without rebuilding anything.
16474
16477}
16478
16480 SourceLocation RPLoc) {
16481 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16482}
16483
16485 SourceLocation RPLoc, unsigned TemplateDepth) {
16486 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16487 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16488
16491 assert(!Cleanup.exprNeedsCleanups() &&
16492 "cleanups within StmtExpr not correctly bound!");
16494
16495 // FIXME: there are a variety of strange constraints to enforce here, for
16496 // example, it is not possible to goto into a stmt expression apparently.
16497 // More semantic analysis is needed.
16498
16499 // If there are sub-stmts in the compound stmt, take the type of the last one
16500 // as the type of the stmtexpr.
16501 QualType Ty = Context.VoidTy;
16502 bool StmtExprMayBindToTemp = false;
16503 if (!Compound->body_empty()) {
16504 if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
16505 if (const Expr *Value = LastStmt->getExprStmt()) {
16506 StmtExprMayBindToTemp = true;
16507 Ty = Value->getType();
16508 }
16509 }
16510 }
16511
16512 // FIXME: Check that expression type is complete/non-abstract; statement
16513 // expressions are not lvalues.
16514 Expr *ResStmtExpr =
16515 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16516 if (StmtExprMayBindToTemp)
16517 return MaybeBindToTemporary(ResStmtExpr);
16518 return ResStmtExpr;
16519}
16520
16522 if (ER.isInvalid())
16523 return ExprError();
16524
16525 // Do function/array conversion on the last expression, but not
16526 // lvalue-to-rvalue. However, initialize an unqualified type.
16528 if (ER.isInvalid())
16529 return ExprError();
16530 Expr *E = ER.get();
16531
16532 if (E->isTypeDependent())
16533 return E;
16534
16535 // In ARC, if the final expression ends in a consume, splice
16536 // the consume out and bind it later. In the alternate case
16537 // (when dealing with a retainable type), the result
16538 // initialization will create a produce. In both cases the
16539 // result will be +1, and we'll need to balance that out with
16540 // a bind.
16541 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16542 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16543 return Cast->getSubExpr();
16544
16545 // FIXME: Provide a better location for the initialization.
16549 SourceLocation(), E);
16550}
16551
16553 TypeSourceInfo *TInfo,
16554 ArrayRef<OffsetOfComponent> Components,
16555 SourceLocation RParenLoc) {
16556 QualType ArgTy = TInfo->getType();
16557 bool Dependent = ArgTy->isDependentType();
16558 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16559
16560 // We must have at least one component that refers to the type, and the first
16561 // one is known to be a field designator. Verify that the ArgTy represents
16562 // a struct/union/class.
16563 if (!Dependent && !ArgTy->isRecordType())
16564 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16565 << ArgTy << TypeRange);
16566
16567 // Type must be complete per C99 7.17p3 because a declaring a variable
16568 // with an incomplete type would be ill-formed.
16569 if (!Dependent
16570 && RequireCompleteType(BuiltinLoc, ArgTy,
16571 diag::err_offsetof_incomplete_type, TypeRange))
16572 return ExprError();
16573
16574 bool DidWarnAboutNonPOD = false;
16575 QualType CurrentType = ArgTy;
16578 for (const OffsetOfComponent &OC : Components) {
16579 if (OC.isBrackets) {
16580 // Offset of an array sub-field. TODO: Should we allow vector elements?
16581 if (!CurrentType->isDependentType()) {
16582 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16583 if(!AT)
16584 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16585 << CurrentType);
16586 CurrentType = AT->getElementType();
16587 } else
16588 CurrentType = Context.DependentTy;
16589
16590 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16591 if (IdxRval.isInvalid())
16592 return ExprError();
16593 Expr *Idx = IdxRval.get();
16594
16595 // The expression must be an integral expression.
16596 // FIXME: An integral constant expression?
16597 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16598 !Idx->getType()->isIntegerType())
16599 return ExprError(
16600 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16601 << Idx->getSourceRange());
16602
16603 // Record this array index.
16604 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16605 Exprs.push_back(Idx);
16606 continue;
16607 }
16608
16609 // Offset of a field.
16610 if (CurrentType->isDependentType()) {
16611 // We have the offset of a field, but we can't look into the dependent
16612 // type. Just record the identifier of the field.
16613 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16614 CurrentType = Context.DependentTy;
16615 continue;
16616 }
16617
16618 // We need to have a complete type to look into.
16619 if (RequireCompleteType(OC.LocStart, CurrentType,
16620 diag::err_offsetof_incomplete_type))
16621 return ExprError();
16622
16623 // Look for the designated field.
16624 auto *RD = CurrentType->getAsRecordDecl();
16625 if (!RD)
16626 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16627 << CurrentType);
16628
16629 // C++ [lib.support.types]p5:
16630 // The macro offsetof accepts a restricted set of type arguments in this
16631 // International Standard. type shall be a POD structure or a POD union
16632 // (clause 9).
16633 // C++11 [support.types]p4:
16634 // If type is not a standard-layout class (Clause 9), the results are
16635 // undefined.
16636 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16637 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16638 unsigned DiagID =
16639 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16640 : diag::ext_offsetof_non_pod_type;
16641
16642 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16643 Diag(BuiltinLoc, DiagID)
16644 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16645 DidWarnAboutNonPOD = true;
16646 }
16647 }
16648
16649 // Look for the field.
16650 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16651 LookupQualifiedName(R, RD);
16652 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16653 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16654 if (!MemberDecl) {
16655 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16656 MemberDecl = IndirectMemberDecl->getAnonField();
16657 }
16658
16659 if (!MemberDecl) {
16660 // Lookup could be ambiguous when looking up a placeholder variable
16661 // __builtin_offsetof(S, _).
16662 // In that case we would already have emitted a diagnostic
16663 if (!R.isAmbiguous())
16664 Diag(BuiltinLoc, diag::err_no_member)
16665 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16666 return ExprError();
16667 }
16668
16669 // C99 7.17p3:
16670 // (If the specified member is a bit-field, the behavior is undefined.)
16671 //
16672 // We diagnose this as an error.
16673 if (MemberDecl->isBitField()) {
16674 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16675 << MemberDecl->getDeclName()
16676 << SourceRange(BuiltinLoc, RParenLoc);
16677 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16678 return ExprError();
16679 }
16680
16681 RecordDecl *Parent = MemberDecl->getParent();
16682 if (IndirectMemberDecl)
16683 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16684
16685 // If the member was found in a base class, introduce OffsetOfNodes for
16686 // the base class indirections.
16687 CXXBasePaths Paths;
16688 if (IsDerivedFrom(OC.LocStart, CurrentType,
16689 Context.getCanonicalTagType(Parent), Paths)) {
16690 if (Paths.getDetectedVirtual()) {
16691 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16692 << MemberDecl->getDeclName()
16693 << SourceRange(BuiltinLoc, RParenLoc);
16694 return ExprError();
16695 }
16696
16697 CXXBasePath &Path = Paths.front();
16698 for (const CXXBasePathElement &B : Path)
16699 Comps.push_back(OffsetOfNode(B.Base));
16700 }
16701
16702 if (IndirectMemberDecl) {
16703 for (auto *FI : IndirectMemberDecl->chain()) {
16704 assert(isa<FieldDecl>(FI));
16705 Comps.push_back(OffsetOfNode(OC.LocStart,
16706 cast<FieldDecl>(FI), OC.LocEnd));
16707 }
16708 } else
16709 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16710
16711 CurrentType = MemberDecl->getType().getNonReferenceType();
16712 }
16713
16714 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16715 Comps, Exprs, RParenLoc);
16716}
16717
16719 SourceLocation BuiltinLoc,
16721 ParsedType ParsedArgTy,
16722 ArrayRef<OffsetOfComponent> Components,
16723 SourceLocation RParenLoc) {
16724
16725 TypeSourceInfo *ArgTInfo;
16726 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16727 if (ArgTy.isNull())
16728 return ExprError();
16729
16730 if (!ArgTInfo)
16731 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16732
16733 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16734}
16735
16736
16738 Expr *CondExpr,
16739 Expr *LHSExpr, Expr *RHSExpr,
16740 SourceLocation RPLoc) {
16741 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16742
16745 QualType resType;
16746 bool CondIsTrue = false;
16747 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16748 resType = Context.DependentTy;
16749 } else {
16750 // The conditional expression is required to be a constant expression.
16751 llvm::APSInt condEval(32);
16753 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16754 if (CondICE.isInvalid())
16755 return ExprError();
16756 CondExpr = CondICE.get();
16757 CondIsTrue = condEval.getZExtValue();
16758
16759 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16760 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16761
16762 resType = ActiveExpr->getType();
16763 VK = ActiveExpr->getValueKind();
16764 OK = ActiveExpr->getObjectKind();
16765 }
16766
16767 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16768 resType, VK, OK, RPLoc, CondIsTrue);
16769}
16770
16771//===----------------------------------------------------------------------===//
16772// Clang Extensions.
16773//===----------------------------------------------------------------------===//
16774
16775void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16777
16778 if (LangOpts.CPlusPlus) {
16780 Decl *ManglingContextDecl;
16781 std::tie(MCtx, ManglingContextDecl) =
16782 getCurrentMangleNumberContext(Block->getDeclContext());
16783 if (MCtx) {
16784 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16785 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16786 }
16787 }
16788
16789 PushBlockScope(CurScope, Block);
16790 CurContext->addDecl(Block);
16791 if (CurScope)
16792 PushDeclContext(CurScope, Block);
16793 else
16794 CurContext = Block;
16795
16797
16798 // Enter a new evaluation context to insulate the block from any
16799 // cleanups from the enclosing full-expression.
16802}
16803
16805 Scope *CurScope) {
16806 assert(ParamInfo.getIdentifier() == nullptr &&
16807 "block-id should have no identifier!");
16808 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16809 BlockScopeInfo *CurBlock = getCurBlock();
16810
16811 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16812 QualType T = Sig->getType();
16814
16815 // GetTypeForDeclarator always produces a function type for a block
16816 // literal signature. Furthermore, it is always a FunctionProtoType
16817 // unless the function was written with a typedef.
16818 assert(T->isFunctionType() &&
16819 "GetTypeForDeclarator made a non-function block signature");
16820
16821 // Look for an explicit signature in that function type.
16822 FunctionProtoTypeLoc ExplicitSignature;
16823
16824 if ((ExplicitSignature = Sig->getTypeLoc()
16826
16827 // Check whether that explicit signature was synthesized by
16828 // GetTypeForDeclarator. If so, don't save that as part of the
16829 // written signature.
16830 if (ExplicitSignature.getLocalRangeBegin() ==
16831 ExplicitSignature.getLocalRangeEnd()) {
16832 // This would be much cheaper if we stored TypeLocs instead of
16833 // TypeSourceInfos.
16834 TypeLoc Result = ExplicitSignature.getReturnLoc();
16835 unsigned Size = Result.getFullDataSize();
16836 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16837 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16838
16839 ExplicitSignature = FunctionProtoTypeLoc();
16840 }
16841 }
16842
16843 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16844 CurBlock->FunctionType = T;
16845
16846 const auto *Fn = T->castAs<FunctionType>();
16847 QualType RetTy = Fn->getReturnType();
16848 bool isVariadic =
16849 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16850
16851 CurBlock->TheDecl->setIsVariadic(isVariadic);
16852
16853 // Context.DependentTy is used as a placeholder for a missing block
16854 // return type. TODO: what should we do with declarators like:
16855 // ^ * { ... }
16856 // If the answer is "apply template argument deduction"....
16857 if (RetTy != Context.DependentTy) {
16858 CurBlock->ReturnType = RetTy;
16859 CurBlock->TheDecl->setBlockMissingReturnType(false);
16860 CurBlock->HasImplicitReturnType = false;
16861 }
16862
16863 // Push block parameters from the declarator if we had them.
16865 if (ExplicitSignature) {
16866 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16867 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16868 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16869 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16870 // Diagnose this as an extension in C17 and earlier.
16871 if (!getLangOpts().C23)
16872 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16873 }
16874 Params.push_back(Param);
16875 }
16876
16877 // Fake up parameter variables if we have a typedef, like
16878 // ^ fntype { ... }
16879 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16880 for (const auto &I : Fn->param_types()) {
16882 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16883 Params.push_back(Param);
16884 }
16885 }
16886
16887 // Set the parameters on the block decl.
16888 if (!Params.empty()) {
16889 CurBlock->TheDecl->setParams(Params);
16891 /*CheckParameterNames=*/false);
16892 }
16893
16894 // Finally we can process decl attributes.
16895 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16896
16897 // Put the parameter variables in scope.
16898 for (auto *AI : CurBlock->TheDecl->parameters()) {
16899 AI->setOwningFunction(CurBlock->TheDecl);
16900
16901 // If this has an identifier, add it to the scope stack.
16902 if (AI->getIdentifier()) {
16903 CheckShadow(CurBlock->TheScope, AI);
16904
16905 PushOnScopeChains(AI, CurBlock->TheScope);
16906 }
16907
16908 if (AI->isInvalidDecl())
16909 CurBlock->TheDecl->setInvalidDecl();
16910 }
16911}
16912
16913void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16914 // Leave the expression-evaluation context.
16917
16918 // Pop off CurBlock, handle nested blocks.
16921}
16922
16924 Stmt *Body, Scope *CurScope) {
16925 // If blocks are disabled, emit an error.
16926 if (!LangOpts.Blocks)
16927 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16928
16929 // Leave the expression-evaluation context.
16932 assert(!Cleanup.exprNeedsCleanups() &&
16933 "cleanups within block not correctly bound!");
16935
16937 BlockDecl *BD = BSI->TheDecl;
16938
16940
16941 if (BSI->HasImplicitReturnType)
16943
16944 QualType RetTy = Context.VoidTy;
16945 if (!BSI->ReturnType.isNull())
16946 RetTy = BSI->ReturnType;
16947
16948 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16949 QualType BlockTy;
16950
16951 // If the user wrote a function type in some form, try to use that.
16952 if (!BSI->FunctionType.isNull()) {
16953 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16954
16955 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16956 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16957
16958 // Turn protoless block types into nullary block types.
16959 if (isa<FunctionNoProtoType>(FTy)) {
16961 EPI.ExtInfo = Ext;
16962 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16963
16964 // Otherwise, if we don't need to change anything about the function type,
16965 // preserve its sugar structure.
16966 } else if (FTy->getReturnType() == RetTy &&
16967 (!NoReturn || FTy->getNoReturnAttr())) {
16968 BlockTy = BSI->FunctionType;
16969
16970 // Otherwise, make the minimal modifications to the function type.
16971 } else {
16974 EPI.TypeQuals = Qualifiers();
16975 EPI.ExtInfo = Ext;
16976 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16977 }
16978
16979 // If we don't have a function type, just build one from nothing.
16980 } else {
16982 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16983 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16984 }
16985
16987 BlockTy = Context.getBlockPointerType(BlockTy);
16988
16989 // If needed, diagnose invalid gotos and switches in the block.
16990 if (getCurFunction()->NeedsScopeChecking() &&
16991 !PP.isCodeCompletionEnabled())
16993
16994 BD->setBody(cast<CompoundStmt>(Body));
16995
16996 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16998
16999 // Try to apply the named return value optimization. We have to check again
17000 // if we can do this, though, because blocks keep return statements around
17001 // to deduce an implicit return type.
17002 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17003 !BD->isDependentContext())
17004 computeNRVO(Body, BSI);
17005
17011
17013
17014 // Set the captured variables on the block.
17016 for (Capture &Cap : BSI->Captures) {
17017 if (Cap.isInvalid() || Cap.isThisCapture())
17018 continue;
17019 // Cap.getVariable() is always a VarDecl because
17020 // blocks cannot capture structured bindings or other ValueDecl kinds.
17021 auto *Var = cast<VarDecl>(Cap.getVariable());
17022 Expr *CopyExpr = nullptr;
17023 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17024 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17025 // The capture logic needs the destructor, so make sure we mark it.
17026 // Usually this is unnecessary because most local variables have
17027 // their destructors marked at declaration time, but parameters are
17028 // an exception because it's technically only the call site that
17029 // actually requires the destructor.
17030 if (isa<ParmVarDecl>(Var))
17032
17033 // Enter a separate potentially-evaluated context while building block
17034 // initializers to isolate their cleanups from those of the block
17035 // itself.
17036 // FIXME: Is this appropriate even when the block itself occurs in an
17037 // unevaluated operand?
17040
17041 SourceLocation Loc = Cap.getLocation();
17042
17044 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
17045
17046 // According to the blocks spec, the capture of a variable from
17047 // the stack requires a const copy constructor. This is not true
17048 // of the copy/move done to move a __block variable to the heap.
17049 if (!Result.isInvalid() &&
17050 !Result.get()->getType().isConstQualified()) {
17052 Result.get()->getType().withConst(),
17053 CK_NoOp, VK_LValue);
17054 }
17055
17056 if (!Result.isInvalid()) {
17058 InitializedEntity::InitializeBlock(Var->getLocation(),
17059 Cap.getCaptureType()),
17060 Loc, Result.get());
17061 }
17062
17063 // Build a full-expression copy expression if initialization
17064 // succeeded and used a non-trivial constructor. Recover from
17065 // errors by pretending that the copy isn't necessary.
17066 if (!Result.isInvalid() &&
17067 !cast<CXXConstructExpr>(Result.get())->getConstructor()
17068 ->isTrivial()) {
17070 CopyExpr = Result.get();
17071 }
17072 }
17073 }
17074
17075 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17076 CopyExpr);
17077 Captures.push_back(NewCap);
17078 }
17079 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
17080
17081 // Pop the block scope now but keep it alive to the end of this function.
17083 AnalysisWarnings.getPolicyInEffectAt(Body->getEndLoc());
17084 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
17085
17086 BlockExpr *Result = new (Context)
17087 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17088
17089 // If the block isn't obviously global, i.e. it captures anything at
17090 // all, then we need to do a few things in the surrounding context:
17091 if (Result->getBlockDecl()->hasCaptures()) {
17092 // First, this expression has a new cleanup object.
17093 ExprCleanupObjects.push_back(Result->getBlockDecl());
17094 Cleanup.setExprNeedsCleanups(true);
17095
17096 // It also gets a branch-protected scope if any of the captured
17097 // variables needs destruction.
17098 for (const auto &CI : Result->getBlockDecl()->captures()) {
17099 const VarDecl *var = CI.getVariable();
17100 if (var->getType().isDestructedType() != QualType::DK_none) {
17102 break;
17103 }
17104 }
17105 }
17106
17107 if (getCurFunction())
17108 getCurFunction()->addBlock(BD);
17109
17110 // This can happen if the block's return type is deduced, but
17111 // the return expression is invalid.
17112 if (BD->isInvalidDecl())
17113 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
17114 {Result}, Result->getType());
17115 return Result;
17116}
17117
17119 SourceLocation RPLoc) {
17120 TypeSourceInfo *TInfo;
17121 GetTypeFromParser(Ty, &TInfo);
17122 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17123}
17124
17126 Expr *E, TypeSourceInfo *TInfo,
17127 SourceLocation RPLoc) {
17128 Expr *OrigExpr = E;
17129 bool IsMS = false;
17130
17131 // CUDA device global function does not support varargs.
17132 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17133 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
17136 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
17137 }
17138 }
17139
17140 // NVPTX does not support va_arg expression.
17141 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17142 Context.getTargetInfo().getTriple().isNVPTX())
17143 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
17144
17145 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17146 // as Microsoft ABI on an actual Microsoft platform, where
17147 // __builtin_ms_va_list and __builtin_va_list are the same.)
17148 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17149 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17150 QualType MSVaListType = Context.getBuiltinMSVaListType();
17151 if (Context.hasSameType(MSVaListType, E->getType())) {
17152 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
17153 return ExprError();
17154 IsMS = true;
17155 }
17156 }
17157
17158 // Get the va_list type
17159 QualType VaListType = Context.getBuiltinVaListType();
17160 if (!IsMS) {
17161 if (VaListType->isArrayType()) {
17162 // Deal with implicit array decay; for example, on x86-64,
17163 // va_list is an array, but it's supposed to decay to
17164 // a pointer for va_arg.
17165 VaListType = Context.getArrayDecayedType(VaListType);
17166 // Make sure the input expression also decays appropriately.
17168 if (Result.isInvalid())
17169 return ExprError();
17170 E = Result.get();
17171 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17172 // If va_list is a record type and we are compiling in C++ mode,
17173 // check the argument using reference binding.
17175 Context, Context.getLValueReferenceType(VaListType), false);
17177 if (Init.isInvalid())
17178 return ExprError();
17179 E = Init.getAs<Expr>();
17180 } else {
17181 // Otherwise, the va_list argument must be an l-value because
17182 // it is modified by va_arg.
17183 if (!E->isTypeDependent() &&
17184 CheckForModifiableLvalue(E, BuiltinLoc, *this))
17185 return ExprError();
17186 }
17187 }
17188
17189 if (!IsMS && !E->isTypeDependent() &&
17190 !Context.hasSameType(VaListType, E->getType()))
17191 return ExprError(
17192 Diag(E->getBeginLoc(),
17193 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17194 << OrigExpr->getType() << E->getSourceRange());
17195
17196 if (!TInfo->getType()->isDependentType()) {
17197 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17198 diag::err_second_parameter_to_va_arg_incomplete,
17199 TInfo->getTypeLoc()))
17200 return ExprError();
17201
17203 TInfo->getType(),
17204 diag::err_second_parameter_to_va_arg_abstract,
17205 TInfo->getTypeLoc()))
17206 return ExprError();
17207
17208 if (!TInfo->getType().isPODType(Context)) {
17209 Diag(TInfo->getTypeLoc().getBeginLoc(),
17210 TInfo->getType()->isObjCLifetimeType()
17211 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17212 : diag::warn_second_parameter_to_va_arg_not_pod)
17213 << TInfo->getType()
17214 << TInfo->getTypeLoc().getSourceRange();
17215 }
17216
17217 if (TInfo->getType()->isArrayType()) {
17219 PDiag(diag::warn_second_parameter_to_va_arg_array)
17220 << TInfo->getType()
17221 << TInfo->getTypeLoc().getSourceRange());
17222 }
17223
17224 // Check for va_arg where arguments of the given type will be promoted
17225 // (i.e. this va_arg is guaranteed to have undefined behavior).
17226 QualType PromoteType;
17227 if (Context.isPromotableIntegerType(TInfo->getType())) {
17228 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17229 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17230 // and C23 7.16.1.1p2 says, in part:
17231 // If type is not compatible with the type of the actual next argument
17232 // (as promoted according to the default argument promotions), the
17233 // behavior is undefined, except for the following cases:
17234 // - both types are pointers to qualified or unqualified versions of
17235 // compatible types;
17236 // - one type is compatible with a signed integer type, the other
17237 // type is compatible with the corresponding unsigned integer type,
17238 // and the value is representable in both types;
17239 // - one type is pointer to qualified or unqualified void and the
17240 // other is a pointer to a qualified or unqualified character type;
17241 // - or, the type of the next argument is nullptr_t and type is a
17242 // pointer type that has the same representation and alignment
17243 // requirements as a pointer to a character type.
17244 // Given that type compatibility is the primary requirement (ignoring
17245 // qualifications), you would think we could call typesAreCompatible()
17246 // directly to test this. However, in C++, that checks for *same type*,
17247 // which causes false positives when passing an enumeration type to
17248 // va_arg. Instead, get the underlying type of the enumeration and pass
17249 // that.
17250 QualType UnderlyingType = TInfo->getType();
17251 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17252 UnderlyingType = ED->getIntegerType();
17253 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17254 /*CompareUnqualified*/ true))
17255 PromoteType = QualType();
17256
17257 // If the types are still not compatible, we need to test whether the
17258 // promoted type and the underlying type are the same except for
17259 // signedness. Ask the AST for the correctly corresponding type and see
17260 // if that's compatible.
17261 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17262 PromoteType->isUnsignedIntegerType() !=
17263 UnderlyingType->isUnsignedIntegerType()) {
17264 UnderlyingType =
17265 UnderlyingType->isUnsignedIntegerType()
17266 ? Context.getCorrespondingSignedType(UnderlyingType)
17267 : Context.getCorrespondingUnsignedType(UnderlyingType);
17268 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17269 /*CompareUnqualified*/ true))
17270 PromoteType = QualType();
17271 }
17272 }
17273 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17274 PromoteType = Context.DoubleTy;
17275 if (!PromoteType.isNull())
17277 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17278 << TInfo->getType()
17279 << PromoteType
17280 << TInfo->getTypeLoc().getSourceRange());
17281 }
17282
17284 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17285}
17286
17288 // The type of __null will be int or long, depending on the size of
17289 // pointers on the target.
17290 QualType Ty;
17291 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17292 if (pw == Context.getTargetInfo().getIntWidth())
17293 Ty = Context.IntTy;
17294 else if (pw == Context.getTargetInfo().getLongWidth())
17295 Ty = Context.LongTy;
17296 else if (pw == Context.getTargetInfo().getLongLongWidth())
17297 Ty = Context.LongLongTy;
17298 else {
17299 llvm_unreachable("I don't know size of pointer!");
17300 }
17301
17302 return new (Context) GNUNullExpr(Ty, TokenLoc);
17303}
17304
17306 CXXRecordDecl *ImplDecl = nullptr;
17307
17308 // Fetch the std::source_location::__impl decl.
17309 if (NamespaceDecl *Std = S.getStdNamespace()) {
17310 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17312 if (S.LookupQualifiedName(ResultSL, Std)) {
17313 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17314 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17316 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17317 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17318 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17319 }
17320 }
17321 }
17322 }
17323
17324 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17325 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17326 return nullptr;
17327 }
17328
17329 // Verify that __impl is a trivial struct type, with no base classes, and with
17330 // only the four expected fields.
17331 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17332 ImplDecl->getNumBases() != 0) {
17333 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17334 return nullptr;
17335 }
17336
17337 unsigned Count = 0;
17338 for (FieldDecl *F : ImplDecl->fields()) {
17339 StringRef Name = F->getName();
17340
17341 if (Name == "_M_file_name") {
17342 if (F->getType() !=
17344 break;
17345 Count++;
17346 } else if (Name == "_M_function_name") {
17347 if (F->getType() !=
17349 break;
17350 Count++;
17351 } else if (Name == "_M_line") {
17352 if (!F->getType()->isIntegerType())
17353 break;
17354 Count++;
17355 } else if (Name == "_M_column") {
17356 if (!F->getType()->isIntegerType())
17357 break;
17358 Count++;
17359 } else {
17360 Count = 100; // invalid
17361 break;
17362 }
17363 }
17364 if (Count != 4) {
17365 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17366 return nullptr;
17367 }
17368
17369 return ImplDecl;
17370}
17371
17373 SourceLocation BuiltinLoc,
17374 SourceLocation RPLoc) {
17375 QualType ResultTy;
17376 switch (Kind) {
17381 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17382 ResultTy =
17383 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17384 break;
17385 }
17388 ResultTy = Context.UnsignedIntTy;
17389 break;
17393 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17395 return ExprError();
17396 }
17397 ResultTy = Context.getPointerType(
17398 Context.getCanonicalTagType(StdSourceLocationImplDecl).withConst());
17399 break;
17400 }
17401
17402 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17403}
17404
17406 SourceLocation BuiltinLoc,
17407 SourceLocation RPLoc,
17408 DeclContext *ParentContext) {
17409 return new (Context)
17410 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17411}
17412
17414 StringLiteral *BinaryData, StringRef FileName) {
17416 Data->BinaryData = BinaryData;
17417 Data->FileName = FileName;
17418 return new (Context)
17419 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17420 Data->getDataElementCount());
17421}
17422
17424 const Expr *SrcExpr) {
17425 if (!DstType->isFunctionPointerType() ||
17426 !SrcExpr->getType()->isFunctionType())
17427 return false;
17428
17429 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17430 if (!DRE)
17431 return false;
17432
17433 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17434 if (!FD)
17435 return false;
17436
17438 /*Complain=*/true,
17439 SrcExpr->getBeginLoc());
17440}
17441
17443 SourceLocation Loc,
17444 QualType DstType, QualType SrcType,
17445 Expr *SrcExpr, AssignmentAction Action,
17446 bool *Complained) {
17447 if (Complained)
17448 *Complained = false;
17449
17450 // Decode the result (notice that AST's are still created for extensions).
17451 bool CheckInferredResultType = false;
17452 bool isInvalid = false;
17453 unsigned DiagKind = 0;
17454 ConversionFixItGenerator ConvHints;
17455 bool MayHaveConvFixit = false;
17456 bool MayHaveFunctionDiff = false;
17457 const ObjCInterfaceDecl *IFace = nullptr;
17458 const ObjCProtocolDecl *PDecl = nullptr;
17459
17460 switch (ConvTy) {
17462 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17463 return false;
17465 // Still a valid conversion, but we may want to diagnose for C++
17466 // compatibility reasons.
17467 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17468 break;
17470 if (getLangOpts().CPlusPlus) {
17471 DiagKind = diag::err_typecheck_convert_pointer_int;
17472 isInvalid = true;
17473 } else {
17474 DiagKind = diag::ext_typecheck_convert_pointer_int;
17475 }
17476 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17477 MayHaveConvFixit = true;
17478 break;
17480 if (getLangOpts().CPlusPlus) {
17481 DiagKind = diag::err_typecheck_convert_int_pointer;
17482 isInvalid = true;
17483 } else {
17484 DiagKind = diag::ext_typecheck_convert_int_pointer;
17485 }
17486 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17487 MayHaveConvFixit = true;
17488 break;
17490 DiagKind =
17491 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17492 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17493 MayHaveConvFixit = true;
17494 break;
17496 if (getLangOpts().CPlusPlus) {
17497 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17498 isInvalid = true;
17499 } else {
17500 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17501 }
17502 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17503 MayHaveConvFixit = true;
17504 break;
17507 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17508 } else if (getLangOpts().CPlusPlus) {
17509 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17510 isInvalid = true;
17511 } else {
17512 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17513 }
17514 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17515 SrcType->isObjCObjectPointerType();
17516 if (CheckInferredResultType) {
17517 SrcType = SrcType.getUnqualifiedType();
17518 DstType = DstType.getUnqualifiedType();
17519 } else {
17520 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17521 }
17522 MayHaveConvFixit = true;
17523 break;
17525 if (getLangOpts().CPlusPlus) {
17526 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17527 isInvalid = true;
17528 } else {
17529 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17530 }
17531 break;
17533 if (getLangOpts().CPlusPlus) {
17534 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17535 isInvalid = true;
17536 } else {
17537 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17538 }
17539 break;
17541 // Perform array-to-pointer decay if necessary.
17542 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17543
17544 isInvalid = true;
17545
17546 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17547 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17548 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17549 DiagKind = diag::err_typecheck_incompatible_address_space;
17550 break;
17551 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17552 DiagKind = diag::err_typecheck_incompatible_ownership;
17553 break;
17554 } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {
17555 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17556 break;
17557 }
17558
17559 llvm_unreachable("unknown error case for discarding qualifiers!");
17560 // fallthrough
17561 }
17563 if (SrcType->isArrayType())
17564 SrcType = Context.getArrayDecayedType(SrcType);
17565
17566 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17567 break;
17569 // If the qualifiers lost were because we were applying the
17570 // (deprecated) C++ conversion from a string literal to a char*
17571 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17572 // Ideally, this check would be performed in
17573 // checkPointerTypesForAssignment. However, that would require a
17574 // bit of refactoring (so that the second argument is an
17575 // expression, rather than a type), which should be done as part
17576 // of a larger effort to fix checkPointerTypesForAssignment for
17577 // C++ semantics.
17578 if (getLangOpts().CPlusPlus &&
17580 return false;
17581 if (getLangOpts().CPlusPlus) {
17582 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17583 isInvalid = true;
17584 } else {
17585 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17586 }
17587
17588 break;
17590 if (getLangOpts().CPlusPlus) {
17591 isInvalid = true;
17592 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17593 } else {
17594 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17595 }
17596 break;
17598 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17599 isInvalid = true;
17600 break;
17602 DiagKind = diag::err_int_to_block_pointer;
17603 isInvalid = true;
17604 break;
17606 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17607 isInvalid = true;
17608 break;
17610 if (SrcType->isObjCQualifiedIdType()) {
17611 const ObjCObjectPointerType *srcOPT =
17612 SrcType->castAs<ObjCObjectPointerType>();
17613 for (auto *srcProto : srcOPT->quals()) {
17614 PDecl = srcProto;
17615 break;
17616 }
17617 if (const ObjCInterfaceType *IFaceT =
17619 IFace = IFaceT->getDecl();
17620 }
17621 else if (DstType->isObjCQualifiedIdType()) {
17622 const ObjCObjectPointerType *dstOPT =
17623 DstType->castAs<ObjCObjectPointerType>();
17624 for (auto *dstProto : dstOPT->quals()) {
17625 PDecl = dstProto;
17626 break;
17627 }
17628 if (const ObjCInterfaceType *IFaceT =
17630 IFace = IFaceT->getDecl();
17631 }
17632 if (getLangOpts().CPlusPlus) {
17633 DiagKind = diag::err_incompatible_qualified_id;
17634 isInvalid = true;
17635 } else {
17636 DiagKind = diag::warn_incompatible_qualified_id;
17637 }
17638 break;
17639 }
17641 if (getLangOpts().CPlusPlus) {
17642 DiagKind = diag::err_incompatible_vectors;
17643 isInvalid = true;
17644 } else {
17645 DiagKind = diag::warn_incompatible_vectors;
17646 }
17647 break;
17649 DiagKind = diag::err_arc_weak_unavailable_assign;
17650 isInvalid = true;
17651 break;
17653 return false;
17655 auto getOBTKindName = [](QualType Ty) -> StringRef {
17656 if (Ty->isPointerType())
17657 Ty = Ty->getPointeeType();
17658 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
17659 return OBT->getBehaviorKind() ==
17660 OverflowBehaviorType::OverflowBehaviorKind::Trap
17661 ? "__ob_trap"
17662 : "__ob_wrap";
17663 }
17664 llvm_unreachable("OBT kind unhandled");
17665 };
17666
17667 Diag(Loc, diag::err_incompatible_obt_kinds_assignment)
17668 << DstType << SrcType << getOBTKindName(DstType)
17669 << getOBTKindName(SrcType);
17670 isInvalid = true;
17671 return true;
17672 }
17674 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17675 if (Complained)
17676 *Complained = true;
17677 return true;
17678 }
17679
17680 DiagKind = diag::err_typecheck_convert_incompatible;
17681 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17682 MayHaveConvFixit = true;
17683 isInvalid = true;
17684 MayHaveFunctionDiff = true;
17685 break;
17686 }
17687
17688 QualType FirstType, SecondType;
17689 switch (Action) {
17692 // The destination type comes first.
17693 FirstType = DstType;
17694 SecondType = SrcType;
17695 break;
17696
17703 // The source type comes first.
17704 FirstType = SrcType;
17705 SecondType = DstType;
17706 break;
17707 }
17708
17709 PartialDiagnostic FDiag = PDiag(DiagKind);
17710 AssignmentAction ActionForDiag = Action;
17712 ActionForDiag = AssignmentAction::Passing;
17713
17714 FDiag << FirstType << SecondType << ActionForDiag
17715 << SrcExpr->getSourceRange();
17716
17717 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17718 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17719 auto isPlainChar = [](const clang::Type *Type) {
17720 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17721 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17722 };
17723 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17724 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17725 }
17726
17727 // If we can fix the conversion, suggest the FixIts.
17728 if (!ConvHints.isNull()) {
17729 for (FixItHint &H : ConvHints.Hints)
17730 FDiag << H;
17731 }
17732
17733 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17734
17735 if (MayHaveFunctionDiff)
17736 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17737
17738 Diag(Loc, FDiag);
17739 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17740 DiagKind == diag::err_incompatible_qualified_id) &&
17741 PDecl && IFace && !IFace->hasDefinition())
17742 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17743 << IFace << PDecl;
17744
17745 if (SecondType == Context.OverloadTy)
17747 FirstType, /*TakingAddress=*/true);
17748
17749 if (CheckInferredResultType)
17751
17752 if (Action == AssignmentAction::Returning &&
17755
17756 if (Complained)
17757 *Complained = true;
17758 return isInvalid;
17759}
17760
17762 llvm::APSInt *Result,
17763 AllowFoldKind CanFold) {
17764 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17765 public:
17766 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17767 QualType T) override {
17768 return S.Diag(Loc, diag::err_ice_not_integral)
17769 << T << S.LangOpts.CPlusPlus;
17770 }
17771 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17772 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17773 }
17774 } Diagnoser;
17775
17776 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17777}
17778
17780 llvm::APSInt *Result,
17781 unsigned DiagID,
17782 AllowFoldKind CanFold) {
17783 class IDDiagnoser : public VerifyICEDiagnoser {
17784 unsigned DiagID;
17785
17786 public:
17787 IDDiagnoser(unsigned DiagID)
17788 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17789
17790 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17791 return S.Diag(Loc, DiagID);
17792 }
17793 } Diagnoser(DiagID);
17794
17795 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17796}
17797
17803
17806 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17807}
17808
17811 VerifyICEDiagnoser &Diagnoser,
17812 AllowFoldKind CanFold) {
17813 SourceLocation DiagLoc = E->getBeginLoc();
17814
17815 if (getLangOpts().CPlusPlus11) {
17816 // C++11 [expr.const]p5:
17817 // If an expression of literal class type is used in a context where an
17818 // integral constant expression is required, then that class type shall
17819 // have a single non-explicit conversion function to an integral or
17820 // unscoped enumeration type
17821 ExprResult Converted;
17822 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17823 VerifyICEDiagnoser &BaseDiagnoser;
17824 public:
17825 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17826 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17827 BaseDiagnoser.Suppress, true),
17828 BaseDiagnoser(BaseDiagnoser) {}
17829
17830 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17831 QualType T) override {
17832 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17833 }
17834
17835 SemaDiagnosticBuilder diagnoseIncomplete(
17836 Sema &S, SourceLocation Loc, QualType T) override {
17837 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17838 }
17839
17840 SemaDiagnosticBuilder diagnoseExplicitConv(
17841 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17842 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17843 }
17844
17845 SemaDiagnosticBuilder noteExplicitConv(
17846 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17847 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17848 << ConvTy->isEnumeralType() << ConvTy;
17849 }
17850
17851 SemaDiagnosticBuilder diagnoseAmbiguous(
17852 Sema &S, SourceLocation Loc, QualType T) override {
17853 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17854 }
17855
17856 SemaDiagnosticBuilder noteAmbiguous(
17857 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17858 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17859 << ConvTy->isEnumeralType() << ConvTy;
17860 }
17861
17862 SemaDiagnosticBuilder diagnoseConversion(
17863 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17864 llvm_unreachable("conversion functions are permitted");
17865 }
17866 } ConvertDiagnoser(Diagnoser);
17867
17868 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17869 ConvertDiagnoser);
17870 if (Converted.isInvalid())
17871 return Converted;
17872 E = Converted.get();
17873 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17874 // don't try to evaluate it later. We also don't want to return the
17875 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17876 // this function will attempt to use 'Value'.
17877 if (isa<RecoveryExpr>(E))
17878 return ExprError();
17880 return ExprError();
17881 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17882 // An ICE must be of integral or unscoped enumeration type.
17883 if (!Diagnoser.Suppress)
17884 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17885 << E->getSourceRange();
17886 return ExprError();
17887 }
17888
17889 ExprResult RValueExpr = DefaultLvalueConversion(E);
17890 if (RValueExpr.isInvalid())
17891 return ExprError();
17892
17893 E = RValueExpr.get();
17894
17895 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17896 // in the non-ICE case.
17899 if (Result)
17901 if (!isa<ConstantExpr>(E))
17904
17905 if (Notes.empty())
17906 return E;
17907
17908 // If our only note is the usual "invalid subexpression" note, just point
17909 // the caret at its location rather than producing an essentially
17910 // redundant note.
17911 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17912 diag::note_invalid_subexpr_in_const_expr) {
17913 DiagLoc = Notes[0].first;
17914 Notes.clear();
17915 }
17916
17917 if (getLangOpts().CPlusPlus) {
17918 if (!Diagnoser.Suppress) {
17919 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17920 for (const PartialDiagnosticAt &Note : Notes)
17921 Diag(Note.first, Note.second);
17922 }
17923 return ExprError();
17924 }
17925
17926 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17927 for (const PartialDiagnosticAt &Note : Notes)
17928 Diag(Note.first, Note.second);
17929
17930 return E;
17931 }
17932
17933 Expr::EvalResult EvalResult;
17935 EvalResult.Diag = &Notes;
17936
17937 // Try to evaluate the expression, and produce diagnostics explaining why it's
17938 // not a constant expression as a side-effect.
17939 bool Folded =
17940 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17941 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17942 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17943
17944 if (!isa<ConstantExpr>(E))
17945 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17946
17947 // In C++11, we can rely on diagnostics being produced for any expression
17948 // which is not a constant expression. If no diagnostics were produced, then
17949 // this is a constant expression.
17950 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17951 if (Result)
17952 *Result = EvalResult.Val.getInt();
17953 return E;
17954 }
17955
17956 // If our only note is the usual "invalid subexpression" note, just point
17957 // the caret at its location rather than producing an essentially
17958 // redundant note.
17959 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17960 diag::note_invalid_subexpr_in_const_expr) {
17961 DiagLoc = Notes[0].first;
17962 Notes.clear();
17963 }
17964
17965 if (!Folded || CanFold == AllowFoldKind::No) {
17966 if (!Diagnoser.Suppress) {
17967 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17968 for (const PartialDiagnosticAt &Note : Notes)
17969 Diag(Note.first, Note.second);
17970 }
17971
17972 return ExprError();
17973 }
17974
17975 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17976 for (const PartialDiagnosticAt &Note : Notes)
17977 Diag(Note.first, Note.second);
17978
17979 if (Result)
17980 *Result = EvalResult.Val.getInt();
17981 return E;
17982}
17983
17984namespace {
17985 // Handle the case where we conclude a expression which we speculatively
17986 // considered to be unevaluated is actually evaluated.
17987 class TransformToPE : public TreeTransform<TransformToPE> {
17988 typedef TreeTransform<TransformToPE> BaseTransform;
17989
17990 public:
17991 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17992
17993 // Make sure we redo semantic analysis
17994 bool AlwaysRebuild() { return true; }
17995 bool ReplacingOriginal() { return true; }
17996
17997 // We need to special-case DeclRefExprs referring to FieldDecls which
17998 // are not part of a member pointer formation; normal TreeTransforming
17999 // doesn't catch this case because of the way we represent them in the AST.
18000 // FIXME: This is a bit ugly; is it really the best way to handle this
18001 // case?
18002 //
18003 // Error on DeclRefExprs referring to FieldDecls.
18004 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18005 if (isa<FieldDecl>(E->getDecl()) &&
18006 !SemaRef.isUnevaluatedContext())
18007 return SemaRef.Diag(E->getLocation(),
18008 diag::err_invalid_non_static_member_use)
18009 << E->getDecl() << E->getSourceRange();
18010
18011 return BaseTransform::TransformDeclRefExpr(E);
18012 }
18013
18014 // Exception: filter out member pointer formation
18015 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18016 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18017 return E;
18018
18019 return BaseTransform::TransformUnaryOperator(E);
18020 }
18021
18022 // The body of a lambda-expression is in a separate expression evaluation
18023 // context so never needs to be transformed.
18024 // FIXME: Ideally we wouldn't transform the closure type either, and would
18025 // just recreate the capture expressions and lambda expression.
18026 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18027 return SkipLambdaBody(E, Body);
18028 }
18029 };
18030}
18031
18033 assert(isUnevaluatedContext() &&
18034 "Should only transform unevaluated expressions");
18035 ExprEvalContexts.back().Context =
18036 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18038 return E;
18039 return TransformToPE(*this).TransformExpr(E);
18040}
18041
18043 assert(isUnevaluatedContext() &&
18044 "Should only transform unevaluated expressions");
18047 return TInfo;
18048 return TransformToPE(*this).TransformType(TInfo);
18049}
18050
18051void
18053 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18055 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
18056 LambdaContextDecl, ExprContext);
18057
18058 // Discarded statements and immediate contexts nested in other
18059 // discarded statements or immediate context are themselves
18060 // a discarded statement or an immediate context, respectively.
18061 ExprEvalContexts.back().InDiscardedStatement =
18063
18064 // C++23 [expr.const]/p15
18065 // An expression or conversion is in an immediate function context if [...]
18066 // it is a subexpression of a manifestly constant-evaluated expression or
18067 // conversion.
18068 const auto &Prev = parentEvaluationContext();
18069 ExprEvalContexts.back().InImmediateFunctionContext =
18070 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18071
18072 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18073 Prev.InImmediateEscalatingFunctionContext;
18074
18075 Cleanup.reset();
18076 if (!MaybeODRUseExprs.empty())
18077 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
18078}
18079
18080void
18084 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18085 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
18086}
18087
18089 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18090 // [expr.const]/p14.1
18091 // An expression or conversion is in an immediate function context if it is
18092 // potentially evaluated and either: its innermost enclosing non-block scope
18093 // is a function parameter scope of an immediate function.
18095 FD && FD->isConsteval()
18097 : NewContext);
18101
18102 Current.InDiscardedStatement = false;
18103
18104 if (FD) {
18105
18106 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18107 // context is nested in an immediate function context, so smaller contexts
18108 // that appear inside immediate functions (like variable initializers) are
18109 // considered to be inside an immediate function context even though by
18110 // themselves they are not immediate function contexts. But when a new
18111 // function is entered, we need to reset this tracking, since the entered
18112 // function might be not an immediate function.
18113
18115 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18116
18117 if (isLambdaMethod(FD))
18119 FD->isConsteval() ||
18120 (isLambdaMethod(FD) && (Parent.isConstantEvaluated() ||
18121 Parent.isImmediateFunctionContext()));
18122 else
18124 }
18125}
18126
18128 TypeSourceInfo *TSI) {
18129 return BuildCXXReflectExpr(CaretCaretLoc, TSI);
18130}
18131
18133 TypeSourceInfo *TSI) {
18134 return CXXReflectExpr::Create(Context, CaretCaretLoc, TSI);
18135}
18136
18137namespace {
18138
18139const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18140 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18141 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
18142 if (E->getOpcode() == UO_Deref)
18143 return CheckPossibleDeref(S, E->getSubExpr());
18144 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
18145 return CheckPossibleDeref(S, E->getBase());
18146 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
18147 return CheckPossibleDeref(S, E->getBase());
18148 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
18149 QualType Inner;
18150 QualType Ty = E->getType();
18151 if (const auto *Ptr = Ty->getAs<PointerType>())
18152 Inner = Ptr->getPointeeType();
18153 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
18154 Inner = Arr->getElementType();
18155 else
18156 return nullptr;
18157
18158 if (Inner->hasAttr(attr::NoDeref))
18159 return E;
18160 }
18161 return nullptr;
18162}
18163
18164} // namespace
18165
18167 for (const Expr *E : Rec.PossibleDerefs) {
18168 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
18169 if (DeclRef) {
18170 const ValueDecl *Decl = DeclRef->getDecl();
18171 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
18172 << Decl->getName() << E->getSourceRange();
18173 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
18174 } else {
18175 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
18176 << E->getSourceRange();
18177 }
18178 }
18179 Rec.PossibleDerefs.clear();
18180}
18181
18184 return;
18185
18186 // Note: ignoring parens here is not justified by the standard rules, but
18187 // ignoring parentheses seems like a more reasonable approach, and this only
18188 // drives a deprecation warning so doesn't affect conformance.
18189 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
18190 if (BO->getOpcode() == BO_Assign) {
18191 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18192 llvm::erase(LHSs, BO->getLHS());
18193 }
18194 }
18195}
18196
18198 assert(getLangOpts().CPlusPlus20 &&
18199 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18200 "Cannot mark an immediate escalating expression outside of an "
18201 "immediate escalating context");
18202 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
18203 Call && Call->getCallee()) {
18204 if (auto *DeclRef =
18205 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18206 DeclRef->setIsImmediateEscalating(true);
18207 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
18208 Ctr->setIsImmediateEscalating(true);
18209 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
18210 DeclRef->setIsImmediateEscalating(true);
18211 } else {
18212 assert(false && "expected an immediately escalating expression");
18213 }
18215 FI->FoundImmediateEscalatingExpression = true;
18216}
18217
18219 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18220 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18223 return E;
18224
18225 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18226 /// It's OK if this fails; we'll also remove this in
18227 /// HandleImmediateInvocations, but catching it here allows us to avoid
18228 /// walking the AST looking for it in simple cases.
18229 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18230 if (auto *DeclRef =
18231 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18232 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18233
18234 // C++23 [expr.const]/p16
18235 // An expression or conversion is immediate-escalating if it is not initially
18236 // in an immediate function context and it is [...] an immediate invocation
18237 // that is not a constant expression and is not a subexpression of an
18238 // immediate invocation.
18239 APValue Cached;
18240 auto CheckConstantExpressionAndKeepResult = [&]() {
18242 Expr::EvalResult Eval;
18243 Eval.Diag = &Notes;
18244 bool Res = E.get()->EvaluateAsConstantExpr(
18245 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
18246 if (Res && Notes.empty()) {
18247 Cached = std::move(Eval.Val);
18248 return true;
18249 }
18250 return false;
18251 };
18252
18253 if (!E.get()->isValueDependent() &&
18254 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18255 !CheckConstantExpressionAndKeepResult()) {
18257 return E;
18258 }
18259
18260 if (Cleanup.exprNeedsCleanups()) {
18261 // Since an immediate invocation is a full expression itself - it requires
18262 // an additional ExprWithCleanups node, but it can participate to a bigger
18263 // full expression which actually requires cleanups to be run after so
18264 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18265 // may discard cleanups for outer expression too early.
18266
18267 // Note that ExprWithCleanups created here must always have empty cleanup
18268 // objects:
18269 // - compound literals do not create cleanup objects in C++ and immediate
18270 // invocations are C++-only.
18271 // - blocks are not allowed inside constant expressions and compiler will
18272 // issue an error if they appear there.
18273 //
18274 // Hence, in correct code any cleanup objects created inside current
18275 // evaluation context must be outside the immediate invocation.
18277 Cleanup.cleanupsHaveSideEffects(), {});
18278 }
18279
18281 getASTContext(), E.get(),
18282 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18283 getASTContext()),
18284 /*IsImmediateInvocation*/ true);
18285 if (Cached.hasValue())
18286 Res->MoveIntoResult(Cached, getASTContext());
18287 /// Value-dependent constant expressions should not be immediately
18288 /// evaluated until they are instantiated.
18289 if (!Res->isValueDependent())
18290 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18291 return Res;
18292}
18293
18297 Expr::EvalResult Eval;
18298 Eval.Diag = &Notes;
18299 ConstantExpr *CE = Candidate.getPointer();
18300 bool Result = CE->EvaluateAsConstantExpr(
18301 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18302 if (!Result || !Notes.empty()) {
18304 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18305 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18306 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18307 FunctionDecl *FD = nullptr;
18308 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18309 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18310 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18311 FD = Call->getConstructor();
18312 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18313 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18314
18315 assert(FD && FD->isImmediateFunction() &&
18316 "could not find an immediate function in this expression");
18317 if (FD->isInvalidDecl())
18318 return;
18319 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18320 << FD << FD->isConsteval();
18321 if (auto Context =
18323 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18324 << Context->Decl;
18325 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18326 }
18327 if (!FD->isConsteval())
18329 for (auto &Note : Notes)
18330 SemaRef.Diag(Note.first, Note.second);
18331 return;
18332 }
18334}
18335
18339 struct ComplexRemove : TreeTransform<ComplexRemove> {
18341 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18344 CurrentII;
18345 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18348 4>::reverse_iterator Current)
18349 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18350 void RemoveImmediateInvocation(ConstantExpr* E) {
18351 auto It = std::find_if(CurrentII, IISet.rend(),
18353 return Elem.getPointer() == E;
18354 });
18355 // It is possible that some subexpression of the current immediate
18356 // invocation was handled from another expression evaluation context. Do
18357 // not handle the current immediate invocation if some of its
18358 // subexpressions failed before.
18359 if (It == IISet.rend()) {
18360 if (SemaRef.FailedImmediateInvocations.contains(E))
18361 CurrentII->setInt(1);
18362 } else {
18363 It->setInt(1); // Mark as deleted
18364 }
18365 }
18366 ExprResult TransformConstantExpr(ConstantExpr *E) {
18367 if (!E->isImmediateInvocation())
18368 return Base::TransformConstantExpr(E);
18369 RemoveImmediateInvocation(E);
18370 return Base::TransformExpr(E->getSubExpr());
18371 }
18372 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18373 /// we need to remove its DeclRefExpr from the DRSet.
18374 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18375 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18376 return Base::TransformCXXOperatorCallExpr(E);
18377 }
18378 /// Base::TransformUserDefinedLiteral doesn't preserve the
18379 /// UserDefinedLiteral node.
18380 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18381 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18382 /// here.
18383 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18384 if (!Init)
18385 return Init;
18386
18387 // We cannot use IgnoreImpCasts because we need to preserve
18388 // full expressions.
18389 while (true) {
18390 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
18391 Init = ICE->getSubExpr();
18392 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
18393 Init = ICE->getSubExpr();
18394 else
18395 break;
18396 }
18397 /// ConstantExprs are the first layer of implicit node to be removed so if
18398 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18399 if (auto *CE = dyn_cast<ConstantExpr>(Init);
18400 CE && CE->isImmediateInvocation())
18401 RemoveImmediateInvocation(CE);
18402 return Base::TransformInitializer(Init, NotCopyInit);
18403 }
18404 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18405 DRSet.erase(E);
18406 return E;
18407 }
18408 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18409 // Do not rebuild lambdas to avoid creating a new type.
18410 // Lambdas have already been processed inside their eval contexts.
18411 return E;
18412 }
18413 bool AlwaysRebuild() { return false; }
18414 bool ReplacingOriginal() { return true; }
18415 bool AllowSkippingCXXConstructExpr() {
18416 bool Res = AllowSkippingFirstCXXConstructExpr;
18417 AllowSkippingFirstCXXConstructExpr = true;
18418 return Res;
18419 }
18420 bool AllowSkippingFirstCXXConstructExpr = true;
18421 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18423
18424 /// CXXConstructExpr with a single argument are getting skipped by
18425 /// TreeTransform in some situtation because they could be implicit. This
18426 /// can only occur for the top-level CXXConstructExpr because it is used
18427 /// nowhere in the expression being transformed therefore will not be rebuilt.
18428 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18429 /// skipping the first CXXConstructExpr.
18430 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18431 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18432
18433 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18434 // The result may not be usable in case of previous compilation errors.
18435 // In this case evaluation of the expression may result in crash so just
18436 // don't do anything further with the result.
18437 if (Res.isUsable()) {
18439 It->getPointer()->setSubExpr(Res.get());
18440 }
18441}
18442
18443static void
18446 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18447 Rec.ReferenceToConsteval.size() == 0) ||
18449 return;
18450
18451 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18452 // [...]
18453 // - the initializer of a variable that is usable in constant expressions or
18454 // has constant initialization.
18455 if (SemaRef.getLangOpts().CPlusPlus23 &&
18456 Rec.ExprContext ==
18458 auto *VD = dyn_cast<VarDecl>(Rec.ManglingContextDecl);
18459 if (VD && (VD->isUsableInConstantExpressions(SemaRef.Context) ||
18460 VD->hasConstantInitialization())) {
18461 // An expression or conversion is in an 'immediate function context' if it
18462 // is potentially evaluated and either:
18463 // [...]
18464 // - it is a subexpression of a manifestly constant-evaluated expression
18465 // or conversion.
18466 return;
18467 }
18468 }
18469
18470 /// When we have more than 1 ImmediateInvocationCandidates or previously
18471 /// failed immediate invocations, we need to check for nested
18472 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18473 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18474 /// invocation.
18475 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18477
18478 /// Prevent sema calls during the tree transform from adding pointers that
18479 /// are already in the sets.
18480 llvm::SaveAndRestore DisableIITracking(
18482
18483 /// Prevent diagnostic during tree transfrom as they are duplicates
18485
18486 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18487 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18488 if (!It->getInt())
18490 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18491 Rec.ReferenceToConsteval.size()) {
18492 struct SimpleRemove : DynamicRecursiveASTVisitor {
18493 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18494 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18495 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18496 DRSet.erase(E);
18497 return DRSet.size();
18498 }
18499 } Visitor(Rec.ReferenceToConsteval);
18500 Visitor.TraverseStmt(
18501 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18502 }
18503 for (auto CE : Rec.ImmediateInvocationCandidates)
18504 if (!CE.getInt())
18506 for (auto *DR : Rec.ReferenceToConsteval) {
18507 // If the expression is immediate escalating, it is not an error;
18508 // The outer context itself becomes immediate and further errors,
18509 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18510 if (DR->isImmediateEscalating())
18511 continue;
18512 auto *FD = cast<FunctionDecl>(DR->getDecl());
18513 const NamedDecl *ND = FD;
18514 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18515 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18516 ND = MD->getParent();
18517
18518 // C++23 [expr.const]/p16
18519 // An expression or conversion is immediate-escalating if it is not
18520 // initially in an immediate function context and it is [...] a
18521 // potentially-evaluated id-expression that denotes an immediate function
18522 // that is not a subexpression of an immediate invocation.
18523 bool ImmediateEscalating = false;
18524 bool IsPotentiallyEvaluated =
18525 Rec.Context ==
18527 Rec.Context ==
18529 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18530 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18531
18533 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18534 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18535 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18536 if (!FD->getBuiltinID())
18537 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18538 if (auto Context =
18540 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18541 << Context->Decl;
18542 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18543 }
18544 if (FD->isImmediateEscalating() && !FD->isConsteval())
18546
18547 } else {
18549 }
18550 }
18551}
18552
18555 if (!Rec.Lambdas.empty()) {
18557 if (!getLangOpts().CPlusPlus20 &&
18558 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18559 Rec.isUnevaluated() ||
18561 unsigned D;
18562 if (Rec.isUnevaluated()) {
18563 // C++11 [expr.prim.lambda]p2:
18564 // A lambda-expression shall not appear in an unevaluated operand
18565 // (Clause 5).
18566 D = diag::err_lambda_unevaluated_operand;
18567 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18568 // C++1y [expr.const]p2:
18569 // A conditional-expression e is a core constant expression unless the
18570 // evaluation of e, following the rules of the abstract machine, would
18571 // evaluate [...] a lambda-expression.
18572 D = diag::err_lambda_in_constant_expression;
18573 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18574 // C++17 [expr.prim.lamda]p2:
18575 // A lambda-expression shall not appear [...] in a template-argument.
18576 D = diag::err_lambda_in_invalid_context;
18577 } else
18578 llvm_unreachable("Couldn't infer lambda error message.");
18579
18580 for (const auto *L : Rec.Lambdas)
18581 Diag(L->getBeginLoc(), D);
18582 }
18583 }
18584
18585 // Append the collected materialized temporaries into previous context before
18586 // exit if the previous also is a lifetime extending context.
18588 parentEvaluationContext().InLifetimeExtendingContext &&
18589 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18592 }
18593
18595 HandleImmediateInvocations(*this, Rec);
18596
18597 // Warn on any volatile-qualified simple-assignments that are not discarded-
18598 // value expressions nor unevaluated operands (those cases get removed from
18599 // this list by CheckUnusedVolatileAssignment).
18600 for (auto *BO : Rec.VolatileAssignmentLHSs)
18601 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18602 << BO->getType();
18603
18604 // When are coming out of an unevaluated context, clear out any
18605 // temporaries that we may have created as part of the evaluation of
18606 // the expression in that context: they aren't relevant because they
18607 // will never be constructed.
18608 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18610 ExprCleanupObjects.end());
18611 Cleanup = Rec.ParentCleanup;
18614 // Otherwise, merge the contexts together.
18615 } else {
18616 Cleanup.mergeFrom(Rec.ParentCleanup);
18617 MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
18618 }
18619
18621
18622 // Pop the current expression evaluation context off the stack.
18623 ExprEvalContexts.pop_back();
18624}
18625
18627 ExprCleanupObjects.erase(
18628 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18629 ExprCleanupObjects.end());
18630 Cleanup.reset();
18631 MaybeODRUseExprs.clear();
18632}
18633
18636 if (Result.isInvalid())
18637 return ExprError();
18638 E = Result.get();
18639 if (!E->getType()->isVariablyModifiedType())
18640 return E;
18642}
18643
18644/// Are we in a context that is potentially constant evaluated per C++20
18645/// [expr.const]p12?
18647 /// C++2a [expr.const]p12:
18648 // An expression or conversion is potentially constant evaluated if it is
18649 switch (SemaRef.ExprEvalContexts.back().Context) {
18652
18653 // -- a manifestly constant-evaluated expression,
18657 // -- a potentially-evaluated expression,
18659 // -- an immediate subexpression of a braced-init-list,
18660
18661 // -- [FIXME] an expression of the form & cast-expression that occurs
18662 // within a templated entity
18663 // -- a subexpression of one of the above that is not a subexpression of
18664 // a nested unevaluated operand.
18665 return true;
18666
18669 // Expressions in this context are never evaluated.
18670 return false;
18671 }
18672 llvm_unreachable("Invalid context");
18673}
18674
18675/// Return true if this function has a calling convention that requires mangling
18676/// in the size of the parameter pack.
18678 // These manglings are only applicable for targets whcih use Microsoft
18679 // mangling scheme for C.
18681 return false;
18682
18683 // If this is C++ and this isn't an extern "C" function, parameters do not
18684 // need to be complete. In this case, C++ mangling will apply, which doesn't
18685 // use the size of the parameters.
18686 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18687 return false;
18688
18689 // Stdcall, fastcall, and vectorcall need this special treatment.
18690 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18691 switch (CC) {
18692 case CC_X86StdCall:
18693 case CC_X86FastCall:
18694 case CC_X86VectorCall:
18695 return true;
18696 default:
18697 break;
18698 }
18699 return false;
18700}
18701
18702/// Require that all of the parameter types of function be complete. Normally,
18703/// parameter types are only required to be complete when a function is called
18704/// or defined, but to mangle functions with certain calling conventions, the
18705/// mangler needs to know the size of the parameter list. In this situation,
18706/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18707/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18708/// result in a linker error. Clang doesn't implement this behavior, and instead
18709/// attempts to error at compile time.
18711 SourceLocation Loc) {
18712 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18713 FunctionDecl *FD;
18714 ParmVarDecl *Param;
18715
18716 public:
18717 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18718 : FD(FD), Param(Param) {}
18719
18720 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18721 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18722 StringRef CCName;
18723 switch (CC) {
18724 case CC_X86StdCall:
18725 CCName = "stdcall";
18726 break;
18727 case CC_X86FastCall:
18728 CCName = "fastcall";
18729 break;
18730 case CC_X86VectorCall:
18731 CCName = "vectorcall";
18732 break;
18733 default:
18734 llvm_unreachable("CC does not need mangling");
18735 }
18736
18737 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18738 << Param->getDeclName() << FD->getDeclName() << CCName;
18739 }
18740 };
18741
18742 for (ParmVarDecl *Param : FD->parameters()) {
18743 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18744 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18745 }
18746}
18747
18748namespace {
18749enum class OdrUseContext {
18750 /// Declarations in this context are not odr-used.
18751 None,
18752 /// Declarations in this context are formally odr-used, but this is a
18753 /// dependent context.
18754 Dependent,
18755 /// Declarations in this context are odr-used but not actually used (yet).
18756 FormallyOdrUsed,
18757 /// Declarations in this context are used.
18758 Used
18759};
18760}
18761
18762/// Are we within a context in which references to resolved functions or to
18763/// variables result in odr-use?
18764static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18767
18768 if (Context.isUnevaluated())
18769 return OdrUseContext::None;
18770
18772 return OdrUseContext::Dependent;
18773
18774 if (Context.isDiscardedStatementContext())
18775 return OdrUseContext::FormallyOdrUsed;
18776
18777 else if (Context.Context ==
18779 return OdrUseContext::FormallyOdrUsed;
18780
18781 return OdrUseContext::Used;
18782}
18783
18785 if (!Func->isConstexpr())
18786 return false;
18787
18788 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18789 return true;
18790
18791 // Lambda conversion operators are never user provided.
18792 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))
18793 return isLambdaConversionOperator(Conv);
18794
18795 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18796 return CCD && CCD->getInheritedConstructor();
18797}
18798
18800 bool MightBeOdrUse) {
18801 assert(Func && "No function?");
18802
18803 Func->setReferenced();
18804
18805 // Recursive functions aren't really used until they're used from some other
18806 // context.
18807 bool IsRecursiveCall = CurContext == Func;
18808
18809 // C++11 [basic.def.odr]p3:
18810 // A function whose name appears as a potentially-evaluated expression is
18811 // odr-used if it is the unique lookup result or the selected member of a
18812 // set of overloaded functions [...].
18813 //
18814 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18815 // can just check that here.
18816 OdrUseContext OdrUse =
18817 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18818 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18819 OdrUse = OdrUseContext::FormallyOdrUsed;
18820
18821 // Trivial default constructors and destructors are never actually used.
18822 // FIXME: What about other special members?
18823 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18824 OdrUse == OdrUseContext::Used) {
18825 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18826 if (Constructor->isDefaultConstructor())
18827 OdrUse = OdrUseContext::FormallyOdrUsed;
18829 OdrUse = OdrUseContext::FormallyOdrUsed;
18830 }
18831
18832 // C++20 [expr.const]p12:
18833 // A function [...] is needed for constant evaluation if it is [...] a
18834 // constexpr function that is named by an expression that is potentially
18835 // constant evaluated
18836 bool NeededForConstantEvaluation =
18839
18840 // Determine whether we require a function definition to exist, per
18841 // C++11 [temp.inst]p3:
18842 // Unless a function template specialization has been explicitly
18843 // instantiated or explicitly specialized, the function template
18844 // specialization is implicitly instantiated when the specialization is
18845 // referenced in a context that requires a function definition to exist.
18846 // C++20 [temp.inst]p7:
18847 // The existence of a definition of a [...] function is considered to
18848 // affect the semantics of the program if the [...] function is needed for
18849 // constant evaluation by an expression
18850 // C++20 [basic.def.odr]p10:
18851 // Every program shall contain exactly one definition of every non-inline
18852 // function or variable that is odr-used in that program outside of a
18853 // discarded statement
18854 // C++20 [special]p1:
18855 // The implementation will implicitly define [defaulted special members]
18856 // if they are odr-used or needed for constant evaluation.
18857 //
18858 // Note that we skip the implicit instantiation of templates that are only
18859 // used in unused default arguments or by recursive calls to themselves.
18860 // This is formally non-conforming, but seems reasonable in practice.
18861 bool NeedDefinition =
18862 !IsRecursiveCall &&
18863 (OdrUse == OdrUseContext::Used ||
18864 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18865
18866 // C++14 [temp.expl.spec]p6:
18867 // If a template [...] is explicitly specialized then that specialization
18868 // shall be declared before the first use of that specialization that would
18869 // cause an implicit instantiation to take place, in every translation unit
18870 // in which such a use occurs
18871 if (NeedDefinition &&
18872 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18873 Func->getMemberSpecializationInfo()))
18875
18876 if (getLangOpts().CUDA)
18877 CUDA().CheckCall(Loc, Func);
18878
18879 // If we need a definition, try to create one.
18880 if (NeedDefinition && !Func->getBody()) {
18883 dyn_cast<CXXConstructorDecl>(Func)) {
18885 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18886 if (Constructor->isDefaultConstructor()) {
18887 if (Constructor->isTrivial() &&
18888 !Constructor->hasAttr<DLLExportAttr>())
18889 return;
18891 } else if (Constructor->isCopyConstructor()) {
18893 } else if (Constructor->isMoveConstructor()) {
18895 }
18896 } else if (Constructor->getInheritedConstructor()) {
18898 }
18899 } else if (CXXDestructorDecl *Destructor =
18900 dyn_cast<CXXDestructorDecl>(Func)) {
18902 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18903 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18904 return;
18906 }
18907 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18908 MarkVTableUsed(Loc, Destructor->getParent());
18909 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18910 if (MethodDecl->isOverloadedOperator() &&
18911 MethodDecl->getOverloadedOperator() == OO_Equal) {
18912 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18913 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18914 if (MethodDecl->isCopyAssignmentOperator())
18915 DefineImplicitCopyAssignment(Loc, MethodDecl);
18916 else if (MethodDecl->isMoveAssignmentOperator())
18917 DefineImplicitMoveAssignment(Loc, MethodDecl);
18918 }
18919 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18920 MethodDecl->getParent()->isLambda()) {
18921 CXXConversionDecl *Conversion =
18922 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18923 if (Conversion->isLambdaToBlockPointerConversion())
18925 else
18927 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18928 MarkVTableUsed(Loc, MethodDecl->getParent());
18929 }
18930
18931 if (Func->isDefaulted() && !Func->isDeleted()) {
18935 }
18936
18937 // Implicit instantiation of function templates and member functions of
18938 // class templates.
18939 if (Func->isImplicitlyInstantiable()) {
18941 Func->getTemplateSpecializationKindForInstantiation();
18942 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18943 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18944 if (FirstInstantiation) {
18945 PointOfInstantiation = Loc;
18946 if (auto *MSI = Func->getMemberSpecializationInfo())
18947 MSI->setPointOfInstantiation(Loc);
18948 // FIXME: Notify listener.
18949 else
18950 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18951 } else if (TSK != TSK_ImplicitInstantiation) {
18952 // Use the point of use as the point of instantiation, instead of the
18953 // point of explicit instantiation (which we track as the actual point
18954 // of instantiation). This gives better backtraces in diagnostics.
18955 PointOfInstantiation = Loc;
18956 }
18957
18958 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18959 Func->isConstexpr()) {
18960 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18961 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18962 CodeSynthesisContexts.size())
18964 std::make_pair(Func, PointOfInstantiation));
18965 else if (Func->isConstexpr())
18966 // Do not defer instantiations of constexpr functions, to avoid the
18967 // expression evaluator needing to call back into Sema if it sees a
18968 // call to such a function.
18969 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18970 else {
18971 Func->setInstantiationIsPending(true);
18972 PendingInstantiations.push_back(
18973 std::make_pair(Func, PointOfInstantiation));
18974 if (llvm::isTimeTraceVerbose()) {
18975 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
18976 std::string Name;
18977 llvm::raw_string_ostream OS(Name);
18978 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
18979 /*Qualified=*/true);
18980 return Name;
18981 });
18982 }
18983 // Notify the consumer that a function was implicitly instantiated.
18984 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
18985 }
18986 }
18987 } else {
18988 // Walk redefinitions, as some of them may be instantiable.
18989 for (auto *i : Func->redecls()) {
18990 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18991 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18992 }
18993 }
18994 });
18995 }
18996
18997 // If a constructor was defined in the context of a default parameter
18998 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18999 // context), its initializers may not be referenced yet.
19000 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
19002 *this,
19003 Constructor->isImmediateFunction()
19006 Constructor);
19007 for (CXXCtorInitializer *Init : Constructor->inits()) {
19008 if (Init->isInClassMemberInitializer())
19009 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
19010 MarkDeclarationsReferencedInExpr(Init->getInit());
19011 });
19012 }
19013 }
19014
19015 // C++14 [except.spec]p17:
19016 // An exception-specification is considered to be needed when:
19017 // - the function is odr-used or, if it appears in an unevaluated operand,
19018 // would be odr-used if the expression were potentially-evaluated;
19019 //
19020 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19021 // function is a pure virtual function we're calling, and in that case the
19022 // function was selected by overload resolution and we need to resolve its
19023 // exception specification for a different reason.
19024 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19026 ResolveExceptionSpec(Loc, FPT);
19027
19028 // A callee could be called by a host function then by a device function.
19029 // If we only try recording once, we will miss recording the use on device
19030 // side. Therefore keep trying until it is recorded.
19031 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19032 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
19034
19035 // If this is the first "real" use, act on that.
19036 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19037 // Keep track of used but undefined functions.
19038 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19039 if (mightHaveNonExternalLinkage(Func))
19040 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19041 else if (Func->getMostRecentDecl()->isInlined() &&
19042 !LangOpts.GNUInline &&
19043 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19044 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19046 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19047 }
19048
19049 // Some x86 Windows calling conventions mangle the size of the parameter
19050 // pack into the name. Computing the size of the parameters requires the
19051 // parameter types to be complete. Check that now.
19054
19055 // In the MS C++ ABI, the compiler emits destructor variants where they are
19056 // used. If the destructor is used here but defined elsewhere, mark the
19057 // virtual base destructors referenced. If those virtual base destructors
19058 // are inline, this will ensure they are defined when emitting the complete
19059 // destructor variant. This checking may be redundant if the destructor is
19060 // provided later in this TU.
19061 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19062 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
19063 CXXRecordDecl *Parent = Dtor->getParent();
19064 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19066 }
19067 }
19068
19069 Func->markUsed(Context);
19070 }
19071}
19072
19073/// Directly mark a variable odr-used. Given a choice, prefer to use
19074/// MarkVariableReferenced since it does additional checks and then
19075/// calls MarkVarDeclODRUsed.
19076/// If the variable must be captured:
19077/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19078/// - else capture it in the DeclContext that maps to the
19079/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19080static void
19082 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19083 // Keep track of used but undefined variables.
19084 // FIXME: We shouldn't suppress this warning for static data members.
19085 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19086 assert(Var && "expected a capturable variable");
19087
19089 (!Var->isExternallyVisible() || Var->isInline() ||
19091 !(Var->isStaticDataMember() && Var->hasInit())) {
19093 if (old.isInvalid())
19094 old = Loc;
19095 }
19096 QualType CaptureType, DeclRefType;
19097 if (SemaRef.LangOpts.OpenMP)
19100 /*EllipsisLoc*/ SourceLocation(),
19101 /*BuildAndDiagnose*/ true, CaptureType,
19102 DeclRefType, FunctionScopeIndexToStopAt);
19103
19104 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19105 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
19106 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
19107 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
19108 if (VarTarget == SemaCUDA::CVT_Host &&
19109 (UserTarget == CUDAFunctionTarget::Device ||
19110 UserTarget == CUDAFunctionTarget::HostDevice ||
19111 UserTarget == CUDAFunctionTarget::Global)) {
19112 // Diagnose ODR-use of host global variables in device functions.
19113 // Reference of device global variables in host functions is allowed
19114 // through shadow variables therefore it is not diagnosed.
19115 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19116 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
19117 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19119 Var->getType().isConstQualified()
19120 ? diag::note_cuda_const_var_unpromoted
19121 : diag::note_cuda_host_var);
19122 }
19123 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19124 // Also capture __device__ const variables, which are classified
19125 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19126 // an explicit CUDADeviceAttr to distinguish them from plain
19127 // const variables (no __device__), which also get CVT_Both but
19128 // only have an implicit CUDADeviceAttr.
19129 (VarTarget == SemaCUDA::CVT_Both &&
19130 Var->hasAttr<CUDADeviceAttr>() &&
19131 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19132 !Var->hasAttr<CUDASharedAttr>() &&
19133 (UserTarget == CUDAFunctionTarget::Host ||
19134 UserTarget == CUDAFunctionTarget::HostDevice)) {
19135 // Record a CUDA/HIP device side variable if it is ODR-used
19136 // by host code. This is done conservatively, when the variable is
19137 // referenced in any of the following contexts:
19138 // - a non-function context
19139 // - a host function
19140 // - a host device function
19141 // This makes the ODR-use of the device side variable by host code to
19142 // be visible in the device compilation for the compiler to be able to
19143 // emit template variables instantiated by host code only and to
19144 // externalize the static device side variable ODR-used by host code.
19145 if (!Var->hasExternalStorage())
19147 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19148 (!FD || (!FD->getDescribedFunctionTemplate() &&
19152 }
19153 }
19154
19155 V->markUsed(SemaRef.Context);
19156}
19157
19159 SourceLocation Loc,
19160 unsigned CapturingScopeIndex) {
19161 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
19162}
19163
19165 SourceLocation loc,
19166 ValueDecl *var) {
19167 DeclContext *VarDC = var->getDeclContext();
19168
19169 // If the parameter still belongs to the translation unit, then
19170 // we're actually just using one parameter in the declaration of
19171 // the next.
19172 if (isa<ParmVarDecl>(var) &&
19174 return;
19175
19176 // For C code, don't diagnose about capture if we're not actually in code
19177 // right now; it's impossible to write a non-constant expression outside of
19178 // function context, so we'll get other (more useful) diagnostics later.
19179 //
19180 // For C++, things get a bit more nasty... it would be nice to suppress this
19181 // diagnostic for certain cases like using a local variable in an array bound
19182 // for a member of a local class, but the correct predicate is not obvious.
19183 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19184 return;
19185
19186 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
19187 unsigned ContextKind = 3; // unknown
19188 if (isa<CXXMethodDecl>(VarDC) &&
19189 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
19190 ContextKind = 2;
19191 } else if (isa<FunctionDecl>(VarDC)) {
19192 ContextKind = 0;
19193 } else if (isa<BlockDecl>(VarDC)) {
19194 ContextKind = 1;
19195 }
19196
19197 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
19198 << var << ValueKind << ContextKind << VarDC;
19199 S.Diag(var->getLocation(), diag::note_entity_declared_at)
19200 << var;
19201
19202 // FIXME: Add additional diagnostic info about class etc. which prevents
19203 // capture.
19204}
19205
19207 ValueDecl *Var,
19208 bool &SubCapturesAreNested,
19209 QualType &CaptureType,
19210 QualType &DeclRefType) {
19211 // Check whether we've already captured it.
19212 if (CSI->CaptureMap.count(Var)) {
19213 // If we found a capture, any subcaptures are nested.
19214 SubCapturesAreNested = true;
19215
19216 // Retrieve the capture type for this variable.
19217 CaptureType = CSI->getCapture(Var).getCaptureType();
19218
19219 // Compute the type of an expression that refers to this variable.
19220 DeclRefType = CaptureType.getNonReferenceType();
19221
19222 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19223 // are mutable in the sense that user can change their value - they are
19224 // private instances of the captured declarations.
19225 const Capture &Cap = CSI->getCapture(Var);
19226 // C++ [expr.prim.lambda]p10:
19227 // The type of such a data member is [...] an lvalue reference to the
19228 // referenced function type if the entity is a reference to a function.
19229 // [...]
19230 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19231 !(isa<LambdaScopeInfo>(CSI) &&
19232 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
19234 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19235 DeclRefType.addConst();
19236 return true;
19237 }
19238 return false;
19239}
19240
19241// Only block literals, captured statements, and lambda expressions can
19242// capture; other scopes don't work.
19244 ValueDecl *Var,
19245 SourceLocation Loc,
19246 const bool Diagnose,
19247 Sema &S) {
19250
19251 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19252 if (Underlying) {
19253 if (Underlying->hasLocalStorage() && Diagnose)
19255 }
19256 return nullptr;
19257}
19258
19259// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19260// certain types of variables (unnamed, variably modified types etc.)
19261// so check for eligibility.
19263 SourceLocation Loc, const bool Diagnose,
19264 Sema &S) {
19265
19266 assert((isa<VarDecl, BindingDecl>(Var)) &&
19267 "Only variables and structured bindings can be captured");
19268
19269 bool IsBlock = isa<BlockScopeInfo>(CSI);
19270 bool IsLambda = isa<LambdaScopeInfo>(CSI);
19271
19272 // Lambdas are not allowed to capture unnamed variables
19273 // (e.g. anonymous unions).
19274 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19275 // assuming that's the intent.
19276 if (IsLambda && !Var->getDeclName()) {
19277 if (Diagnose) {
19278 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19279 S.Diag(Var->getLocation(), diag::note_declared_at);
19280 }
19281 return false;
19282 }
19283
19284 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19285 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19286 if (Diagnose) {
19287 S.Diag(Loc, diag::err_ref_vm_type);
19288 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19289 }
19290 return false;
19291 }
19292 // Prohibit structs with flexible array members too.
19293 // We cannot capture what is in the tail end of the struct.
19294 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19295 VTD && VTD->hasFlexibleArrayMember()) {
19296 if (Diagnose) {
19297 if (IsBlock)
19298 S.Diag(Loc, diag::err_ref_flexarray_type);
19299 else
19300 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19301 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19302 }
19303 return false;
19304 }
19305 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19306 // Lambdas and captured statements are not allowed to capture __block
19307 // variables; they don't support the expected semantics.
19308 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19309 if (Diagnose) {
19310 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19311 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19312 }
19313 return false;
19314 }
19315 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19316 if (S.getLangOpts().OpenCL && IsBlock &&
19317 Var->getType()->isBlockPointerType()) {
19318 if (Diagnose)
19319 S.Diag(Loc, diag::err_opencl_block_ref_block);
19320 return false;
19321 }
19322
19323 if (isa<BindingDecl>(Var)) {
19324 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19325 if (Diagnose)
19327 return false;
19328 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19329 S.Diag(Loc, S.LangOpts.CPlusPlus20
19330 ? diag::warn_cxx17_compat_capture_binding
19331 : diag::ext_capture_binding)
19332 << Var;
19333 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19334 }
19335 }
19336
19337 return true;
19338}
19339
19340// Returns true if the capture by block was successful.
19342 SourceLocation Loc, const bool BuildAndDiagnose,
19343 QualType &CaptureType, QualType &DeclRefType,
19344 const bool Nested, Sema &S, bool Invalid) {
19345 bool ByRef = false;
19346
19347 // Blocks are not allowed to capture arrays, excepting OpenCL.
19348 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19349 // (decayed to pointers).
19350 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19351 if (BuildAndDiagnose) {
19352 S.Diag(Loc, diag::err_ref_array_type);
19353 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19354 Invalid = true;
19355 } else {
19356 return false;
19357 }
19358 }
19359
19360 // Forbid the block-capture of autoreleasing variables.
19361 if (!Invalid &&
19363 if (BuildAndDiagnose) {
19364 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19365 << /*block*/ 0;
19366 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19367 Invalid = true;
19368 } else {
19369 return false;
19370 }
19371 }
19372
19373 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19374 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19375 QualType PointeeTy = PT->getPointeeType();
19376
19377 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19379 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19380 if (BuildAndDiagnose) {
19381 SourceLocation VarLoc = Var->getLocation();
19382 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19383 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19384 }
19385 }
19386 }
19387
19388 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19389 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19390 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
19391 // Block capture by reference does not change the capture or
19392 // declaration reference types.
19393 ByRef = true;
19394 } else {
19395 // Block capture by copy introduces 'const'.
19396 CaptureType = CaptureType.getNonReferenceType().withConst();
19397 DeclRefType = CaptureType;
19398 }
19399
19400 // Actually capture the variable.
19401 if (BuildAndDiagnose)
19402 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19403 CaptureType, Invalid);
19404
19405 return !Invalid;
19406}
19407
19408/// Capture the given variable in the captured region.
19411 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19412 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19413 Sema &S, bool Invalid) {
19414 // By default, capture variables by reference.
19415 bool ByRef = true;
19416 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19417 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19418 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19419 // Using an LValue reference type is consistent with Lambdas (see below).
19420 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
19421 bool HasConst = DeclRefType.isConstQualified();
19422 DeclRefType = DeclRefType.getUnqualifiedType();
19423 // Don't lose diagnostics about assignments to const.
19424 if (HasConst)
19425 DeclRefType.addConst();
19426 }
19427 // Do not capture firstprivates in tasks.
19428 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
19429 RSI->OpenMPCaptureLevel) != OMPC_unknown)
19430 return true;
19431 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19432 RSI->OpenMPCaptureLevel);
19433 }
19434
19435 if (ByRef)
19436 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19437 else
19438 CaptureType = DeclRefType;
19439
19440 // Actually capture the variable.
19441 if (BuildAndDiagnose)
19442 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19443 Loc, SourceLocation(), CaptureType, Invalid);
19444
19445 return !Invalid;
19446}
19447
19448/// Capture the given variable in the lambda.
19450 SourceLocation Loc, const bool BuildAndDiagnose,
19451 QualType &CaptureType, QualType &DeclRefType,
19452 const bool RefersToCapturedVariable,
19453 const TryCaptureKind Kind,
19454 SourceLocation EllipsisLoc, const bool IsTopScope,
19455 Sema &S, bool Invalid) {
19456 // Determine whether we are capturing by reference or by value.
19457 bool ByRef = false;
19458 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19459 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19460 } else {
19461 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19462 }
19463
19464 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19466 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19467 Invalid = true;
19468 }
19469
19470 // Compute the type of the field that will capture this variable.
19471 if (ByRef) {
19472 // C++11 [expr.prim.lambda]p15:
19473 // An entity is captured by reference if it is implicitly or
19474 // explicitly captured but not captured by copy. It is
19475 // unspecified whether additional unnamed non-static data
19476 // members are declared in the closure type for entities
19477 // captured by reference.
19478 //
19479 // FIXME: It is not clear whether we want to build an lvalue reference
19480 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19481 // to do the former, while EDG does the latter. Core issue 1249 will
19482 // clarify, but for now we follow GCC because it's a more permissive and
19483 // easily defensible position.
19484 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19485 } else {
19486 // C++11 [expr.prim.lambda]p14:
19487 // For each entity captured by copy, an unnamed non-static
19488 // data member is declared in the closure type. The
19489 // declaration order of these members is unspecified. The type
19490 // of such a data member is the type of the corresponding
19491 // captured entity if the entity is not a reference to an
19492 // object, or the referenced type otherwise. [Note: If the
19493 // captured entity is a reference to a function, the
19494 // corresponding data member is also a reference to a
19495 // function. - end note ]
19496 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19497 if (!RefType->getPointeeType()->isFunctionType())
19498 CaptureType = RefType->getPointeeType();
19499 }
19500
19501 // Forbid the lambda copy-capture of autoreleasing variables.
19502 if (!Invalid &&
19504 if (BuildAndDiagnose) {
19505 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19506 S.Diag(Var->getLocation(), diag::note_previous_decl)
19507 << Var->getDeclName();
19508 Invalid = true;
19509 } else {
19510 return false;
19511 }
19512 }
19513
19514 // Make sure that by-copy captures are of a complete and non-abstract type.
19515 if (!Invalid && BuildAndDiagnose) {
19516 if (!CaptureType->isDependentType() &&
19518 Loc, CaptureType,
19519 diag::err_capture_of_incomplete_or_sizeless_type,
19520 Var->getDeclName()))
19521 Invalid = true;
19522 else if (S.RequireNonAbstractType(Loc, CaptureType,
19523 diag::err_capture_of_abstract_type))
19524 Invalid = true;
19525 }
19526 }
19527
19528 // Compute the type of a reference to this captured variable.
19529 if (ByRef)
19530 DeclRefType = CaptureType.getNonReferenceType();
19531 else {
19532 // C++ [expr.prim.lambda]p5:
19533 // The closure type for a lambda-expression has a public inline
19534 // function call operator [...]. This function call operator is
19535 // declared const (9.3.1) if and only if the lambda-expression's
19536 // parameter-declaration-clause is not followed by mutable.
19537 DeclRefType = CaptureType.getNonReferenceType();
19538 bool Const = LSI->lambdaCaptureShouldBeConst();
19539 // C++ [expr.prim.lambda]p10:
19540 // The type of such a data member is [...] an lvalue reference to the
19541 // referenced function type if the entity is a reference to a function.
19542 // [...]
19543 if (Const && !CaptureType->isReferenceType() &&
19544 !DeclRefType->isFunctionType())
19545 DeclRefType.addConst();
19546 }
19547
19548 // Add the capture.
19549 if (BuildAndDiagnose)
19550 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19551 Loc, EllipsisLoc, CaptureType, Invalid);
19552
19553 return !Invalid;
19554}
19555
19557 const ASTContext &Context) {
19558 // Offer a Copy fix even if the type is dependent.
19559 if (Var->getType()->isDependentType())
19560 return true;
19562 if (T.isTriviallyCopyableType(Context))
19563 return true;
19564 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19565
19566 if (!(RD = RD->getDefinition()))
19567 return false;
19568 if (RD->hasSimpleCopyConstructor())
19569 return true;
19570 if (RD->hasUserDeclaredCopyConstructor())
19571 for (CXXConstructorDecl *Ctor : RD->ctors())
19572 if (Ctor->isCopyConstructor())
19573 return !Ctor->isDeleted();
19574 }
19575 return false;
19576}
19577
19578/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19579/// default capture. Fixes may be omitted if they aren't allowed by the
19580/// standard, for example we can't emit a default copy capture fix-it if we
19581/// already explicitly copy capture capture another variable.
19583 ValueDecl *Var) {
19585 // Don't offer Capture by copy of default capture by copy fixes if Var is
19586 // known not to be copy constructible.
19587 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19588
19589 SmallString<32> FixBuffer;
19590 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19591 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19592 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19593 if (ShouldOfferCopyFix) {
19594 // Offer fixes to insert an explicit capture for the variable.
19595 // [] -> [VarName]
19596 // [OtherCapture] -> [OtherCapture, VarName]
19597 FixBuffer.assign({Separator, Var->getName()});
19598 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19599 << Var << /*value*/ 0
19600 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19601 }
19602 // As above but capture by reference.
19603 FixBuffer.assign({Separator, "&", Var->getName()});
19604 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19605 << Var << /*reference*/ 1
19606 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19607 }
19608
19609 // Only try to offer default capture if there are no captures excluding this
19610 // and init captures.
19611 // [this]: OK.
19612 // [X = Y]: OK.
19613 // [&A, &B]: Don't offer.
19614 // [A, B]: Don't offer.
19615 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19616 return !C.isThisCapture() && !C.isInitCapture();
19617 }))
19618 return;
19619
19620 // The default capture specifiers, '=' or '&', must appear first in the
19621 // capture body.
19622 SourceLocation DefaultInsertLoc =
19624
19625 if (ShouldOfferCopyFix) {
19626 bool CanDefaultCopyCapture = true;
19627 // [=, *this] OK since c++17
19628 // [=, this] OK since c++20
19629 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19630 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19632 : false;
19633 // We can't use default capture by copy if any captures already specified
19634 // capture by copy.
19635 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19636 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19637 })) {
19638 FixBuffer.assign({"=", Separator});
19639 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19640 << /*value*/ 0
19641 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19642 }
19643 }
19644
19645 // We can't use default capture by reference if any captures already specified
19646 // capture by reference.
19647 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19648 return !C.isInitCapture() && C.isReferenceCapture() &&
19649 !C.isThisCapture();
19650 })) {
19651 FixBuffer.assign({"&", Separator});
19652 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19653 << /*reference*/ 1
19654 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19655 }
19656}
19657
19659 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19660 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19661 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19662 // An init-capture is notionally from the context surrounding its
19663 // declaration, but its parent DC is the lambda class.
19664 DeclContext *VarDC = Var->getDeclContext();
19665 DeclContext *DC = CurContext;
19666
19667 // Skip past RequiresExprBodys because they don't constitute function scopes.
19668 while (DC->isRequiresExprBody())
19669 DC = DC->getParent();
19670
19671 // tryCaptureVariable is called every time a DeclRef is formed,
19672 // it can therefore have non-negigible impact on performances.
19673 // For local variables and when there is no capturing scope,
19674 // we can bailout early.
19675 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19676 return true;
19677
19678 // Exception: Function parameters are not tied to the function's DeclContext
19679 // until we enter the function definition. Capturing them anyway would result
19680 // in an out-of-bounds error while traversing DC and its parents.
19681 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
19682 return true;
19683
19684 const auto *VD = dyn_cast<VarDecl>(Var);
19685 if (VD) {
19686 if (VD->isInitCapture())
19687 VarDC = VarDC->getParent();
19688 } else {
19690 }
19691 assert(VD && "Cannot capture a null variable");
19692
19693 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19694 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19695 // We need to sync up the Declaration Context with the
19696 // FunctionScopeIndexToStopAt
19697 if (FunctionScopeIndexToStopAt) {
19698 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19699 unsigned FSIndex = FunctionScopes.size() - 1;
19700 // When we're parsing the lambda parameter list, the current DeclContext is
19701 // NOT the lambda but its parent. So move away the current LSI before
19702 // aligning DC and FunctionScopeIndexToStopAt.
19703 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
19704 FSIndex && LSI && !LSI->AfterParameterList)
19705 --FSIndex;
19706 assert(MaxFunctionScopesIndex <= FSIndex &&
19707 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19708 "FunctionScopes.");
19709 while (FSIndex != MaxFunctionScopesIndex) {
19711 --FSIndex;
19712 }
19713 }
19714
19715 // Capture global variables if it is required to use private copy of this
19716 // variable.
19717 bool IsGlobal = !VD->hasLocalStorage();
19718 if (IsGlobal && !(LangOpts.OpenMP &&
19719 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19720 MaxFunctionScopesIndex)))
19721 return true;
19722
19723 if (isa<VarDecl>(Var))
19724 Var = cast<VarDecl>(Var->getCanonicalDecl());
19725
19726 // Walk up the stack to determine whether we can capture the variable,
19727 // performing the "simple" checks that don't depend on type. We stop when
19728 // we've either hit the declared scope of the variable or find an existing
19729 // capture of that variable. We start from the innermost capturing-entity
19730 // (the DC) and ensure that all intervening capturing-entities
19731 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19732 // declcontext can either capture the variable or have already captured
19733 // the variable.
19734 CaptureType = Var->getType();
19735 DeclRefType = CaptureType.getNonReferenceType();
19736 bool Nested = false;
19737 bool Explicit = (Kind != TryCaptureKind::Implicit);
19738 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19739 do {
19740
19741 LambdaScopeInfo *LSI = nullptr;
19742 if (!FunctionScopes.empty())
19743 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19744 FunctionScopes[FunctionScopesIndex]);
19745
19746 bool IsInScopeDeclarationContext =
19747 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19748
19749 if (LSI && !LSI->AfterParameterList) {
19750 // This allows capturing parameters from a default value which does not
19751 // seems correct
19752 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19753 return true;
19754 }
19755 // If the variable is declared in the current context, there is no need to
19756 // capture it.
19757 if (IsInScopeDeclarationContext &&
19758 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19759 return true;
19760
19761 // Only block literals, captured statements, and lambda expressions can
19762 // capture; other scopes don't work.
19763 DeclContext *ParentDC =
19764 !IsInScopeDeclarationContext
19765 ? DC->getParent()
19766 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19767 BuildAndDiagnose, *this);
19768 // We need to check for the parent *first* because, if we *have*
19769 // private-captured a global variable, we need to recursively capture it in
19770 // intermediate blocks, lambdas, etc.
19771 if (!ParentDC) {
19772 if (IsGlobal) {
19773 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19774 break;
19775 }
19776 return true;
19777 }
19778
19779 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19781
19782 // Check whether we've already captured it.
19783 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19784 DeclRefType)) {
19785 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19786 break;
19787 }
19788
19789 // When evaluating some attributes (like enable_if) we might refer to a
19790 // function parameter appertaining to the same declaration as that
19791 // attribute.
19792 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19793 Parm && Parm->getDeclContext() == DC)
19794 return true;
19795
19796 // If we are instantiating a generic lambda call operator body,
19797 // we do not want to capture new variables. What was captured
19798 // during either a lambdas transformation or initial parsing
19799 // should be used.
19801 if (BuildAndDiagnose) {
19804 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19805 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19806 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19807 buildLambdaCaptureFixit(*this, LSI, Var);
19808 } else
19810 }
19811 return true;
19812 }
19813
19814 // Try to capture variable-length arrays types.
19815 if (Var->getType()->isVariablyModifiedType()) {
19816 // We're going to walk down into the type and look for VLA
19817 // expressions.
19818 QualType QTy = Var->getType();
19819 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19820 QTy = PVD->getOriginalType();
19822 }
19823
19824 if (getLangOpts().OpenMP) {
19825 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19826 // OpenMP private variables should not be captured in outer scope, so
19827 // just break here. Similarly, global variables that are captured in a
19828 // target region should not be captured outside the scope of the region.
19829 if (RSI->CapRegionKind == CR_OpenMP) {
19830 // FIXME: We should support capturing structured bindings in OpenMP.
19831 if (isa<BindingDecl>(Var)) {
19832 if (BuildAndDiagnose) {
19833 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19834 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19835 }
19836 return true;
19837 }
19838 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19839 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19840 // If the variable is private (i.e. not captured) and has variably
19841 // modified type, we still need to capture the type for correct
19842 // codegen in all regions, associated with the construct. Currently,
19843 // it is captured in the innermost captured region only.
19844 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19845 Var->getType()->isVariablyModifiedType()) {
19846 QualType QTy = Var->getType();
19847 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19848 QTy = PVD->getOriginalType();
19849 for (int I = 1,
19850 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19851 I < E; ++I) {
19852 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19853 FunctionScopes[FunctionScopesIndex - I]);
19854 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19855 "Wrong number of captured regions associated with the "
19856 "OpenMP construct.");
19857 captureVariablyModifiedType(Context, QTy, OuterRSI);
19858 }
19859 }
19860 bool IsTargetCap =
19861 IsOpenMPPrivateDecl != OMPC_private &&
19862 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19863 RSI->OpenMPCaptureLevel);
19864 // Do not capture global if it is not privatized in outer regions.
19865 bool IsGlobalCap =
19866 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19867 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19868
19869 // When we detect target captures we are looking from inside the
19870 // target region, therefore we need to propagate the capture from the
19871 // enclosing region. Therefore, the capture is not initially nested.
19872 if (IsTargetCap)
19873 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19874 RSI->OpenMPLevel);
19875
19876 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19877 (IsGlobal && !IsGlobalCap)) {
19878 Nested = !IsTargetCap;
19879 bool HasConst = DeclRefType.isConstQualified();
19880 DeclRefType = DeclRefType.getUnqualifiedType();
19881 // Don't lose diagnostics about assignments to const.
19882 if (HasConst)
19883 DeclRefType.addConst();
19884 CaptureType = Context.getLValueReferenceType(DeclRefType);
19885 break;
19886 }
19887 }
19888 }
19889 }
19891 // No capture-default, and this is not an explicit capture
19892 // so cannot capture this variable.
19893 if (BuildAndDiagnose) {
19894 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19895 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19896 auto *LSI = cast<LambdaScopeInfo>(CSI);
19897 if (LSI->Lambda) {
19898 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19899 buildLambdaCaptureFixit(*this, LSI, Var);
19900 }
19901 // FIXME: If we error out because an outer lambda can not implicitly
19902 // capture a variable that an inner lambda explicitly captures, we
19903 // should have the inner lambda do the explicit capture - because
19904 // it makes for cleaner diagnostics later. This would purely be done
19905 // so that the diagnostic does not misleadingly claim that a variable
19906 // can not be captured by a lambda implicitly even though it is captured
19907 // explicitly. Suggestion:
19908 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19909 // at the function head
19910 // - cache the StartingDeclContext - this must be a lambda
19911 // - captureInLambda in the innermost lambda the variable.
19912 }
19913 return true;
19914 }
19915 Explicit = false;
19916 FunctionScopesIndex--;
19917 if (IsInScopeDeclarationContext)
19918 DC = ParentDC;
19919 } while (!VarDC->Equals(DC));
19920
19921 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19922 // computing the type of the capture at each step, checking type-specific
19923 // requirements, and adding captures if requested.
19924 // If the variable had already been captured previously, we start capturing
19925 // at the lambda nested within that one.
19926 bool Invalid = false;
19927 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19928 ++I) {
19930
19931 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19932 // certain types of variables (unnamed, variably modified types etc.)
19933 // so check for eligibility.
19934 if (!Invalid)
19935 Invalid =
19936 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19937
19938 // After encountering an error, if we're actually supposed to capture, keep
19939 // capturing in nested contexts to suppress any follow-on diagnostics.
19940 if (Invalid && !BuildAndDiagnose)
19941 return true;
19942
19943 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19944 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19945 DeclRefType, Nested, *this, Invalid);
19946 Nested = true;
19947 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19949 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19950 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19951 Nested = true;
19952 } else {
19954 Invalid =
19955 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19956 DeclRefType, Nested, Kind, EllipsisLoc,
19957 /*IsTopScope*/ I == N - 1, *this, Invalid);
19958 Nested = true;
19959 }
19960
19961 if (Invalid && !BuildAndDiagnose)
19962 return true;
19963 }
19964 return Invalid;
19965}
19966
19968 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19969 QualType CaptureType;
19970 QualType DeclRefType;
19971 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19972 /*BuildAndDiagnose=*/true, CaptureType,
19973 DeclRefType, nullptr);
19974}
19975
19977 QualType CaptureType;
19978 QualType DeclRefType;
19979 return !tryCaptureVariable(
19981 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);
19982}
19983
19985 assert(Var && "Null value cannot be captured");
19986
19987 QualType CaptureType;
19988 QualType DeclRefType;
19989
19990 // Determine whether we can capture this variable.
19992 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
19993 nullptr))
19994 return QualType();
19995
19996 return DeclRefType;
19997}
19998
19999namespace {
20000// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20001// The produced TemplateArgumentListInfo* points to data stored within this
20002// object, so should only be used in contexts where the pointer will not be
20003// used after the CopiedTemplateArgs object is destroyed.
20004class CopiedTemplateArgs {
20005 bool HasArgs;
20006 TemplateArgumentListInfo TemplateArgStorage;
20007public:
20008 template<typename RefExpr>
20009 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20010 if (HasArgs)
20011 E->copyTemplateArgumentsInto(TemplateArgStorage);
20012 }
20013 operator TemplateArgumentListInfo*()
20014#ifdef __has_cpp_attribute
20015#if __has_cpp_attribute(clang::lifetimebound)
20016 [[clang::lifetimebound]]
20017#endif
20018#endif
20019 {
20020 return HasArgs ? &TemplateArgStorage : nullptr;
20021 }
20022};
20023}
20024
20025/// Walk the set of potential results of an expression and mark them all as
20026/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20027///
20028/// \return A new expression if we found any potential results, ExprEmpty() if
20029/// not, and ExprError() if we diagnosed an error.
20031 NonOdrUseReason NOUR) {
20032 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20033 // an object that satisfies the requirements for appearing in a
20034 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20035 // is immediately applied." This function handles the lvalue-to-rvalue
20036 // conversion part.
20037 //
20038 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20039 // transform it into the relevant kind of non-odr-use node and rebuild the
20040 // tree of nodes leading to it.
20041 //
20042 // This is a mini-TreeTransform that only transforms a restricted subset of
20043 // nodes (and only certain operands of them).
20044
20045 // Rebuild a subexpression.
20046 auto Rebuild = [&](Expr *Sub) {
20047 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
20048 };
20049
20050 // Check whether a potential result satisfies the requirements of NOUR.
20051 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20052 // Any entity other than a VarDecl is always odr-used whenever it's named
20053 // in a potentially-evaluated expression.
20054 auto *VD = dyn_cast<VarDecl>(D);
20055 if (!VD)
20056 return true;
20057
20058 // C++2a [basic.def.odr]p4:
20059 // A variable x whose name appears as a potentially-evalauted expression
20060 // e is odr-used by e unless
20061 // -- x is a reference that is usable in constant expressions, or
20062 // -- x is a variable of non-reference type that is usable in constant
20063 // expressions and has no mutable subobjects, and e is an element of
20064 // the set of potential results of an expression of
20065 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20066 // conversion is applied, or
20067 // -- x is a variable of non-reference type, and e is an element of the
20068 // set of potential results of a discarded-value expression to which
20069 // the lvalue-to-rvalue conversion is not applied
20070 //
20071 // We check the first bullet and the "potentially-evaluated" condition in
20072 // BuildDeclRefExpr. We check the type requirements in the second bullet
20073 // in CheckLValueToRValueConversionOperand below.
20074 switch (NOUR) {
20075 case NOUR_None:
20076 case NOUR_Unevaluated:
20077 llvm_unreachable("unexpected non-odr-use-reason");
20078
20079 case NOUR_Constant:
20080 // Constant references were handled when they were built.
20081 if (VD->getType()->isReferenceType())
20082 return true;
20083 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20084 if (RD->hasDefinition() && RD->hasMutableFields())
20085 return true;
20086 if (!VD->isUsableInConstantExpressions(S.Context))
20087 return true;
20088 break;
20089
20090 case NOUR_Discarded:
20091 if (VD->getType()->isReferenceType())
20092 return true;
20093 break;
20094 }
20095 return false;
20096 };
20097
20098 // Check whether this expression may be odr-used in CUDA/HIP.
20099 auto MaybeCUDAODRUsed = [&]() -> bool {
20100 if (!S.LangOpts.CUDA)
20101 return false;
20102 LambdaScopeInfo *LSI = S.getCurLambda();
20103 if (!LSI)
20104 return false;
20105 auto *DRE = dyn_cast<DeclRefExpr>(E);
20106 if (!DRE)
20107 return false;
20108 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
20109 if (!VD)
20110 return false;
20111 return LSI->CUDAPotentialODRUsedVars.count(VD);
20112 };
20113
20114 // Mark that this expression does not constitute an odr-use.
20115 auto MarkNotOdrUsed = [&] {
20116 if (!MaybeCUDAODRUsed()) {
20117 S.MaybeODRUseExprs.remove(E);
20118 if (LambdaScopeInfo *LSI = S.getCurLambda())
20119 LSI->markVariableExprAsNonODRUsed(E);
20120 }
20121 };
20122
20123 // C++2a [basic.def.odr]p2:
20124 // The set of potential results of an expression e is defined as follows:
20125 switch (E->getStmtClass()) {
20126 // -- If e is an id-expression, ...
20127 case Expr::DeclRefExprClass: {
20128 auto *DRE = cast<DeclRefExpr>(E);
20129 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20130 break;
20131
20132 // Rebuild as a non-odr-use DeclRefExpr.
20133 MarkNotOdrUsed();
20134 return DeclRefExpr::Create(
20135 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
20136 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
20137 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
20138 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
20139 }
20140
20141 case Expr::FunctionParmPackExprClass: {
20142 auto *FPPE = cast<FunctionParmPackExpr>(E);
20143 // If any of the declarations in the pack is odr-used, then the expression
20144 // as a whole constitutes an odr-use.
20145 for (ValueDecl *D : *FPPE)
20146 if (IsPotentialResultOdrUsed(D))
20147 return ExprEmpty();
20148
20149 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20150 // nothing cares about whether we marked this as an odr-use, but it might
20151 // be useful for non-compiler tools.
20152 MarkNotOdrUsed();
20153 break;
20154 }
20155
20156 // -- If e is a subscripting operation with an array operand...
20157 case Expr::ArraySubscriptExprClass: {
20158 auto *ASE = cast<ArraySubscriptExpr>(E);
20159 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20160 if (!OldBase->getType()->isArrayType())
20161 break;
20162 ExprResult Base = Rebuild(OldBase);
20163 if (!Base.isUsable())
20164 return Base;
20165 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20166 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20167 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20168 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
20169 ASE->getRBracketLoc());
20170 }
20171
20172 case Expr::MemberExprClass: {
20173 auto *ME = cast<MemberExpr>(E);
20174 // -- If e is a class member access expression [...] naming a non-static
20175 // data member...
20176 if (isa<FieldDecl>(ME->getMemberDecl())) {
20177 ExprResult Base = Rebuild(ME->getBase());
20178 if (!Base.isUsable())
20179 return Base;
20180 return MemberExpr::Create(
20181 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
20182 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
20183 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
20184 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
20185 ME->getObjectKind(), ME->isNonOdrUse());
20186 }
20187
20188 if (ME->getMemberDecl()->isCXXInstanceMember())
20189 break;
20190
20191 // -- If e is a class member access expression naming a static data member,
20192 // ...
20193 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20194 break;
20195
20196 // Rebuild as a non-odr-use MemberExpr.
20197 MarkNotOdrUsed();
20198 return MemberExpr::Create(
20199 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
20200 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
20201 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
20202 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
20203 }
20204
20205 case Expr::BinaryOperatorClass: {
20206 auto *BO = cast<BinaryOperator>(E);
20207 Expr *LHS = BO->getLHS();
20208 Expr *RHS = BO->getRHS();
20209 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20210 if (BO->getOpcode() == BO_PtrMemD) {
20211 ExprResult Sub = Rebuild(LHS);
20212 if (!Sub.isUsable())
20213 return Sub;
20214 BO->setLHS(Sub.get());
20215 // -- If e is a comma expression, ...
20216 } else if (BO->getOpcode() == BO_Comma) {
20217 ExprResult Sub = Rebuild(RHS);
20218 if (!Sub.isUsable())
20219 return Sub;
20220 BO->setRHS(Sub.get());
20221 } else {
20222 break;
20223 }
20224 return ExprResult(BO);
20225 }
20226
20227 // -- If e has the form (e1)...
20228 case Expr::ParenExprClass: {
20229 auto *PE = cast<ParenExpr>(E);
20230 ExprResult Sub = Rebuild(PE->getSubExpr());
20231 if (!Sub.isUsable())
20232 return Sub;
20233 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20234 }
20235
20236 // -- If e is a glvalue conditional expression, ...
20237 // We don't apply this to a binary conditional operator. FIXME: Should we?
20238 case Expr::ConditionalOperatorClass: {
20239 auto *CO = cast<ConditionalOperator>(E);
20240 ExprResult LHS = Rebuild(CO->getLHS());
20241 if (LHS.isInvalid())
20242 return ExprError();
20243 ExprResult RHS = Rebuild(CO->getRHS());
20244 if (RHS.isInvalid())
20245 return ExprError();
20246 if (!LHS.isUsable() && !RHS.isUsable())
20247 return ExprEmpty();
20248 if (!LHS.isUsable())
20249 LHS = CO->getLHS();
20250 if (!RHS.isUsable())
20251 RHS = CO->getRHS();
20252 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20253 CO->getCond(), LHS.get(), RHS.get());
20254 }
20255
20256 // [Clang extension]
20257 // -- If e has the form __extension__ e1...
20258 case Expr::UnaryOperatorClass: {
20259 auto *UO = cast<UnaryOperator>(E);
20260 if (UO->getOpcode() != UO_Extension)
20261 break;
20262 ExprResult Sub = Rebuild(UO->getSubExpr());
20263 if (!Sub.isUsable())
20264 return Sub;
20265 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20266 Sub.get());
20267 }
20268
20269 // [Clang extension]
20270 // -- If e has the form _Generic(...), the set of potential results is the
20271 // union of the sets of potential results of the associated expressions.
20272 case Expr::GenericSelectionExprClass: {
20273 auto *GSE = cast<GenericSelectionExpr>(E);
20274
20275 SmallVector<Expr *, 4> AssocExprs;
20276 bool AnyChanged = false;
20277 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20278 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20279 if (AssocExpr.isInvalid())
20280 return ExprError();
20281 if (AssocExpr.isUsable()) {
20282 AssocExprs.push_back(AssocExpr.get());
20283 AnyChanged = true;
20284 } else {
20285 AssocExprs.push_back(OrigAssocExpr);
20286 }
20287 }
20288
20289 void *ExOrTy = nullptr;
20290 bool IsExpr = GSE->isExprPredicate();
20291 if (IsExpr)
20292 ExOrTy = GSE->getControllingExpr();
20293 else
20294 ExOrTy = GSE->getControllingType();
20295 return AnyChanged ? S.CreateGenericSelectionExpr(
20296 GSE->getGenericLoc(), GSE->getDefaultLoc(),
20297 GSE->getRParenLoc(), IsExpr, ExOrTy,
20298 GSE->getAssocTypeSourceInfos(), AssocExprs)
20299 : ExprEmpty();
20300 }
20301
20302 // [Clang extension]
20303 // -- If e has the form __builtin_choose_expr(...), the set of potential
20304 // results is the union of the sets of potential results of the
20305 // second and third subexpressions.
20306 case Expr::ChooseExprClass: {
20307 auto *CE = cast<ChooseExpr>(E);
20308
20309 ExprResult LHS = Rebuild(CE->getLHS());
20310 if (LHS.isInvalid())
20311 return ExprError();
20312
20313 ExprResult RHS = Rebuild(CE->getLHS());
20314 if (RHS.isInvalid())
20315 return ExprError();
20316
20317 if (!LHS.get() && !RHS.get())
20318 return ExprEmpty();
20319 if (!LHS.isUsable())
20320 LHS = CE->getLHS();
20321 if (!RHS.isUsable())
20322 RHS = CE->getRHS();
20323
20324 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20325 RHS.get(), CE->getRParenLoc());
20326 }
20327
20328 // Step through non-syntactic nodes.
20329 case Expr::ConstantExprClass: {
20330 auto *CE = cast<ConstantExpr>(E);
20331 ExprResult Sub = Rebuild(CE->getSubExpr());
20332 if (!Sub.isUsable())
20333 return Sub;
20334 return ConstantExpr::Create(S.Context, Sub.get());
20335 }
20336
20337 // We could mostly rely on the recursive rebuilding to rebuild implicit
20338 // casts, but not at the top level, so rebuild them here.
20339 case Expr::ImplicitCastExprClass: {
20340 auto *ICE = cast<ImplicitCastExpr>(E);
20341 // Only step through the narrow set of cast kinds we expect to encounter.
20342 // Anything else suggests we've left the region in which potential results
20343 // can be found.
20344 switch (ICE->getCastKind()) {
20345 case CK_NoOp:
20346 case CK_DerivedToBase:
20347 case CK_UncheckedDerivedToBase: {
20348 ExprResult Sub = Rebuild(ICE->getSubExpr());
20349 if (!Sub.isUsable())
20350 return Sub;
20351 CXXCastPath Path(ICE->path());
20352 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20353 ICE->getValueKind(), &Path);
20354 }
20355
20356 default:
20357 break;
20358 }
20359 break;
20360 }
20361
20362 default:
20363 break;
20364 }
20365
20366 // Can't traverse through this node. Nothing to do.
20367 return ExprEmpty();
20368}
20369
20371 // Check whether the operand is or contains an object of non-trivial C union
20372 // type.
20373 if (E->getType().isVolatileQualified() &&
20379
20380 // C++2a [basic.def.odr]p4:
20381 // [...] an expression of non-volatile-qualified non-class type to which
20382 // the lvalue-to-rvalue conversion is applied [...]
20383 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20384 return E;
20385
20388 if (Result.isInvalid())
20389 return ExprError();
20390 return Result.get() ? Result : E;
20391}
20392
20394 if (!Res.isUsable())
20395 return Res;
20396
20397 // If a constant-expression is a reference to a variable where we delay
20398 // deciding whether it is an odr-use, just assume we will apply the
20399 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20400 // (a non-type template argument), we have special handling anyway.
20402}
20403
20405 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20406 // call.
20407 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20408 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20409
20410 for (Expr *E : LocalMaybeODRUseExprs) {
20411 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20412 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20413 DRE->getLocation(), *this);
20414 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20415 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20416 *this);
20417 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20418 for (ValueDecl *VD : *FP)
20419 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20420 } else {
20421 llvm_unreachable("Unexpected expression");
20422 }
20423 }
20424
20425 assert(MaybeODRUseExprs.empty() &&
20426 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20427}
20428
20430 ValueDecl *Var, Expr *E) {
20432 if (!VD)
20433 return;
20434
20435 const bool RefersToEnclosingScope =
20436 (SemaRef.CurContext != VD->getDeclContext() &&
20438 if (RefersToEnclosingScope) {
20439 LambdaScopeInfo *const LSI =
20440 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20441 if (LSI && (!LSI->CallOperator ||
20442 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20443 // If a variable could potentially be odr-used, defer marking it so
20444 // until we finish analyzing the full expression for any
20445 // lvalue-to-rvalue
20446 // or discarded value conversions that would obviate odr-use.
20447 // Add it to the list of potential captures that will be analyzed
20448 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20449 // unless the variable is a reference that was initialized by a constant
20450 // expression (this will never need to be captured or odr-used).
20451 //
20452 // FIXME: We can simplify this a lot after implementing P0588R1.
20453 assert(E && "Capture variable should be used in an expression.");
20454 if (!Var->getType()->isReferenceType() ||
20457 }
20458 }
20459}
20460
20462 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20463 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20464 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20466 "Invalid Expr argument to DoMarkVarDeclReferenced");
20467 Var->setReferenced();
20468
20469 if (Var->isInvalidDecl())
20470 return;
20471
20472 auto *MSI = Var->getMemberSpecializationInfo();
20473 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20475
20476 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20477 bool UsableInConstantExpr =
20479
20480 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
20481 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
20482 }
20483
20484 // C++20 [expr.const]p12:
20485 // A variable [...] is needed for constant evaluation if it is [...] a
20486 // variable whose name appears as a potentially constant evaluated
20487 // expression that is either a contexpr variable or is of non-volatile
20488 // const-qualified integral type or of reference type
20489 bool NeededForConstantEvaluation =
20490 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20491
20492 bool NeedDefinition =
20493 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20494 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20495 Var->getType()->isUndeducedType());
20496
20498 "Can't instantiate a partial template specialization.");
20499
20500 // If this might be a member specialization of a static data member, check
20501 // the specialization is visible. We already did the checks for variable
20502 // template specializations when we created them.
20503 if (NeedDefinition && TSK != TSK_Undeclared &&
20506
20507 // Perform implicit instantiation of static data members, static data member
20508 // templates of class templates, and variable template specializations. Delay
20509 // instantiations of variable templates, except for those that could be used
20510 // in a constant expression.
20511 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20512 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20513 // instantiation declaration if a variable is usable in a constant
20514 // expression (among other cases).
20515 bool TryInstantiating =
20517 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20518
20519 if (TryInstantiating) {
20520 SourceLocation PointOfInstantiation =
20521 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20522 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20523 if (FirstInstantiation) {
20524 PointOfInstantiation = Loc;
20525 if (MSI)
20526 MSI->setPointOfInstantiation(PointOfInstantiation);
20527 // FIXME: Notify listener.
20528 else
20529 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20530 }
20531
20532 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20533 // Do not defer instantiations of variables that could be used in a
20534 // constant expression.
20535 // The type deduction also needs a complete initializer.
20536 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20537 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20538 });
20539
20540 // The size of an incomplete array type can be updated by
20541 // instantiating the initializer. The DeclRefExpr's type should be
20542 // updated accordingly too, or users of it would be confused!
20543 if (E)
20545
20546 // Re-set the member to trigger a recomputation of the dependence bits
20547 // for the expression.
20548 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20549 DRE->setDecl(DRE->getDecl());
20550 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20551 ME->setMemberDecl(ME->getMemberDecl());
20552 } else if (FirstInstantiation) {
20554 .push_back(std::make_pair(Var, PointOfInstantiation));
20555 } else {
20556 bool Inserted = false;
20557 for (auto &I : SemaRef.SavedPendingInstantiations) {
20558 auto Iter = llvm::find_if(
20559 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20560 return P.first == Var;
20561 });
20562 if (Iter != I.end()) {
20563 SemaRef.PendingInstantiations.push_back(*Iter);
20564 I.erase(Iter);
20565 Inserted = true;
20566 break;
20567 }
20568 }
20569
20570 // FIXME: For a specialization of a variable template, we don't
20571 // distinguish between "declaration and type implicitly instantiated"
20572 // and "implicit instantiation of definition requested", so we have
20573 // no direct way to avoid enqueueing the pending instantiation
20574 // multiple times.
20575 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20577 .push_back(std::make_pair(Var, PointOfInstantiation));
20578 }
20579 }
20580 }
20581
20582 // C++2a [basic.def.odr]p4:
20583 // A variable x whose name appears as a potentially-evaluated expression e
20584 // is odr-used by e unless
20585 // -- x is a reference that is usable in constant expressions
20586 // -- x is a variable of non-reference type that is usable in constant
20587 // expressions and has no mutable subobjects [FIXME], and e is an
20588 // element of the set of potential results of an expression of
20589 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20590 // conversion is applied
20591 // -- x is a variable of non-reference type, and e is an element of the set
20592 // of potential results of a discarded-value expression to which the
20593 // lvalue-to-rvalue conversion is not applied [FIXME]
20594 //
20595 // We check the first part of the second bullet here, and
20596 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20597 // FIXME: To get the third bullet right, we need to delay this even for
20598 // variables that are not usable in constant expressions.
20599
20600 // If we already know this isn't an odr-use, there's nothing more to do.
20601 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20602 if (DRE->isNonOdrUse())
20603 return;
20604 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20605 if (ME->isNonOdrUse())
20606 return;
20607
20608 switch (OdrUse) {
20609 case OdrUseContext::None:
20610 // In some cases, a variable may not have been marked unevaluated, if it
20611 // appears in a defaukt initializer.
20612 assert((!E || isa<FunctionParmPackExpr>(E) ||
20614 "missing non-odr-use marking for unevaluated decl ref");
20615 break;
20616
20617 case OdrUseContext::FormallyOdrUsed:
20618 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20619 // behavior.
20620 break;
20621
20622 case OdrUseContext::Used:
20623 // If we might later find that this expression isn't actually an odr-use,
20624 // delay the marking.
20626 SemaRef.MaybeODRUseExprs.insert(E);
20627 else
20628 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20629 break;
20630
20631 case OdrUseContext::Dependent:
20632 // If this is a dependent context, we don't need to mark variables as
20633 // odr-used, but we may still need to track them for lambda capture.
20634 // FIXME: Do we also need to do this inside dependent typeid expressions
20635 // (which are modeled as unevaluated at this point)?
20636 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20637 break;
20638 }
20639}
20640
20642 BindingDecl *BD, Expr *E) {
20643 BD->setReferenced();
20644
20645 if (BD->isInvalidDecl())
20646 return;
20647
20648 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20649 if (OdrUse == OdrUseContext::Used) {
20650 QualType CaptureType, DeclRefType;
20652 /*EllipsisLoc*/ SourceLocation(),
20653 /*BuildAndDiagnose*/ true, CaptureType,
20654 DeclRefType,
20655 /*FunctionScopeIndexToStopAt*/ nullptr);
20656 } else if (OdrUse == OdrUseContext::Dependent) {
20657 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20658 }
20659}
20660
20662 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20663}
20664
20665// C++ [temp.dep.expr]p3:
20666// An id-expression is type-dependent if it contains:
20667// - an identifier associated by name lookup with an entity captured by copy
20668// in a lambda-expression that has an explicit object parameter whose type
20669// is dependent ([dcl.fct]),
20671 Sema &SemaRef, ValueDecl *D, Expr *E) {
20672 auto *ID = dyn_cast<DeclRefExpr>(E);
20673 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20674 return;
20675
20676 // If any enclosing lambda with a dependent explicit object parameter either
20677 // explicitly captures the variable by value, or has a capture default of '='
20678 // and does not capture the variable by reference, then the type of the DRE
20679 // is dependent on the type of that lambda's explicit object parameter.
20680 auto IsDependent = [&]() {
20681 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
20682 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
20683 if (!LSI)
20684 continue;
20685
20686 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
20687 LSI->AfterParameterList)
20688 return false;
20689
20690 const auto *MD = LSI->CallOperator;
20691 if (MD->getType().isNull())
20692 continue;
20693
20694 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20695 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20696 !Ty->getParamType(0)->isDependentType())
20697 continue;
20698
20699 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
20700 if (C->isCopyCapture())
20701 return true;
20702 continue;
20703 }
20704
20705 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20706 return true;
20707 }
20708 return false;
20709 }();
20710
20711 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20712 IsDependent, SemaRef.getASTContext());
20713}
20714
20715static void
20717 bool MightBeOdrUse,
20718 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20721
20722 if (SemaRef.getLangOpts().OpenACC)
20723 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20724
20725 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20727 if (SemaRef.getLangOpts().CPlusPlus)
20729 Var, E);
20730 return;
20731 }
20732
20733 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20735 if (SemaRef.getLangOpts().CPlusPlus)
20737 Decl, E);
20738 return;
20739 }
20740 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20741
20742 // If this is a call to a method via a cast, also mark the method in the
20743 // derived class used in case codegen can devirtualize the call.
20744 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20745 if (!ME)
20746 return;
20747 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20748 if (!MD)
20749 return;
20750 // Only attempt to devirtualize if this is truly a virtual call.
20751 bool IsVirtualCall = MD->isVirtual() &&
20753 if (!IsVirtualCall)
20754 return;
20755
20756 // If it's possible to devirtualize the call, mark the called function
20757 // referenced.
20759 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20760 if (DM)
20761 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20762}
20763
20765 // [basic.def.odr] (CWG 1614)
20766 // A function is named by an expression or conversion [...]
20767 // unless it is a pure virtual function and either the expression is not an
20768 // id-expression naming the function with an explicitly qualified name or
20769 // the expression forms a pointer to member
20770 bool OdrUse = true;
20771 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20772 if (Method->isVirtual() &&
20773 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20774 OdrUse = false;
20775
20776 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20780 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20781 !FD->isDependentContext())
20782 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20783 }
20784 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20786}
20787
20789 // C++11 [basic.def.odr]p2:
20790 // A non-overloaded function whose name appears as a potentially-evaluated
20791 // expression or a member of a set of candidate functions, if selected by
20792 // overload resolution when referred to from a potentially-evaluated
20793 // expression, is odr-used, unless it is a pure virtual function and its
20794 // name is not explicitly qualified.
20795 bool MightBeOdrUse = true;
20797 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20798 if (Method->isPureVirtual())
20799 MightBeOdrUse = false;
20800 }
20801 SourceLocation Loc =
20802 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20803 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20805}
20806
20812
20813/// Perform marking for a reference to an arbitrary declaration. It
20814/// marks the declaration referenced, and performs odr-use checking for
20815/// functions and variables. This method should not be used when building a
20816/// normal expression which refers to a variable.
20818 bool MightBeOdrUse) {
20819 if (MightBeOdrUse) {
20820 if (auto *VD = dyn_cast<VarDecl>(D)) {
20821 MarkVariableReferenced(Loc, VD);
20822 return;
20823 }
20824 }
20825 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20826 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20827 return;
20828 }
20829 D->setReferenced();
20830}
20831
20832namespace {
20833 // Mark all of the declarations used by a type as referenced.
20834 // FIXME: Not fully implemented yet! We need to have a better understanding
20835 // of when we're entering a context we should not recurse into.
20836 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20837 // TreeTransforms rebuilding the type in a new context. Rather than
20838 // duplicating the TreeTransform logic, we should consider reusing it here.
20839 // Currently that causes problems when rebuilding LambdaExprs.
20840class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20841 Sema &S;
20842 SourceLocation Loc;
20843
20844public:
20845 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20846
20847 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20848};
20849}
20850
20851bool MarkReferencedDecls::TraverseTemplateArgument(
20852 const TemplateArgument &Arg) {
20853 {
20854 // A non-type template argument is a constant-evaluated context.
20855 EnterExpressionEvaluationContext Evaluated(
20858 if (Decl *D = Arg.getAsDecl())
20859 S.MarkAnyDeclReferenced(Loc, D, true);
20860 } else if (Arg.getKind() == TemplateArgument::Expression) {
20862 }
20863 }
20864
20866}
20867
20869 MarkReferencedDecls Marker(*this, Loc);
20870 Marker.TraverseType(T);
20871}
20872
20873namespace {
20874/// Helper class that marks all of the declarations referenced by
20875/// potentially-evaluated subexpressions as "referenced".
20876class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20877public:
20878 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20879 bool SkipLocalVariables;
20881
20882 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20884 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20885
20886 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20888 }
20889
20890 void Visit(Expr *E) {
20891 if (llvm::is_contained(StopAt, E))
20892 return;
20893 Inherited::Visit(E);
20894 }
20895
20896 void VisitConstantExpr(ConstantExpr *E) {
20897 // Don't mark declarations within a ConstantExpression, as this expression
20898 // will be evaluated and folded to a value.
20899 }
20900
20901 void VisitDeclRefExpr(DeclRefExpr *E) {
20902 // If we were asked not to visit local variables, don't.
20903 if (SkipLocalVariables) {
20904 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20905 if (VD->hasLocalStorage())
20906 return;
20907 }
20908
20909 // FIXME: This can trigger the instantiation of the initializer of a
20910 // variable, which can cause the expression to become value-dependent
20911 // or error-dependent. Do we need to propagate the new dependence bits?
20913 }
20914
20915 void VisitMemberExpr(MemberExpr *E) {
20917 Visit(E->getBase());
20918 }
20919};
20920} // namespace
20921
20923 bool SkipLocalVariables,
20924 ArrayRef<const Expr*> StopAt) {
20925 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20926}
20927
20928/// Emit a diagnostic when statements are reachable.
20930 const PartialDiagnostic &PD) {
20931 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
20932 // The initializer of a constexpr variable or of the first declaration of a
20933 // static data member is not syntactically a constant evaluated constant,
20934 // but nonetheless is always required to be a constant expression, so we
20935 // can skip diagnosing.
20936 if (Decl &&
20937 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
20938 Decl->isFirstDecl() && !Decl->isInline())))
20939 return false;
20940
20941 if (Stmts.empty()) {
20942 Diag(Loc, PD);
20943 return true;
20944 }
20945
20946 if (getCurFunction()) {
20947 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20948 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20949 return true;
20950 }
20951
20952 // For non-constexpr file-scope variables with reachability context (non-empty
20953 // Stmts), build a CFG for the initializer and check whether the context in
20954 // question is reachable.
20955 if (Decl && Decl->isFileVarDecl()) {
20956 AnalysisWarnings.registerVarDeclWarning(
20957 Decl, sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20958 return true;
20959 }
20960
20961 Diag(Loc, PD);
20962 return true;
20963}
20964
20965/// Emit a diagnostic that describes an effect on the run-time behavior
20966/// of the program being compiled.
20967///
20968/// This routine emits the given diagnostic when the code currently being
20969/// type-checked is "potentially evaluated", meaning that there is a
20970/// possibility that the code will actually be executable. Code in sizeof()
20971/// expressions, code used only during overload resolution, etc., are not
20972/// potentially evaluated. This routine will suppress such diagnostics or,
20973/// in the absolutely nutty case of potentially potentially evaluated
20974/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20975/// later.
20976///
20977/// This routine should be used for all diagnostics that describe the run-time
20978/// behavior of a program, such as passing a non-POD value through an ellipsis.
20979/// Failure to do so will likely result in spurious diagnostics or failures
20980/// during overload resolution or within sizeof/alignof/typeof/typeid.
20982 const PartialDiagnostic &PD) {
20983
20984 if (ExprEvalContexts.back().isDiscardedStatementContext())
20985 return false;
20986
20987 switch (ExprEvalContexts.back().Context) {
20992 // The argument will never be evaluated, so don't complain.
20993 break;
20994
20997 // Relevant diagnostics should be produced by constant evaluation.
20998 break;
20999
21002 return DiagIfReachable(Loc, Stmts, PD);
21003 }
21004
21005 return false;
21006}
21007
21009 const PartialDiagnostic &PD) {
21010 return DiagRuntimeBehavior(
21011 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21012 PD);
21013}
21014
21016 CallExpr *CE, FunctionDecl *FD) {
21017 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21018 return false;
21019
21020 // If we're inside a decltype's expression, don't check for a valid return
21021 // type or construct temporaries until we know whether this is the last call.
21022 if (ExprEvalContexts.back().ExprContext ==
21024 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
21025 return false;
21026 }
21027
21028 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21029 FunctionDecl *FD;
21030 CallExpr *CE;
21031
21032 public:
21033 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21034 : FD(FD), CE(CE) { }
21035
21036 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21037 if (!FD) {
21038 S.Diag(Loc, diag::err_call_incomplete_return)
21039 << T << CE->getSourceRange();
21040 return;
21041 }
21042
21043 S.Diag(Loc, diag::err_call_function_incomplete_return)
21044 << CE->getSourceRange() << FD << T;
21045 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
21046 << FD->getDeclName();
21047 }
21048 } Diagnoser(FD, CE);
21049
21050 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
21051 return true;
21052
21053 return false;
21054}
21055
21056// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21057// will prevent this condition from triggering, which is what we want.
21059 SourceLocation Loc;
21060
21061 unsigned diagnostic = diag::warn_condition_is_assignment;
21062 bool IsOrAssign = false;
21063
21064 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
21065 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21066 return;
21067
21068 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21069
21070 // Greylist some idioms by putting them into a warning subcategory.
21071 if (ObjCMessageExpr *ME
21072 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
21073 Selector Sel = ME->getSelector();
21074
21075 // self = [<foo> init...]
21076 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21077 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21078
21079 // <foo> = [<bar> nextObject]
21080 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
21081 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21082 }
21083
21084 Loc = Op->getOperatorLoc();
21085 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
21086 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21087 return;
21088
21089 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21090 Loc = Op->getOperatorLoc();
21091 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
21092 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
21093 else {
21094 // Not an assignment.
21095 return;
21096 }
21097
21098 Diag(Loc, diagnostic) << E->getSourceRange();
21099
21102 Diag(Loc, diag::note_condition_assign_silence)
21104 << FixItHint::CreateInsertion(Close, ")");
21105
21106 if (IsOrAssign)
21107 Diag(Loc, diag::note_condition_or_assign_to_comparison)
21108 << FixItHint::CreateReplacement(Loc, "!=");
21109 else
21110 Diag(Loc, diag::note_condition_assign_to_comparison)
21111 << FixItHint::CreateReplacement(Loc, "==");
21112}
21113
21115 // Don't warn if the parens came from a macro.
21116 SourceLocation parenLoc = ParenE->getBeginLoc();
21117 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21118 return;
21119 // Don't warn for dependent expressions.
21120 if (ParenE->isTypeDependent())
21121 return;
21122
21123 Expr *E = ParenE->IgnoreParens();
21124 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21125 return;
21126
21127 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
21128 if (opE->getOpcode() == BO_EQ &&
21129 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
21130 == Expr::MLV_Valid) {
21131 SourceLocation Loc = opE->getOperatorLoc();
21132
21133 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
21134 SourceRange ParenERange = ParenE->getSourceRange();
21135 Diag(Loc, diag::note_equality_comparison_silence)
21136 << FixItHint::CreateRemoval(ParenERange.getBegin())
21137 << FixItHint::CreateRemoval(ParenERange.getEnd());
21138 Diag(Loc, diag::note_equality_comparison_to_assign)
21139 << FixItHint::CreateReplacement(Loc, "=");
21140 }
21141}
21142
21144 bool IsConstexpr) {
21146 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
21148
21149 ExprResult result = CheckPlaceholderExpr(E);
21150 if (result.isInvalid()) return ExprError();
21151 E = result.get();
21152
21153 if (!E->isTypeDependent()) {
21154 if (getLangOpts().CPlusPlus)
21155 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
21156
21158 if (ERes.isInvalid())
21159 return ExprError();
21160 E = ERes.get();
21161
21162 QualType T = E->getType();
21163 if (!T->isScalarType()) { // C99 6.8.4.1p1
21164 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
21165 << T << E->getSourceRange();
21166 return ExprError();
21167 }
21168 CheckBoolLikeConversion(E, Loc);
21169 }
21170
21171 return E;
21172}
21173
21175 Expr *SubExpr, ConditionKind CK,
21176 bool MissingOK) {
21177 // MissingOK indicates whether having no condition expression is valid
21178 // (for loop) or invalid (e.g. while loop).
21179 if (!SubExpr)
21180 return MissingOK ? ConditionResult() : ConditionError();
21181
21183 switch (CK) {
21185 Cond = CheckBooleanCondition(Loc, SubExpr);
21186 break;
21187
21189 // Note: this might produce a FullExpr
21190 Cond = CheckBooleanCondition(Loc, SubExpr, true);
21191 break;
21192
21194 Cond = CheckSwitchCondition(Loc, SubExpr);
21195 break;
21196 }
21197 if (Cond.isInvalid()) {
21198 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
21199 {SubExpr}, PreferredConditionType(CK));
21200 if (!Cond.get())
21201 return ConditionError();
21202 } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))
21203 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
21204
21205 if (!Cond.isUsable())
21206 return ConditionError();
21207
21208 return ConditionResult(*this, nullptr, Cond,
21210}
21211
21212namespace {
21213 /// A visitor for rebuilding a call to an __unknown_any expression
21214 /// to have an appropriate type.
21215 struct RebuildUnknownAnyFunction
21216 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21217
21218 Sema &S;
21219
21220 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21221
21222 ExprResult VisitStmt(Stmt *S) {
21223 llvm_unreachable("unexpected statement!");
21224 }
21225
21226 ExprResult VisitExpr(Expr *E) {
21227 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21228 << E->getSourceRange();
21229 return ExprError();
21230 }
21231
21232 /// Rebuild an expression which simply semantically wraps another
21233 /// expression which it shares the type and value kind of.
21234 template <class T> ExprResult rebuildSugarExpr(T *E) {
21235 ExprResult SubResult = Visit(E->getSubExpr());
21236 if (SubResult.isInvalid()) return ExprError();
21237
21238 Expr *SubExpr = SubResult.get();
21239 E->setSubExpr(SubExpr);
21240 E->setType(SubExpr->getType());
21241 E->setValueKind(SubExpr->getValueKind());
21242 assert(E->getObjectKind() == OK_Ordinary);
21243 return E;
21244 }
21245
21246 ExprResult VisitParenExpr(ParenExpr *E) {
21247 return rebuildSugarExpr(E);
21248 }
21249
21250 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21251 return rebuildSugarExpr(E);
21252 }
21253
21254 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21255 ExprResult SubResult = Visit(E->getSubExpr());
21256 if (SubResult.isInvalid()) return ExprError();
21257
21258 Expr *SubExpr = SubResult.get();
21259 E->setSubExpr(SubExpr);
21260 E->setType(S.Context.getPointerType(SubExpr->getType()));
21261 assert(E->isPRValue());
21262 assert(E->getObjectKind() == OK_Ordinary);
21263 return E;
21264 }
21265
21266 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21267 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21268
21269 E->setType(VD->getType());
21270
21271 assert(E->isPRValue());
21272 if (S.getLangOpts().CPlusPlus &&
21273 !(isa<CXXMethodDecl>(VD) &&
21274 cast<CXXMethodDecl>(VD)->isInstance()))
21276
21277 return E;
21278 }
21279
21280 ExprResult VisitMemberExpr(MemberExpr *E) {
21281 return resolveDecl(E, E->getMemberDecl());
21282 }
21283
21284 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21285 return resolveDecl(E, E->getDecl());
21286 }
21287 };
21288}
21289
21290/// Given a function expression of unknown-any type, try to rebuild it
21291/// to have a function type.
21293 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21294 if (Result.isInvalid()) return ExprError();
21295 return S.DefaultFunctionArrayConversion(Result.get());
21296}
21297
21298namespace {
21299 /// A visitor for rebuilding an expression of type __unknown_anytype
21300 /// into one which resolves the type directly on the referring
21301 /// expression. Strict preservation of the original source
21302 /// structure is not a goal.
21303 struct RebuildUnknownAnyExpr
21304 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21305
21306 Sema &S;
21307
21308 /// The current destination type.
21309 QualType DestType;
21310
21311 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21312 : S(S), DestType(CastType) {}
21313
21314 ExprResult VisitStmt(Stmt *S) {
21315 llvm_unreachable("unexpected statement!");
21316 }
21317
21318 ExprResult VisitExpr(Expr *E) {
21319 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21320 << E->getSourceRange();
21321 return ExprError();
21322 }
21323
21324 ExprResult VisitCallExpr(CallExpr *E);
21325 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21326
21327 /// Rebuild an expression which simply semantically wraps another
21328 /// expression which it shares the type and value kind of.
21329 template <class T> ExprResult rebuildSugarExpr(T *E) {
21330 ExprResult SubResult = Visit(E->getSubExpr());
21331 if (SubResult.isInvalid()) return ExprError();
21332 Expr *SubExpr = SubResult.get();
21333 E->setSubExpr(SubExpr);
21334 E->setType(SubExpr->getType());
21335 E->setValueKind(SubExpr->getValueKind());
21336 assert(E->getObjectKind() == OK_Ordinary);
21337 return E;
21338 }
21339
21340 ExprResult VisitParenExpr(ParenExpr *E) {
21341 return rebuildSugarExpr(E);
21342 }
21343
21344 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21345 return rebuildSugarExpr(E);
21346 }
21347
21348 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21349 const PointerType *Ptr = DestType->getAs<PointerType>();
21350 if (!Ptr) {
21351 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21352 << E->getSourceRange();
21353 return ExprError();
21354 }
21355
21356 if (isa<CallExpr>(E->getSubExpr())) {
21357 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21358 << E->getSourceRange();
21359 return ExprError();
21360 }
21361
21362 assert(E->isPRValue());
21363 assert(E->getObjectKind() == OK_Ordinary);
21364 E->setType(DestType);
21365
21366 // Build the sub-expression as if it were an object of the pointee type.
21367 DestType = Ptr->getPointeeType();
21368 ExprResult SubResult = Visit(E->getSubExpr());
21369 if (SubResult.isInvalid()) return ExprError();
21370 E->setSubExpr(SubResult.get());
21371 return E;
21372 }
21373
21374 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21375
21376 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21377
21378 ExprResult VisitMemberExpr(MemberExpr *E) {
21379 return resolveDecl(E, E->getMemberDecl());
21380 }
21381
21382 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21383 return resolveDecl(E, E->getDecl());
21384 }
21385 };
21386}
21387
21388/// Rebuilds a call expression which yielded __unknown_anytype.
21389ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21390 Expr *CalleeExpr = E->getCallee();
21391
21392 enum FnKind {
21393 FK_MemberFunction,
21394 FK_FunctionPointer,
21395 FK_BlockPointer
21396 };
21397
21398 FnKind Kind;
21399 QualType CalleeType = CalleeExpr->getType();
21400 if (CalleeType == S.Context.BoundMemberTy) {
21402 Kind = FK_MemberFunction;
21403 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21404 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21405 CalleeType = Ptr->getPointeeType();
21406 Kind = FK_FunctionPointer;
21407 } else {
21408 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21409 Kind = FK_BlockPointer;
21410 }
21411 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21412
21413 // Verify that this is a legal result type of a function.
21414 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21415 DestType->isFunctionType()) {
21416 unsigned diagID = diag::err_func_returning_array_function;
21417 if (Kind == FK_BlockPointer)
21418 diagID = diag::err_block_returning_array_function;
21419
21420 S.Diag(E->getExprLoc(), diagID)
21421 << DestType->isFunctionType() << DestType;
21422 return ExprError();
21423 }
21424
21425 // Otherwise, go ahead and set DestType as the call's result.
21426 E->setType(DestType.getNonLValueExprType(S.Context));
21428 assert(E->getObjectKind() == OK_Ordinary);
21429
21430 // Rebuild the function type, replacing the result type with DestType.
21431 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21432 if (Proto) {
21433 // __unknown_anytype(...) is a special case used by the debugger when
21434 // it has no idea what a function's signature is.
21435 //
21436 // We want to build this call essentially under the K&R
21437 // unprototyped rules, but making a FunctionNoProtoType in C++
21438 // would foul up all sorts of assumptions. However, we cannot
21439 // simply pass all arguments as variadic arguments, nor can we
21440 // portably just call the function under a non-variadic type; see
21441 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21442 // However, it turns out that in practice it is generally safe to
21443 // call a function declared as "A foo(B,C,D);" under the prototype
21444 // "A foo(B,C,D,...);". The only known exception is with the
21445 // Windows ABI, where any variadic function is implicitly cdecl
21446 // regardless of its normal CC. Therefore we change the parameter
21447 // types to match the types of the arguments.
21448 //
21449 // This is a hack, but it is far superior to moving the
21450 // corresponding target-specific code from IR-gen to Sema/AST.
21451
21452 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21453 SmallVector<QualType, 8> ArgTypes;
21454 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21455 ArgTypes.reserve(E->getNumArgs());
21456 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21457 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21458 }
21459 ParamTypes = ArgTypes;
21460 }
21461 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21462 Proto->getExtProtoInfo());
21463 } else {
21464 DestType = S.Context.getFunctionNoProtoType(DestType,
21465 FnType->getExtInfo());
21466 }
21467
21468 // Rebuild the appropriate pointer-to-function type.
21469 switch (Kind) {
21470 case FK_MemberFunction:
21471 // Nothing to do.
21472 break;
21473
21474 case FK_FunctionPointer:
21475 DestType = S.Context.getPointerType(DestType);
21476 break;
21477
21478 case FK_BlockPointer:
21479 DestType = S.Context.getBlockPointerType(DestType);
21480 break;
21481 }
21482
21483 // Finally, we can recurse.
21484 ExprResult CalleeResult = Visit(CalleeExpr);
21485 if (!CalleeResult.isUsable()) return ExprError();
21486 E->setCallee(CalleeResult.get());
21487
21488 // Bind a temporary if necessary.
21489 return S.MaybeBindToTemporary(E);
21490}
21491
21492ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21493 // Verify that this is a legal result type of a call.
21494 if (DestType->isArrayType() || DestType->isFunctionType()) {
21495 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21496 << DestType->isFunctionType() << DestType;
21497 return ExprError();
21498 }
21499
21500 // Rewrite the method result type if available.
21501 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21502 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21503 Method->setReturnType(DestType);
21504 }
21505
21506 // Change the type of the message.
21507 E->setType(DestType.getNonReferenceType());
21509
21510 return S.MaybeBindToTemporary(E);
21511}
21512
21513ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21514 // The only case we should ever see here is a function-to-pointer decay.
21515 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21516 assert(E->isPRValue());
21517 assert(E->getObjectKind() == OK_Ordinary);
21518
21519 E->setType(DestType);
21520
21521 // Rebuild the sub-expression as the pointee (function) type.
21522 DestType = DestType->castAs<PointerType>()->getPointeeType();
21523
21524 ExprResult Result = Visit(E->getSubExpr());
21525 if (!Result.isUsable()) return ExprError();
21526
21527 E->setSubExpr(Result.get());
21528 return E;
21529 } else if (E->getCastKind() == CK_LValueToRValue) {
21530 assert(E->isPRValue());
21531 assert(E->getObjectKind() == OK_Ordinary);
21532
21533 assert(isa<BlockPointerType>(E->getType()));
21534
21535 E->setType(DestType);
21536
21537 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21538 DestType = S.Context.getLValueReferenceType(DestType);
21539
21540 ExprResult Result = Visit(E->getSubExpr());
21541 if (!Result.isUsable()) return ExprError();
21542
21543 E->setSubExpr(Result.get());
21544 return E;
21545 } else {
21546 llvm_unreachable("Unhandled cast type!");
21547 }
21548}
21549
21550ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21551 ExprValueKind ValueKind = VK_LValue;
21552 QualType Type = DestType;
21553
21554 // We know how to make this work for certain kinds of decls:
21555
21556 // - functions
21557 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21558 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21559 DestType = Ptr->getPointeeType();
21560 ExprResult Result = resolveDecl(E, VD);
21561 if (Result.isInvalid()) return ExprError();
21562 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21563 VK_PRValue);
21564 }
21565
21566 if (!Type->isFunctionType()) {
21567 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21568 << VD << E->getSourceRange();
21569 return ExprError();
21570 }
21571 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21572 // We must match the FunctionDecl's type to the hack introduced in
21573 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21574 // type. See the lengthy commentary in that routine.
21575 QualType FDT = FD->getType();
21576 const FunctionType *FnType = FDT->castAs<FunctionType>();
21577 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21578 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21579 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21580 SourceLocation Loc = FD->getLocation();
21581 FunctionDecl *NewFD = FunctionDecl::Create(
21582 S.Context, FD->getDeclContext(), Loc, Loc,
21583 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21585 false /*isInlineSpecified*/, FD->hasPrototype(),
21586 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21587
21588 if (FD->getQualifier())
21589 NewFD->setQualifierInfo(FD->getQualifierLoc());
21590
21591 SmallVector<ParmVarDecl*, 16> Params;
21592 for (const auto &AI : FT->param_types()) {
21593 ParmVarDecl *Param =
21594 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21595 Param->setScopeInfo(0, Params.size());
21596 Params.push_back(Param);
21597 }
21598 NewFD->setParams(Params);
21599 DRE->setDecl(NewFD);
21600 VD = DRE->getDecl();
21601 }
21602 }
21603
21604 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21605 if (MD->isInstance()) {
21606 ValueKind = VK_PRValue;
21608 }
21609
21610 // Function references aren't l-values in C.
21611 if (!S.getLangOpts().CPlusPlus)
21612 ValueKind = VK_PRValue;
21613
21614 // - variables
21615 } else if (isa<VarDecl>(VD)) {
21616 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21617 Type = RefTy->getPointeeType();
21618 } else if (Type->isFunctionType()) {
21619 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21620 << VD << E->getSourceRange();
21621 return ExprError();
21622 }
21623
21624 // - nothing else
21625 } else {
21626 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21627 << VD << E->getSourceRange();
21628 return ExprError();
21629 }
21630
21631 // Modifying the declaration like this is friendly to IR-gen but
21632 // also really dangerous.
21633 VD->setType(DestType);
21634 E->setType(Type);
21635 E->setValueKind(ValueKind);
21636 return E;
21637}
21638
21641 ExprValueKind &VK, CXXCastPath &Path) {
21642 // The type we're casting to must be either void or complete.
21643 if (!CastType->isVoidType() &&
21645 diag::err_typecheck_cast_to_incomplete))
21646 return ExprError();
21647
21648 // Rewrite the casted expression from scratch.
21649 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21650 if (!result.isUsable()) return ExprError();
21651
21652 CastExpr = result.get();
21654 CastKind = CK_NoOp;
21655
21656 return CastExpr;
21657}
21658
21660 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21661}
21662
21664 Expr *arg, QualType &paramType) {
21665 // If the syntactic form of the argument is not an explicit cast of
21666 // any sort, just do default argument promotion.
21667 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21668 if (!castArg) {
21670 if (result.isInvalid()) return ExprError();
21671 paramType = result.get()->getType();
21672 return result;
21673 }
21674
21675 // Otherwise, use the type that was written in the explicit cast.
21676 assert(!arg->hasPlaceholderType());
21677 paramType = castArg->getTypeAsWritten();
21678
21679 // Copy-initialize a parameter of that type.
21680 InitializedEntity entity =
21682 /*consumed*/ false);
21683 return PerformCopyInitialization(entity, callLoc, arg);
21684}
21685
21687 Expr *orig = E;
21688 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21689 while (true) {
21690 E = E->IgnoreParenImpCasts();
21691 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21692 E = call->getCallee();
21693 diagID = diag::err_uncasted_call_of_unknown_any;
21694 } else {
21695 break;
21696 }
21697 }
21698
21699 SourceLocation loc;
21700 NamedDecl *d;
21701 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21702 loc = ref->getLocation();
21703 d = ref->getDecl();
21704 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21705 loc = mem->getMemberLoc();
21706 d = mem->getMemberDecl();
21707 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21708 diagID = diag::err_uncasted_call_of_unknown_any;
21709 loc = msg->getSelectorStartLoc();
21710 d = msg->getMethodDecl();
21711 if (!d) {
21712 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21713 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21714 << orig->getSourceRange();
21715 return ExprError();
21716 }
21717 } else {
21718 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21719 << E->getSourceRange();
21720 return ExprError();
21721 }
21722
21723 S.Diag(loc, diagID) << d << orig->getSourceRange();
21724
21725 // Never recoverable.
21726 return ExprError();
21727}
21728
21730 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21731 if (!placeholderType) return E;
21732
21733 switch (placeholderType->getKind()) {
21734 case BuiltinType::UnresolvedTemplate: {
21735 auto *ULE = cast<UnresolvedLookupExpr>(E->IgnoreParens());
21736 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21737 // There's only one FoundDecl for UnresolvedTemplate type. See
21738 // BuildTemplateIdExpr.
21739 NamedDecl *Temp = *ULE->decls_begin();
21740 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
21741
21742 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21743 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21744 // as it models only the unqualified-id case, where this case can clearly be
21745 // qualified. Thus we can't just qualify an assumed template.
21746 TemplateName TN;
21747 if (auto *TD = dyn_cast<TemplateDecl>(Temp))
21748 TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),
21749 TemplateName(TD));
21750 else
21751 TN = Context.getAssumedTemplateName(NameInfo.getName());
21752
21753 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21754 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21755 Diag(Temp->getLocation(), diag::note_referenced_type_template)
21756 << IsTypeAliasTemplateDecl;
21757
21758 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21759 bool HasAnyDependentTA = false;
21760 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21761 HasAnyDependentTA |= Arg.getArgument().isDependent();
21762 TAL.addArgument(Arg);
21763 }
21764
21765 QualType TST;
21766 {
21767 SFINAETrap Trap(*this);
21768 TST = CheckTemplateIdType(
21769 ElaboratedTypeKeyword::None, TN, NameInfo.getBeginLoc(), TAL,
21770 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21771 }
21772 if (TST.isNull())
21773 TST = Context.getTemplateSpecializationType(
21774 ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),
21775 /*CanonicalArgs=*/{},
21776 HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21777 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},
21778 TST);
21779 }
21780
21781 // Overloaded expressions.
21782 case BuiltinType::Overload: {
21783 // Try to resolve a single function template specialization.
21784 // This is obligatory.
21785 ExprResult Result = E;
21787 return Result;
21788
21789 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21790 // leaves Result unchanged on failure.
21791 Result = E;
21793 return Result;
21794
21795 // If that failed, try to recover with a call.
21796 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21797 /*complain*/ true);
21798 return Result;
21799 }
21800
21801 // Bound member functions.
21802 case BuiltinType::BoundMember: {
21803 ExprResult result = E;
21804 const Expr *BME = E->IgnoreParens();
21805 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21806 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21808 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21809 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21810 if (ME->getMemberNameInfo().getName().getNameKind() ==
21812 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21813 }
21814 tryToRecoverWithCall(result, PD,
21815 /*complain*/ true);
21816 return result;
21817 }
21818
21819 // ARC unbridged casts.
21820 case BuiltinType::ARCUnbridgedCast: {
21821 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
21822 ObjC().diagnoseARCUnbridgedCast(realCast);
21823 return realCast;
21824 }
21825
21826 // Expressions of unknown type.
21827 case BuiltinType::UnknownAny:
21828 return diagnoseUnknownAnyExpr(*this, E);
21829
21830 // Pseudo-objects.
21831 case BuiltinType::PseudoObject:
21832 return PseudoObject().checkRValue(E);
21833
21834 case BuiltinType::BuiltinFn: {
21835 // Accept __noop without parens by implicitly converting it to a call expr.
21836 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21837 if (DRE) {
21838 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21839 unsigned BuiltinID = FD->getBuiltinID();
21840 if (BuiltinID == Builtin::BI__noop) {
21841 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21842 CK_BuiltinFnToFnPtr)
21843 .get();
21844 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21847 }
21848
21849 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21850 // Any use of these other than a direct call is ill-formed as of C++20,
21851 // because they are not addressable functions. In earlier language
21852 // modes, warn and force an instantiation of the real body.
21853 Diag(E->getBeginLoc(),
21855 ? diag::err_use_of_unaddressable_function
21856 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21857 if (FD->isImplicitlyInstantiable()) {
21858 // Require a definition here because a normal attempt at
21859 // instantiation for a builtin will be ignored, and we won't try
21860 // again later. We assume that the definition of the template
21861 // precedes this use.
21863 /*Recursive=*/false,
21864 /*DefinitionRequired=*/true,
21865 /*AtEndOfTU=*/false);
21866 }
21867 // Produce a properly-typed reference to the function.
21868 CXXScopeSpec SS;
21869 SS.Adopt(DRE->getQualifierLoc());
21870 TemplateArgumentListInfo TemplateArgs;
21871 DRE->copyTemplateArgumentsInto(TemplateArgs);
21872 return BuildDeclRefExpr(
21873 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21874 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21875 DRE->getTemplateKeywordLoc(),
21876 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21877 }
21878 }
21879
21880 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21881 return ExprError();
21882 }
21883
21884 case BuiltinType::IncompleteMatrixIdx: {
21885 auto *MS = cast<MatrixSubscriptExpr>(E->IgnoreParens());
21886 // At this point, we know there was no second [] to complete the operator.
21887 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
21888 if (getLangOpts().HLSL) {
21890 MS->getBase(), MS->getRowIdx(), E->getExprLoc());
21891 }
21892 Diag(MS->getRowIdx()->getBeginLoc(), diag::err_matrix_incomplete_index);
21893 return ExprError();
21894 }
21895
21896 // Expressions of unknown type.
21897 case BuiltinType::ArraySection:
21898 // If we've already diagnosed something on the array section type, we
21899 // shouldn't need to do any further diagnostic here.
21900 if (!E->containsErrors())
21901 Diag(E->getBeginLoc(), diag::err_array_section_use)
21902 << cast<ArraySectionExpr>(E->IgnoreParens())->isOMPArraySection();
21903 return ExprError();
21904
21905 // Expressions of unknown type.
21906 case BuiltinType::OMPArrayShaping:
21907 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21908
21909 case BuiltinType::OMPIterator:
21910 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21911
21912 // Everything else should be impossible.
21913#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21914 case BuiltinType::Id:
21915#include "clang/Basic/OpenCLImageTypes.def"
21916#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21917 case BuiltinType::Id:
21918#include "clang/Basic/OpenCLExtensionTypes.def"
21919#define SVE_TYPE(Name, Id, SingletonId) \
21920 case BuiltinType::Id:
21921#include "clang/Basic/AArch64ACLETypes.def"
21922#define PPC_VECTOR_TYPE(Name, Id, Size) \
21923 case BuiltinType::Id:
21924#include "clang/Basic/PPCTypes.def"
21925#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21926#include "clang/Basic/RISCVVTypes.def"
21927#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21928#include "clang/Basic/WebAssemblyReferenceTypes.def"
21929#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
21930#include "clang/Basic/AMDGPUTypes.def"
21931#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21932#include "clang/Basic/HLSLIntangibleTypes.def"
21933#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21934#define PLACEHOLDER_TYPE(Id, SingletonId)
21935#include "clang/AST/BuiltinTypes.def"
21936 break;
21937 }
21938
21939 llvm_unreachable("invalid placeholder type!");
21940}
21941
21943 if (E->isTypeDependent())
21944 return true;
21946 return E->getType()->isIntegralOrEnumerationType();
21947 return false;
21948}
21949
21951 ArrayRef<Expr *> SubExprs, QualType T) {
21952 if (!Context.getLangOpts().RecoveryAST)
21953 return ExprError();
21954
21955 if (isSFINAEContext())
21956 return ExprError();
21957
21958 if (T.isNull() || T->isUndeducedType() ||
21959 !Context.getLangOpts().RecoveryASTType)
21960 // We don't know the concrete type, fallback to dependent type.
21961 T = Context.DependentTy;
21962
21963 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21964}
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:2703
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 QualType getUnderlyingType(const SubRegion *R)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to 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 bool areTypesCompatibleForGeneric(ASTContext &Ctx, QualType T, QualType U)
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
static bool MayBeFunctionType(const ASTContext &Context, const Expr *E)
static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S)
Convert vector E to a vector with the same number of elements but different element type.
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, const Expr **RHSExprs)
IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary expression, either using a built-i...
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, BinaryOperatorKind Opc, QualType ResultTy, ExprValueKind VK, ExprObjectKind OK, bool IsCompAssign, SourceLocation OpLoc, FPOptionsOverride FPFeatures)
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
@ ConstUnknown
@ ConstVariable
@ NestedConstMember
@ ConstMember
@ ConstFunction
static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult, QualType UnionType, FieldDecl *Field)
Constructs a transparent union from an expression that is used to initialize the transparent union.
static QualType OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType CondTy, SourceLocation QuestionLoc)
Convert scalar operands to a vector that matches the condition in length.
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS, Expr *RHS, SourceLocation Loc, ArithConvKind ACK)
static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *SubExpr)
Look for bitwise op in the left or right hand of a bitwise op with lower precedence and emit a diagno...
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation OpLoc, bool IsInc, bool IsPrefix)
CheckIncrementDecrementOperand - unlike most "Check" methods, this routine doesn't need to call Usual...
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, SourceLocation QuestionLoc)
Return false if the vector condition type and the vector result type are compatible.
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, const Expr *E)
Check whether E is a pointer from a decayed array type (the decayed pointer type is equal to T) and e...
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition SemaExpr.cpp:148
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:164
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:561
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
static OdrUseContext isOdrUseContext(Sema &SemaRef)
Are we within a context in which references to resolved functions or to variables result in odr-use?
static void DiagnoseConstAssignment(Sema &S, const Expr *E, SourceLocation Loc)
Emit the "read-only variable not assignable" error and print notes to give more information about why...
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
static void CheckSufficientAllocSize(Sema &S, QualType DestType, const Expr *E)
Check that a call to alloc_size function specifies sufficient space for the destination type.
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
static QualType handleOverflowBehaviorTypeConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, unsigned Offset)
getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the location of the token and the off...
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
OriginalExprKind
@ OEK_Variable
@ OEK_LValue
@ OEK_Member
static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S, bool Invalid)
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Return the resulting type when a vector is shifted by a scalar or vector shift amount.
static FieldDecl * FindFieldDeclInstantiationPattern(const ASTContext &Ctx, FieldDecl *Field)
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
static bool IsReadonlyMessage(Expr *E, Sema &S)
static std::optional< bool > isTautologicalBoundsCheck(Sema &S, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opc)
Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a pointer and size is an unsigne...
static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, ValueDecl *Var)
Create up to 4 fix-its for explicit reference and value capture of Var or default capture.
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the captured region.
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, Expr *PointerExpr, SourceLocation Loc, bool IsIntFirstExpr)
Return false if the first expression is not an integer and the second expression is not a pointer,...
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
static bool IsArithmeticOp(BinaryOperatorKind Opc)
static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr, ExprResult &ComplexExpr, QualType IntTy, QualType ComplexTy, bool SkipCast)
Convert complex integers to complex floats and real integers to real floats as required for complex a...
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, SourceLocation OpLoc)
Check if a bitwise-& is performed on an Objective-C pointer.
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition SemaExpr.cpp:586
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:110
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:508
bool hasValue() const
Definition APValue.h:483
bool isInt() const
Definition APValue.h:485
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:988
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:226
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:801
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:797
const LangOptions & getLangOpts() const
Definition ASTContext.h:951
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition ASTContext.h:919
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:916
QualType getOverflowBehaviorType(const OverflowBehaviorAttr *Attr, QualType Wrapped) const
std::optional< CharUnits > getTypeSizeInCharsIfKnown(QualType Ty) const
void getFunctionFeatureMap(llvm::StringMap< bool > &FeatureMap, const FunctionDecl *) const
QualType getCorrespondingUnsignedType(QualType T) const
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
unsigned getTargetAddressSpace(LangAS AS) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
CanQualType HalfTy
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false) const
uint64_t getCharWidth() const
Return the size of the character type, in bits.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition Expr.h:4553
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2724
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:2779
Wrapper for source info for arrays.
Definition TypeLoc.h:1777
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3730
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3744
QualType getElementType() const
Definition TypeBase.h:3742
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition Expr.h:6732
Attr - This represents one attribute.
Definition Attr.h:46
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition Expr.h:4456
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4041
Expr * getLHS() const
Definition Expr.h:4091
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4135
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2180
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4141
StringRef getOpcodeStr() const
Definition Expr.h:4107
bool isRelationalOp() const
Definition Expr.h:4136
SourceLocation getOperatorLoc() const
Definition Expr.h:4083
bool isMultiplicativeOp() const
Definition Expr.h:4126
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2133
bool isShiftOp() const
Definition Expr.h:4130
Expr * getRHS() const
Definition Expr.h:4093
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:5076
bool isBitwiseOp() const
Definition Expr.h:4133
bool isAdditiveOp() const
Definition Expr.h:4128
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4177
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4182
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:2205
Opcode getOpcode() const
Definition Expr.h:4086
bool isAssignmentOp() const
Definition Expr.h:4180
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2142
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4138
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4132
BinaryOperatorKind Opcode
Definition Expr.h:4046
A binding in a decomposition declaration.
Definition DeclCXX.h:4188
A class which contains all the information about a particular captured value.
Definition Decl.h:4680
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4674
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.cpp:5447
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition Decl.h:4756
void setBlockMissingReturnType(bool val=true)
Definition Decl.h:4813
void setIsVariadic(bool value)
Definition Decl.h:4750
SourceLocation getCaretLocation() const
Definition Decl.h:4747
void setBody(CompoundStmt *B)
Definition Decl.h:4754
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:4760
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition Decl.cpp:5458
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5646
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6671
Pointer to a block type.
Definition TypeBase.h:3550
This class is used for builtin types like 'int'.
Definition TypeBase.h:3172
bool isSVEBool() const
Definition TypeBase.h:3249
Kind getKind() const
Definition TypeBase.h:3220
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:1974
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:2611
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2946
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition DeclCXX.cpp:3255
Represents a C++ base or member initializer.
Definition DeclCXX.h:2376
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:2876
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2136
bool isVirtual() const
Definition DeclCXX.h:2191
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2262
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:2526
A call to an overloaded operator written using operator syntax.
Definition ExprCXX.h:85
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition ExprCXX.h:153
SourceRange getSourceRange() const
Definition ExprCXX.h:165
static CXXParenListInitExpr * Create(ASTContext &C, ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Definition ExprCXX.cpp:2005
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition ExprCXX.h:2746
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:603
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:2085
bool hasDefinition() const
Definition DeclCXX.h:561
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
static CXXReflectExpr * Create(ASTContext &C, SourceLocation OperatorLoc, TypeSourceInfo *TL)
Definition ExprCXX.cpp:1950
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition DeclSpec.h:181
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:186
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:80
SourceLocation getBeginLoc() const
Definition DeclSpec.h:84
bool isSet() const
Deprecated.
Definition DeclSpec.h:199
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:95
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:184
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:179
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:2946
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3150
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3163
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:1517
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3129
Expr * getCallee()
Definition Expr.h:3093
void computeDependence()
Compute and set dependence bits.
Definition Expr.h:3169
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3137
void setCallee(Expr *F)
Definition Expr.h:3095
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:3679
CastKind getCastKind() const
Definition Expr.h:3723
const char * getCastKindName() const
Definition Expr.h:3727
void setSubExpr(Expr *E)
Definition Expr.h:3731
Expr * getSubExpr()
Definition Expr.h:3729
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Represents a byte-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
unsigned getValue() const
Definition Expr.h:1632
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4851
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3283
QualType getElementType() const
Definition TypeBase.h:3293
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:5098
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3608
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1732
bool body_empty() const
Definition Stmt.h:1776
Stmt * body_back()
Definition Stmt.h:1800
ConditionalOperator - The ?
Definition Expr.h:4394
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3768
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3824
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3844
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1085
static ConstantResultStorageKind getStorageKind(const APValue &Value)
Definition Expr.cpp:302
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition Expr.cpp:378
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:1135
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:350
bool isImmediateInvocation() const
Definition Expr.h:1157
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4395
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4414
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4411
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
void setTypoName(const IdentifierInfo *II)
void setTypoNNS(NestedNameSpecifier NNS)
Wrapper for source info for pointers decayed from arrays and functions.
Definition TypeLoc.h:1474
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h: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:1273
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition Expr.h:1384
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition Expr.h:1428
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1374
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1477
void setDecl(ValueDecl *NewD)
Definition Expr.cpp:544
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition Expr.h:1432
DeclarationNameInfo getNameInfo() const
Definition Expr.h:1345
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition Expr.h:1400
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:488
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition Expr.h:1362
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1366
ValueDecl * getDecl()
Definition Expr.h:1341
SourceLocation getBeginLoc() const
Definition Expr.h:1352
SourceLocation getLocation() const
Definition Expr.h:1349
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 isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition DeclBase.h:1070
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:2012
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1921
DeclaratorContext getContext() const
Definition DeclSpec.h:2093
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2104
bool isInvalidType() const
Definition DeclSpec.h:2735
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2351
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:959
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:728
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
Represents a reference to emded data.
Definition Expr.h:5129
RAII object that enters a new expression evaluation context.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4186
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3931
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3958
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:300
@ LV_ClassTemporary
Definition Expr.h:299
@ LV_MemberFunction
Definition Expr.h:297
@ LV_IncompleteVoidType
Definition Expr.h:292
@ LV_Valid
Definition Expr.h:290
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3117
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:677
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition Expr.cpp:3046
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:3095
void setType(QualType t)
Definition Expr.h:145
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition Expr.h:241
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3090
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3078
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition Expr.cpp:3099
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:3086
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:3339
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:834
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:830
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:838
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3670
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:3070
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:805
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:814
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:817
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition Expr.h:820
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:807
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:4050
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition Expr.cpp:266
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition Expr.h:464
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
static bool isSameComparisonOperand(const Expr *E1, const Expr *E2)
Checks that the two Expr's will refer to the same value as a comparison operand.
Definition Expr.cpp:4302
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:467
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
isModifiableLvalueResult
Definition Expr.h:305
@ MLV_DuplicateVectorComponents
Definition Expr.h:309
@ MLV_LValueCast
Definition Expr.h:312
@ MLV_InvalidMessageExpression
Definition Expr.h:321
@ MLV_DuplicateMatrixComponents
Definition Expr.h:310
@ MLV_ConstQualifiedField
Definition Expr.h:315
@ MLV_InvalidExpression
Definition Expr.h:311
@ MLV_IncompleteType
Definition Expr.h:313
@ MLV_Valid
Definition Expr.h:306
@ MLV_ConstQualified
Definition Expr.h:314
@ MLV_NoSetterProperty
Definition Expr.h:318
@ MLV_ArrayTemporary
Definition Expr.h:323
@ MLV_SubObjCPropertySetting
Definition Expr.h:320
@ MLV_ConstAddrSpace
Definition Expr.h:316
@ MLV_MemberFunction
Definition Expr.h:319
@ MLV_NotObjectType
Definition Expr.h:307
@ MLV_ArrayType
Definition Expr.h:317
@ MLV_ClassTemporary
Definition Expr.h:322
@ MLV_IncompleteVoidType
Definition Expr.h:308
QualType getType() const
Definition Expr.h:144
bool isOrdinaryOrBitFieldObject() const
Definition Expr.h:458
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:437
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition Expr.cpp:137
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6609
ExtVectorType - Extended vector type.
Definition TypeBase.h:4275
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:997
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1076
const Expr * getSubExpr() const
Definition Expr.h:1065
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:3848
bool isImmediateFunction() const
Definition Decl.cpp:3341
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4025
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3763
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3866
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:3619
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isImmediateEscalating() const
Definition Decl.cpp:3312
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:4131
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:3200
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition Decl.cpp:4041
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:4842
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4871
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5315
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5819
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5622
bool isParamConsumed(unsigned I) const
Definition TypeBase.h:5833
unsigned getNumParams() const
Definition TypeBase.h:5593
QualType getParamType(unsigned i) const
Definition TypeBase.h:5595
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5719
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5604
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5600
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5755
Declaration of a template function.
unsigned getNumParams() const
Definition TypeLoc.h:1716
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1722
SourceLocation getLocalRangeEnd() const
Definition TypeLoc.h:1668
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1725
SourceLocation getLocalRangeBegin() const
Definition TypeLoc.h:1660
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4622
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4693
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4550
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4511
ExtInfo getExtInfo() const
Definition TypeBase.h:4867
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:4859
bool getCFIUncheckedCalleeAttr() const
Determine whether this is a function prototype that includes the cfi_unchecked_callee attribute.
Definition Type.cpp:3643
QualType getReturnType() const
Definition TypeBase.h:4851
bool getCmseNSCallAttr() const
Definition TypeBase.h:4865
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4879
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4926
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:4698
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:1734
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3856
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2073
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:622
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3467
Describes an C or C++ initializer list.
Definition Expr.h:5302
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:975
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:1969
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:1038
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:319
Represents the results of name lookup.
Definition Lookup.h:147
DeclClass * getAsSingle() const
Definition Lookup.h:558
A global _GUID constant.
Definition DeclCXX.h:4401
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...
MatrixSingleSubscriptExpr - Matrix single subscript expression for the MatrixType extension when you ...
Definition Expr.h:2798
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition Expr.h:2868
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4345
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4359
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3556
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3450
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:1750
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3585
Expr * getBase() const
Definition Expr.h:3444
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1794
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:7950
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition ExprObjC.h:1495
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:546
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprObjC.h:592
SourceLocation getLocation() const
Definition ExprObjC.h:589
SourceLocation getOpLoc() const
Definition ExprObjC.h:597
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:576
bool isArrow() const
Definition ExprObjC.h:584
SourceLocation getEndLoc() const LLVM_READONLY
Definition ExprObjC.h:595
const Expr * getBase() const
Definition ExprObjC.h:580
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:937
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1361
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:8006
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1853
qual_range quals() const
Definition TypeBase.h:8125
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:1653
Helper class for OffsetOfExpr.
Definition Expr.h:2424
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:1181
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3129
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3190
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2185
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2206
const Expr * getSubExpr() const
Definition Expr.h:2202
bool isProducedByFoldExpansion() const
Definition Expr.h:2227
Expr * getExpr(unsigned Init)
Definition Expr.h:6115
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:4948
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition Expr.h:6113
SourceLocation getLParenLoc() const
Definition Expr.h:6128
SourceLocation getRParenLoc() const
Definition Expr.h:6129
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:2958
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3336
QualType getPointeeType() const
Definition TypeBase.h:3346
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition Expr.cpp:633
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition Expr.cpp:673
bool isMacroDefined(StringRef Id)
IdentifierTable & getIdentifierTable()
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6803
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8472
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8477
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:3627
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:2968
bool isAddressSpaceOverlapping(QualType T, const ASTContext &Ctx) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition TypeBase.h:1422
QualType withConst() const
Definition TypeBase.h:1165
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1162
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:8388
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8514
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:8428
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:2746
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1444
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8573
QualType getCanonicalType() const
Definition TypeBase.h:8440
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8482
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition Type.cpp:2987
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1185
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C.
Definition TypeBase.h:8580
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8461
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1683
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1551
bool isCanonical() const
Definition TypeBase.h:8445
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1315
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1338
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2738
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:8553
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8420
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:4327
bool hasFlexibleArrayMember() const
Definition Decl.h:4360
field_iterator field_end() const
Definition Decl.h:4533
field_range fields() const
Definition Decl.h:4530
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition Expr.cpp:5434
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:3581
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
bool Contains(const Scope &rhs) const
Returns if rhs has a higher scope depth than this.
Definition Scope.h:637
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
bool checkSVETypeSupport(QualType Ty, SourceLocation Loc, const FunctionDecl *FD, const llvm::StringMap< bool > &FeatureMap)
Definition SemaARM.cpp:1852
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:812
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:212
bool CheckCall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition SemaCUDA.cpp:988
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition SemaCUDA.h:120
@ CVT_Both
Emitted on host side only.
Definition SemaCUDA.h:121
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)
void CheckDeviceUseOfDecl(NamedDecl *ND, SourceLocation Loc)
Issues a deferred diagnostic if use of the declaration designated by 'ND' is invalid in a device cont...
Definition SemaSYCL.cpp:224
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8502
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12520
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12564
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7771
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:868
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:8255
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13663
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1133
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:8305
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
bool isAlwaysConstantEvaluatedContext() const
Definition Sema.h:8223
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:949
bool isAttrContext() const
Definition Sema.h:7004
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:8298
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9385
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9424
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9393
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:415
ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx, SourceLocation RBLoc)
ExprResult ActOnConstantExpression(ExprResult Res)
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool areVectorTypesSameSize(QualType srcType, QualType destType)
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition Sema.h:1525
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:1243
SemaCUDA & CUDA()
Definition Sema.h:1465
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:7892
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7894
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7893
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:8243
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:8385
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1236
Preprocessor & getPreprocessor() const
Definition Sema.h:938
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:6982
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2332
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:8374
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition Sema.h:8286
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:6811
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:2069
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.
SemaSYCL & SYCL()
Definition Sema.h:1550
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:6994
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:1674
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:837
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:1300
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:8210
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
bool DiagIfReachable(SourceLocation Loc, ArrayRef< const Stmt * > Stmts, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the statements's reachability analysis.
bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E)
Perform Bounds Safety semantic checks for uses of invalid uses counted_by or counted_by_or_null point...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:225
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
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:1510
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:2842
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:758
bool isImmediateFunctionContext() const
Definition Sema.h:8235
ASTContext & getASTContext() const
Definition Sema.h:939
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1073
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition SemaExpr.cpp:768
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:756
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition SemaExpr.cpp:887
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:6129
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6131
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:1204
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1679
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:11482
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:510
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:8270
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:934
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8368
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:14537
const LangOptions & getLangOpts() const
Definition Sema.h:932
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
void DiagnoseInvalidJumps(Stmt *Body)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2463
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:1515
ReuseLambdaContextDecl_t
Definition Sema.h:7070
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:1299
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:2141
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:1298
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:2578
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:956
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6555
SemaHLSL & HLSL()
Definition Sema.h:1475
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:15761
ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr)
Prepare SplattedExpr for a matrix splat operation, adding implicit casts if necessary.
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:214
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
Definition Sema.h:5291
ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc, TypeSourceInfo *TSI)
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition SemaExpr.cpp:76
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:7015
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6585
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:14085
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:863
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:1333
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:7012
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2315
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:643
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:8239
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:8106
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2533
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1438
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:12591
SemaOpenCL & OpenCL()
Definition Sema.h:1520
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:14094
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:8231
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1654
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:6814
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:14029
SourceManager & getSourceManager() const
Definition Sema.h:937
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:7525
@ NTCUK_Destruct
Definition Sema.h:4130
@ NTCUK_Copy
Definition Sema.h:4131
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition Sema.h:8384
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:2363
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:6812
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool isSFINAEContext() const
Definition Sema.h:13762
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e....
ExprResult ActOnCXXReflectExpr(SourceLocation OpLoc, TypeSourceInfo *TSI)
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15533
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:2518
bool isConstantEvaluatedContext() const
Definition Sema.h:2631
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:1301
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4689
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:7019
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:124
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1338
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14077
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:6756
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6778
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6768
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6783
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6773
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6793
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6762
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6788
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6803
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:1259
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:8221
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:8371
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:1303
@ TemplateNameIsRequired
Definition Sema.h:11459
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:787
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:1302
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:933
FPOptions CurFPFeatures
Definition Sema.h:1296
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:519
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:1580
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:6589
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:625
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:2124
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
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:8029
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9438
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9444
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9436
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9441
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9452
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9448
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:6470
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition Sema.h:14073
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:7878
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:1535
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2509
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:8247
SemaARM & ARM()
Definition Sema.h:1445
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
SmallVector< std::pair< Scope *, SourceLocation >, 2 > CurrentDefer
Stack of '_Defer' statements that are currently being parsed, as well as the locations of their '_Def...
Definition Sema.h:11025
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:8713
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:5020
SourceLocation getBeginLoc() const
Definition Expr.h:5065
const DeclContext * getParentContext() const
If the SourceLocExpr has been resolved return the subexpression representing the resolved value.
Definition Expr.h:5061
SourceLocation getEndLoc() const
Definition Expr.h:5066
SourceLocIdentKind getIdentKind() const
Definition Expr.h:5040
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:298
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:309
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition Overload.h:396
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4598
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
StmtClass getStmtClass() const
Definition Stmt.h:1485
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1802
unsigned getLength() const
Definition Expr.h:1912
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:1188
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1885
StringRef getString() const
Definition Expr.h:1870
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3818
bool isUnion() const
Definition Decl.h:3928
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:735
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:335
virtual bool useFP16ConversionIntrinsics() const
Check whether conversions to and from __fp16 should go through an integer bitcast with i16.
bool shouldUseMicrosoftCCforMangling() const
Should the Microsoft mangling scheme be used for C Calling Convention.
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
Location wrapper for a TemplateArgument.
Represents a template argument.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Represents a C++ template name within the type system.
A template parameter object.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
void setKind(tok::TokenKind K)
Definition Token.h:100
void startToken()
Reset all flags to cleared.
Definition Token.h:187
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
EnsureImmediateInvocationInDefaultArgs & getDerived()
Represents a declaration of a type.
Definition Decl.h: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:2735
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8359
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:8370
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1839
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2491
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition TypeBase.h:9059
bool isBlockPointerType() const
Definition TypeBase.h:8645
bool isVoidType() const
Definition TypeBase.h:8991
bool isBooleanType() const
Definition TypeBase.h:9128
bool isObjCBuiltinType() const
Definition TypeBase.h:8855
bool isMFloat8Type() const
Definition TypeBase.h:9016
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:1964
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9178
bool isIncompleteArrayType() const
Definition TypeBase.h:8732
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:8967
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:725
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2137
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:9158
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:2083
bool isVoidPointerType() const
Definition Type.cpp:713
const ComplexType * getAsComplexIntegerType() const
Definition Type.cpp:746
bool isArrayType() const
Definition TypeBase.h:8724
bool isCharType() const
Definition Type.cpp:2157
bool isFunctionPointerType() const
Definition TypeBase.h:8692
bool isArithmeticType() const
Definition Type.cpp:2374
bool isConstantMatrixType() const
Definition TypeBase.h:8792
bool isPointerType() const
Definition TypeBase.h:8625
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9035
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2617
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9285
bool isReferenceType() const
Definition TypeBase.h:8649
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:9079
bool isEnumeralType() const
Definition TypeBase.h:8756
bool isScalarType() const
Definition TypeBase.h:9097
bool isVariableArrayType() const
Definition TypeBase.h:8736
bool isSizelessBuiltinType() const
Definition Type.cpp:2575
bool isClkEventT() const
Definition TypeBase.h:8877
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2651
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2120
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8825
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9113
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition Type.cpp:2328
bool isExtVectorType() const
Definition TypeBase.h:8768
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2193
bool isExtVectorBoolType() const
Definition TypeBase.h:8772
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2690
bool isImageType() const
Definition TypeBase.h:8889
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition TypeBase.h:8985
bool isPipeType() const
Definition TypeBase.h:8896
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2798
bool isBitIntType() const
Definition TypeBase.h:8900
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:8960
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8748
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2790
bool isAnyComplexType() const
Definition TypeBase.h:8760
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9051
bool isHalfType() const
Definition TypeBase.h:8995
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9067
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2411
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition Type.cpp:2406
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:8973
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2274
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2601
bool isQueueT() const
Definition TypeBase.h:8881
bool isMemberPointerType() const
Definition TypeBase.h:8706
bool isAtomicType() const
Definition TypeBase.h:8817
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9141
bool isObjCIdType() const
Definition TypeBase.h:8837
bool isMatrixType() const
Definition TypeBase.h:8788
bool isOverflowBehaviorType() const
Definition TypeBase.h:8796
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:2808
bool isComplexIntegerType() const
Definition Type.cpp:731
bool isUnscopedEnumerationType() const
Definition Type.cpp:2150
bool isObjCObjectType() const
Definition TypeBase.h:8808
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition Type.cpp:5297
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9271
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5386
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9134
bool isHLSLResourceRecord() const
Definition Type.cpp:5446
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isDoubleType() const
Definition TypeBase.h:9008
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2479
bool isFunctionType() const
Definition TypeBase.h:8621
bool isObjCObjectPointerType() const
Definition TypeBase.h:8804
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2349
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:9093
bool isVectorType() const
Definition TypeBase.h:8764
bool isObjCQualifiedClassType() const
Definition TypeBase.h:8831
bool isObjCClassType() const
Definition TypeBase.h:8843
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2357
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2638
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2929
@ STK_FloatingComplex
Definition TypeBase.h:2772
@ STK_ObjCObjectPointer
Definition TypeBase.h:2766
@ STK_IntegralComplex
Definition TypeBase.h:2771
@ STK_MemberPointer
Definition TypeBase.h:2767
bool isFloatingType() const
Definition Type.cpp:2341
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:2284
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2936
bool isAnyPointerType() const
Definition TypeBase.h:8633
bool isRealType() const
Definition Type.cpp:2363
TypeClass getTypeClass() const
Definition TypeBase.h:2391
bool isSubscriptableVectorType() const
Definition TypeBase.h:8784
bool isSamplerT() const
Definition TypeBase.h:8869
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9218
bool isNullPtrType() const
Definition TypeBase.h:9028
bool isRecordType() const
Definition TypeBase.h:8752
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5450
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5097
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition Type.cpp:736
bool isUnicodeCharacterType() const
Definition Type.cpp:2213
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Definition Type.cpp:2396
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:2628
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2247
void setSubExpr(Expr *E)
Definition Expr.h:2289
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition Expr.h:2292
Expr * getSubExpr() const
Definition Expr.h:2288
Opcode getOpcode() const
Definition Expr.h:2283
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1430
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2343
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:5133
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4458
Represents a C++ unqualified-id that has been parsed.
Definition DeclSpec.h:1033
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
Definition DeclSpec.h:1121
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1115
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition DeclSpec.h:1085
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3391
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:4127
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:641
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:4960
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:5582
VarDecl * getPotentiallyDecomposedVarDecl()
Definition DeclCXX.cpp:3653
QualType getType() const
Definition Value.cpp:237
Represents a variable declaration or definition.
Definition Decl.h:926
bool hasInit() const
Definition Decl.cpp:2410
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2269
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:2498
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:2919
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:2387
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:2540
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:2812
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:2791
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2910
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:3974
Expr * getSizeExpr() const
Definition TypeBase.h:3988
Represents a GCC generic vector type.
Definition TypeBase.h:4183
unsigned getNumElements() const
Definition TypeBase.h:4198
VectorKind getVectorKind() const
Definition TypeBase.h:4203
QualType getElementType() const
Definition TypeBase.h:4197
Retains information about a block that is currently being parsed.
Definition ScopeInfo.h:794
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition ScopeInfo.h:800
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition ScopeInfo.h:804
ValueDecl * getVariable() const
Definition ScopeInfo.h:679
bool isBlockCapture() const
Definition ScopeInfo.h:660
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:690
void markUsed(bool IsODRUse)
Definition ScopeInfo.h:672
bool isInvalid() const
Definition ScopeInfo.h:665
bool isThisCapture() const
Definition ScopeInfo.h:653
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition ScopeInfo.h:699
bool isCopyCapture() const
Definition ScopeInfo.h:658
bool isNested() const
Definition ScopeInfo.h:663
Retains information about a captured region.
Definition ScopeInfo.h:820
unsigned short CapRegionKind
The kind of captured region.
Definition ScopeInfo.h:835
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:749
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:736
bool ContainsUnexpandedParameterPack
Whether this contains an unexpanded parameter pack.
Definition ScopeInfo.h:732
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:725
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:712
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of 'this'; zero if 'this' is not captured.
Definition ScopeInfo.h:722
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition ScopeInfo.h:762
llvm::DenseMap< ValueDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition ScopeInfo.h:718
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:759
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:741
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition ScopeInfo.h:775
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:1094
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:497
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:888
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:996
void addPotentialThisCapture(SourceLocation Loc)
Definition ScopeInfo.h:1002
llvm::SmallPtrSet< VarDecl *, 4 > CUDAPotentialODRUsedVars
Variables that are potentially ODR-used in CUDA/HIP.
Definition ScopeInfo.h:957
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:875
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition ScopeInfo.h:896
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:883
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:878
#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:93
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:513
bool isTargetAddressSpace(LangAS AS)
CUDAFunctionTarget
Definition Cuda.h:61
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
TryCaptureKind
Definition Sema.h:653
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition Sema.h:661
@ BitwiseOp
A bitwise operation.
Definition Sema.h:665
@ Arithmetic
An arithmetic operation.
Definition Sema.h:663
@ Conditional
A conditional (?:) operator.
Definition Sema.h:669
@ CompAssign
A compound assignment expression.
Definition Sema.h:671
@ Comparison
A comparison.
Definition Sema.h:667
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h: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 of 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 or range of elements 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:1027
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1025
@ 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
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:205
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_Identity
Identity conversion (no conversion)
Definition Overload.h:106
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition Overload.h:136
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition Overload.h:115
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:689
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:712
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition Sema.h:787
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition Sema.h:704
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition Sema.h:759
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition Sema.h:749
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition Sema.h:776
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition Sema.h:763
@ CompatibleOBTDiscards
CompatibleOBTDiscards - Assignment discards overflow behavior.
Definition Sema.h:783
@ IncompatibleOBTKinds
IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType kinds, e....
Definition Sema.h:780
@ CompatibleVoidPtrToNonVoidPtr
CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because a void * can implicitly convert...
Definition Sema.h:696
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition Sema.h:738
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:733
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition Sema.h:772
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:691
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition Sema.h:723
@ IncompatiblePointerDiscardsOverflowBehavior
IncompatiblePointerDiscardsOverflowBehavior - The assignment discards overflow behavior annotations b...
Definition Sema.h:743
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition Sema.h:700
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition Sema.h:708
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition Sema.h:755
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition Sema.h:717
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:729
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition Sema.h:767
bool isFunctionLocalStringLiteralMacro(tok::TokenKind K, const LangOptions &LO)
Return true if the token corresponds to a function local predefined macro, which expands to a string ...
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:564
@ AR_Unavailable
Definition DeclBase.h:76
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
AllowFoldKind
Definition Sema.h:655
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
VarArgKind
Definition Sema.h:676
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition ASTLambda.h:69
AssignmentAction
Definition Sema.h:216
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Concept_template
The name refers to a concept.
BuiltinCountedByRefKind
Definition Sema.h:521
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h: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:150
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:276
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:282
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:290
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:279
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:286
StringLiteralKind
Definition Expr.h:1766
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:4153
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4162
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4147
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4150
@ Neon
is ARM Neon vector
Definition TypeBase.h:4156
@ Generic
not a target-specific vector type
Definition TypeBase.h:4144
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4168
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4171
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4165
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:5007
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5935
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:1992
@ Implicit
An implicit conversion.
Definition Sema.h:440
CharacterLiteralKind
Definition Expr.h:1606
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.
SourceLocation getEndLoc() const LLVM_READONLY
Stores data related to a single embed directive.
Definition Expr.h:5096
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:648
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:650
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:636
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition Expr.h:620
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
Extra information about a function prototype.
Definition TypeBase.h:5400
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13185
Data structure used to record current or nested expression evaluation contexts.
Definition Sema.h:6818
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition Sema.h:6853
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6904
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition Sema.h:6838
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition Sema.h:6858
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:6866
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition Sema.h:6862
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6872
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:6833
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:6880
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition Sema.h:6823
ExpressionEvaluationContext Context
The expression evaluation context.
Definition Sema.h:6820
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition Sema.h:6827
Abstract class used to diagnose incomplete types.
Definition Sema.h:8312
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.